[libjogl2-java] 22/58: Imported Upstream version 2.0-rc8

Tony Mancill tmancill at moszumanska.debian.org
Thu Sep 4 03:59:12 UTC 2014


This is an automated email from the git hooks/post-receive script.

tmancill pushed a commit to branch master
in repository libjogl2-java.

commit 8d5d8b6c65a0185d10b5f59c5980da0c692e959e
Author: tony mancill <tmancill at debian.org>
Date:   Fri Aug 29 18:43:39 2014 -0700

    Imported Upstream version 2.0-rc8
---
 .classpath                                         |    3 +-
 .externalToolBuilders/jogl builder.launch          |    5 -
 LICENSE.txt                                        |   27 +-
 doc/Platform.Applets.txt                           |   23 +
 doc/Platform.GLES.txt                              |  112 +
 doc/Platforms.txt                                  |   62 +
 doc/userguide/index.html                           | 1051 +++--
 etc/profile.jogl                                   |    4 +-
 ...nner-newt-ElektronenMultiplizierer-napplet.html |    2 -
 ...pplet-runner-newt-ElektronenMultiplizierer.html |    2 -
 ...applet-runner-newt-GraphTextDemo01-napplet.html |    2 -
 .../jogl-applet-runner-newt-GraphTextDemo01.html   |    2 -
 ...let-runner-newt-GraphUISceneDemo01-napplet.html |    2 -
 ...jogl-applet-runner-newt-GraphUISceneDemo01.html |    2 -
 ...jogl-applet-runner-newt-MovieCube-napplet.html} |   26 +-
 ...html => jogl-applet-runner-newt-MovieCube.html} |   33 +-
 ...plet-runner-newt-gears-normal-launcheronly.html |    8 +-
 ...gl-applet-runner-newt-gears-normal-napplet.html |    4 -
 ...-applet-runner-newt-gears-normal-napplet2.html} |   11 +-
 .../jogl-applet-runner-newt-gears-normal.html      |    5 -
 ...l-applet-runner-newt-gears-special-napplet.html |    2 -
 .../jogl-applet-runner-newt-gears-special.html     |    2 -
 jnlp-files/jogl-applet-runner-newt.jnlp            |    1 -
 jnlp-files/jogl-test-applets.html                  |   17 +-
 make/build-common.xml                              |   39 +-
 make/build-jogl.xml                                |  223 +-
 make/build-nativewindow.xml                        |  119 +-
 make/build-newt.xml                                |   86 +-
 make/build-staticglgen.xml                         |   12 +-
 make/build-test.xml                                |  474 +-
 make/build.xml                                     |   73 +-
 make/config/jogl/cg-common.cfg                     |    1 +
 make/config/jogl/egl-common.cfg                    |    8 +-
 make/config/jogl/gl-common-extensions.cfg          |   34 +-
 make/config/jogl/gl-common.cfg                     |   74 +-
 make/config/jogl/gl-es1.cfg                        |    6 +-
 make/config/jogl/gl-es2.cfg                        |    4 +-
 make/config/jogl/gl-gl4bc.cfg                      |   14 +-
 make/config/jogl/gl-if-CustomJavaCode-gl2_es2.java |    2 +
 make/config/jogl/gl-if-CustomJavaCode-gl2_gl3.java |    2 +
 make/config/jogl/gl-if-gl-ignores.cfg              |  133 +-
 make/config/jogl/gl-if-gl.cfg                      |    5 +-
 make/config/jogl/gl-if-gl2.cfg                     |   16 +-
 make/config/jogl/gl-if-gl2_es1.cfg                 |    9 +-
 make/config/jogl/gl-if-gl2_es2.cfg                 |    9 +-
 make/config/jogl/gl-if-gl2_gl3.cfg                 |   11 +-
 make/config/jogl/gl-if-gl3-ignores.cfg             |    2 +-
 make/config/jogl/gl-if-gl3-subset.cfg              |    2 +
 make/config/jogl/gl-if-gl3.cfg                     |   11 +-
 make/config/jogl/gl-if-gl3bc.cfg                   |   13 +-
 make/config/jogl/gl-if-gl4.cfg                     |   11 +-
 .../config/jogl/gl-impl-CustomJavaCode-common.java |   11 +-
 .../jogl/gl-impl-CustomJavaCode-desktop.java       |    3 +
 make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java |    2 +-
 make/config/jogl/gl-impl-CustomJavaCode-gles1.java |    6 +-
 make/config/jogl/gl-impl-CustomJavaCode-gles2.java |    6 +-
 make/config/jogl/glu-common.cfg                    |    1 +
 make/config/jogl/wgl-win32.cfg                     |    5 +
 make/config/nativewindow/jawt-CustomJavaCode.java  |   35 +-
 .../jawt-DrawingSurfaceInfo-CustomJavaCode.java    |    2 +-
 make/config/nativewindow/x11-CustomJavaCode.java   |    2 +-
 make/config/nativewindow/x11-lib.cfg               |    2 +
 .../resources/android/AndroidManifest-launcher.xml |  130 -
 make/resources/android/AndroidManifest-test.xml    |  143 +
 .../{res-launcher => res-jogl}/values/colors.xml   |    0
 .../{res-launcher => res-jogl}/values/styles.xml   |    0
 .../drawable-hdpi/icon.png                         |  Bin
 .../drawable-ldpi/icon.png                         |  Bin
 .../drawable-mdpi/icon.png                         |  Bin
 .../{res-launcher => res-test}/layout/main.xml     |    0
 .../{res-launcher => res-test}/values/strings.xml  |   14 +-
 make/resources/assets-test/placeholder.txt         |    1 +
 .../jogl/util/data/av/test-ntsc01-160x90.png       |  Bin 0 -> 2785 bytes
 ...adb-install-all.sh => adb-install-all-armv7.sh} |    2 +-
 make/scripts/adb-launch-activity.sh                |   11 +
 make/scripts/adb-launch-main.sh                    |   69 +
 make/scripts/adb-power-alwayson.sh                 |    3 +
 ...reinstall-all.sh => adb-reinstall-all-armv7.sh} |    2 +-
 make/scripts/adb-uninstall-all.sh                  |    2 +-
 make/scripts/check-java-major-version.sh           |   27 +
 make/scripts/crosstest-java-android-armv7-rel.sh   |   69 -
 make/scripts/crosstest-launch-android-activity.sh  |   17 -
 make/scripts/gluegen-gl.sh                         |   93 +
 make/scripts/java-win32-dbg.bat                    |   24 +-
 make/scripts/java-win32.bat                        |   16 +-
 make/scripts/java-win64-dbg.bat                    |   28 +-
 make/scripts/java-win64.bat                        |    9 +-
 make/scripts/make.jogl.all.android-armv7-cross.sh  |  104 +-
 make/scripts/make.jogl.all.linux-armv7-cross.sh    |   32 +-
 make/scripts/make.jogl.all.linux-armv7.sh          |   27 +
 make/scripts/make.jogl.all.linux-armv7hf-cross.sh  |   51 +
 make/scripts/make.jogl.all.linux-x86_64.sh         |    8 +
 make/scripts/make.jogl.all.macosx.sh               |   12 +-
 make/scripts/make.jogl.all.win32.bat               |    4 +-
 make/scripts/make.jogl.all.win64.bat               |    4 +-
 make/scripts/targetcommand-awt.sh                  |   59 +
 make/scripts/targetcommand-newt.sh                 |  124 +
 make/scripts/tests-javaws-x64.bat                  |    2 +-
 make/scripts/tests-linux-armv7.sh                  |    7 +
 make/scripts/tests-linux-armv7hf.sh                |    7 +
 make/scripts/tests-osx-x32.sh                      |    7 +
 make/scripts/tests-osx-x64.sh                      |    2 +
 make/scripts/tests-x32.bat                         |   78 +-
 make/scripts/tests-x64.bat                         |   46 +-
 make/scripts/tests-x64.sh                          |    2 +
 make/scripts/tests.sh                              |  112 +-
 make/stub_includes/egl/EGL/egl.h                   |    8 +-
 make/stub_includes/egl/EGL/eglext.h                |   76 +-
 make/stub_includes/egl/EGL/eglplatform.h           |    6 +-
 make/stub_includes/libav/libavcodec/avcodec.h      | 4761 ++++++++++++++++++++
 make/stub_includes/libav/libavcodec/avfft.h        |   99 +
 make/stub_includes/libav/libavcodec/dxva2.h        |   71 +
 make/stub_includes/libav/libavcodec/opt.h          |   34 +
 make/stub_includes/libav/libavcodec/vaapi.h        |  167 +
 make/stub_includes/libav/libavcodec/vda.h          |  144 +
 make/stub_includes/libav/libavcodec/vdpau.h        |   88 +
 make/stub_includes/libav/libavcodec/version.h      |  126 +
 make/stub_includes/libav/libavcodec/xvmc.h         |  151 +
 make/stub_includes/libav/libavformat/avformat.h    | 2026 +++++++++
 make/stub_includes/libav/libavformat/avio.h        |  688 +++
 make/stub_includes/libav/libavformat/version.h     |  126 +
 make/stub_includes/libav/libavutil/adler32.h       |   43 +
 make/stub_includes/libav/libavutil/aes.h           |   57 +
 make/stub_includes/libav/libavutil/attributes.h    |  136 +
 make/stub_includes/libav/libavutil/audioconvert.h  |  130 +
 make/stub_includes/libav/libavutil/avassert.h      |   66 +
 make/stub_includes/libav/libavutil/avconfig.h      |    6 +
 make/stub_includes/libav/libavutil/avstring.h      |  175 +
 make/stub_includes/libav/libavutil/avutil.h        |  326 ++
 make/stub_includes/libav/libavutil/base64.h        |   65 +
 make/stub_includes/libav/libavutil/bswap.h         |  109 +
 make/stub_includes/libav/libavutil/common.h        |  398 ++
 make/stub_includes/libav/libavutil/cpu.h           |   56 +
 make/stub_includes/libav/libavutil/crc.h           |   44 +
 make/stub_includes/libav/libavutil/dict.h          |  121 +
 make/stub_includes/libav/libavutil/error.h         |   81 +
 make/stub_includes/libav/libavutil/eval.h          |  113 +
 make/stub_includes/libav/libavutil/fifo.h          |  141 +
 make/stub_includes/libav/libavutil/file.h          |   52 +
 make/stub_includes/libav/libavutil/imgutils.h      |  138 +
 make/stub_includes/libav/libavutil/intfloat.h      |   73 +
 .../libav/libavutil/intfloat_readwrite.h           |   40 +
 make/stub_includes/libav/libavutil/intreadwrite.h  |  522 +++
 make/stub_includes/libav/libavutil/lfg.h           |   62 +
 make/stub_includes/libav/libavutil/log.h           |  172 +
 make/stub_includes/libav/libavutil/lzo.h           |   77 +
 make/stub_includes/libav/libavutil/mathematics.h   |  122 +
 make/stub_includes/libav/libavutil/md5.h           |   46 +
 make/stub_includes/libav/libavutil/mem.h           |  136 +
 make/stub_includes/libav/libavutil/opt.h           |  591 +++
 make/stub_includes/libav/libavutil/parseutils.h    |  124 +
 make/stub_includes/libav/libavutil/pixdesc.h       |  177 +
 make/stub_includes/libav/libavutil/pixfmt.h        |  198 +
 make/stub_includes/libav/libavutil/random_seed.h   |   44 +
 make/stub_includes/libav/libavutil/rational.h      |  144 +
 make/stub_includes/libav/libavutil/samplefmt.h     |  148 +
 make/stub_includes/libav/libavutil/sha.h           |   66 +
 make/stub_includes/opengl/GL/glext.h               |  523 ++-
 make/stub_includes/opengl/GL3/gl3.h                |  385 +-
 make/stub_includes/opengl/GL3/gl3ext.h             |  236 +-
 make/stub_includes/opengl/GLES/glext.h             |  129 +-
 make/stub_includes/opengl/GLES2/gl2.h              |    2 +-
 make/stub_includes/opengl/GLES2/gl2ext.h           |  591 ++-
 make/stub_includes/opengl/macosx-window-system.h   |    5 +-
 make/stub_includes/win32/windows.h                 |   10 -
 make/stub_includes/win32/wingdi.h                  |  165 +-
 .../win32/{wingdi.h => wingdi_types.h}             |   73 +-
 make/stub_includes/win32/winwgl.h                  |   11 +-
 make/stub_includes/x11/window-lib.c                |    5 +-
 .../jogamp/android/launcher/ClassLoaderUtil.java   |  121 -
 .../android/launcher/LauncherTempFileCache.java    |  477 --
 .../android/launcher/NEWTLauncherActivity.java     |  254 --
 .../launcher/NEWTLauncherElektronActivity.java     |   15 -
 .../launcher/NEWTLauncherGearsES1Activity.java     |   15 -
 .../launcher/NEWTLauncherGearsES2Activity.java     |   15 -
 .../NEWTLauncherGearsES2TransActivity.java         |   15 -
 .../launcher/NEWTLauncherGraphUI1pActivity.java    |   15 -
 .../launcher/NEWTLauncherGraphUI2pActivity.java    |   15 -
 .../launcher/NEWTLauncherRedSquareES1Activity.java |   15 -
 .../launcher/NEWTLauncherRedSquareES2Activity.java |   15 -
 .../gluegen/opengl/BuildComposablePipeline.java    |    6 +-
 .../jogamp/gluegen/opengl/BuildStaticGLInfo.java   |   24 +-
 .../com/jogamp/gluegen/opengl/GLConfiguration.java |   22 +-
 .../com/jogamp/gluegen/opengl/GLEmitter.java       |   84 +-
 .../gluegen/opengl/GLJavaMethodBindingEmitter.java |    5 +-
 .../opengl/nativesig/NativeSignatureEmitter.java   |    2 +
 .../NativeSignatureJavaMethodBindingEmitter.java   |   17 +-
 .../com/jogamp/graph/curve/opengl/GLRegion.java    |   10 +-
 .../jogamp/graph/curve/opengl/RegionRenderer.java  |   11 +-
 .../jogamp/graph/curve/opengl/TextRenderer.java    |    5 +-
 .../classes/com/jogamp/graph/font/FontFactory.java |   14 +-
 .../classes/com/jogamp/graph/font/FontSet.java     |    6 +-
 src/jogl/classes/com/jogamp/opengl/FloatUtil.java  |  289 ++
 .../classes/com/jogamp/opengl/JoglVersion.java     |   77 +-
 .../opengl/cg/CgDynamicLibraryBundleInfo.java      |   14 +
 .../classes/com/jogamp/opengl/swt/GLCanvas.java    |  563 +++
 .../classes/com/jogamp/opengl/util/Animator.java   |   15 +-
 .../com/jogamp/opengl/util/AnimatorBase.java       |    4 +-
 .../classes/com/jogamp/opengl/util/FBObject.java   |   27 +-
 .../com/jogamp/opengl/util/GLArrayDataClient.java  |   51 +-
 .../com/jogamp/opengl/util/GLArrayDataServer.java  |   61 +-
 .../com/jogamp/opengl/util/GLArrayDataWrapper.java |   28 +-
 .../classes/com/jogamp/opengl/util/GLBuffers.java  |    2 +-
 .../com/jogamp/opengl/util/GLReadBufferUtil.java   |   57 +-
 .../com/jogamp/opengl/util/ImmModeSink.java        |   70 +-
 .../classes/com/jogamp/opengl/util/PMVMatrix.java  |  233 +-
 .../com/jogamp/opengl/util/av/GLMediaPlayer.java   |  248 +
 .../opengl/util/av/GLMediaPlayerFactory.java}      |   54 +-
 .../classes/com/jogamp/opengl/util/av/package.html |   25 +
 .../com/jogamp/opengl/util/awt/TextRenderer.java   |   10 +-
 .../com/jogamp/opengl/util/glsl/ShaderCode.java    |  659 ++-
 .../com/jogamp/opengl/util/glsl/ShaderProgram.java |   25 +-
 .../com/jogamp/opengl/util/glsl/ShaderState.java   |   78 +-
 .../com/jogamp/opengl/util/glsl/ShaderUtil.java    |  618 ++-
 .../jogamp/opengl/util/glsl/sdk/CompileShader.java |    9 +-
 .../com/jogamp/opengl/util/texture/Texture.java    |   39 +-
 .../jogamp/opengl/util/texture/TextureCoords.java  |   18 +
 .../jogamp/opengl/util/texture/TextureData.java    |    2 +-
 .../com/jogamp/opengl/util/texture/TextureIO.java  |  187 +-
 .../opengl/util/texture/TextureSequence.java       |  221 +
 .../opengl/util/texture/awt/AWTTextureData.java    |    6 +-
 .../jogamp/opengl/util/texture/spi/DDSImage.java   |   26 +-
 .../util/texture/spi/NetPbmTextureWriter.java      |   80 +-
 .../jogamp/opengl/util/texture/spi/PNGImage.java   |  172 +
 .../jogamp/opengl/util/texture/spi/SGIImage.java   |    5 +-
 .../jogamp/opengl/util/texture/spi/TGAImage.java   |   40 +-
 .../com/jogamp/openmax/OMXEventListener.java       |   14 -
 .../classes/com/jogamp/openmax/OMXInstance.java    |  509 ---
 .../media/opengl/DefaultGLCapabilitiesChooser.java |   36 +-
 .../classes/javax/media/opengl/GLArrayData.java    |    7 +-
 .../classes/javax/media/opengl/GLAutoDrawable.java |   11 +-
 src/jogl/classes/javax/media/opengl/GLBase.java    |   73 +-
 .../classes/javax/media/opengl/GLCapabilities.java |    6 +-
 src/jogl/classes/javax/media/opengl/GLContext.java |  441 +-
 .../javax/media/opengl/GLDrawableFactory.java      |   38 +-
 .../javax/media/opengl/GLPipelineFactory.java      |    2 +-
 src/jogl/classes/javax/media/opengl/GLProfile.java |  596 ++-
 .../classes/javax/media/opengl/GLRunnable.java     |   14 +-
 .../classes/javax/media/opengl/GLUniformData.java  |    6 +-
 src/jogl/classes/javax/media/opengl/Threading.java |   60 +-
 .../classes/javax/media/opengl/awt/GLCanvas.java   |  386 +-
 .../classes/javax/media/opengl/awt/GLJPanel.java   |  318 +-
 .../graph/curve/opengl/RegionRendererImpl01.java   |   12 +-
 .../graph/curve/opengl/TextRendererImpl01.java     |   13 +-
 .../jogamp/graph/curve/opengl/VBORegion2PES2.java  |   42 +-
 .../jogamp/graph/curve/opengl/VBORegionSPES2.java  |   10 +-
 .../jogamp/graph/curve/text/GlyphString.java       |   13 +-
 .../classes/jogamp/graph/font/FontConstructor.java |    4 +-
 .../classes/jogamp/graph/font/JavaFontLoader.java  |   10 +-
 .../jogamp/graph/font/UbuntuFontLoader.java        |   19 +-
 .../font/typecast/TypecastFontConstructor.java     |   26 +-
 .../graph/font/typecast/ot/Disassembler.java       |    2 +-
 .../graph/font/typecast/ot/OTFontCollection.java   |    2 +-
 .../graph/font/typecast/ot/mac/ResourceType.java   |    2 +-
 .../graph/font/typecast/ot/table/BaseTable.java    |   10 +-
 .../graph/font/typecast/ot/table/CffTable.java     |   18 +-
 .../font/typecast/ot/table/CharstringType2.java    |    4 +-
 .../graph/font/typecast/ot/table/CmapFormat.java   |    2 +-
 .../graph/font/typecast/ot/table/CmapFormat4.java  |    2 +-
 .../font/typecast/ot/table/CmapIndexEntry.java     |    2 +-
 .../graph/font/typecast/ot/table/CmapTable.java    |    2 +-
 .../graph/font/typecast/ot/table/CvtTable.java     |    2 +-
 .../font/typecast/ot/table/DirectoryEntry.java     |    4 +-
 .../graph/font/typecast/ot/table/DsigTable.java    |    2 +-
 .../font/typecast/ot/table/FeatureRecord.java      |    2 +-
 .../graph/font/typecast/ot/table/GaspRange.java    |    2 +-
 .../graph/font/typecast/ot/table/GaspTable.java    |    2 +-
 .../graph/font/typecast/ot/table/GlyfDescript.java |    2 +-
 .../font/typecast/ot/table/GlyfSimpleDescript.java |    2 +-
 .../graph/font/typecast/ot/table/HdmxTable.java    |    2 +-
 .../graph/font/typecast/ot/table/HeadTable.java    |    2 +-
 .../graph/font/typecast/ot/table/HheaTable.java    |    2 +-
 .../graph/font/typecast/ot/table/HmtxTable.java    |    2 +-
 .../font/typecast/ot/table/LangSysRecord.java      |    2 +-
 .../graph/font/typecast/ot/table/LocaTable.java    |    2 +-
 .../graph/font/typecast/ot/table/LtshTable.java    |    2 +-
 .../graph/font/typecast/ot/table/MaxpTable.java    |    2 +-
 .../graph/font/typecast/ot/table/NameRecord.java   |    4 +-
 .../graph/font/typecast/ot/table/Os2Table.java     |    4 +-
 .../graph/font/typecast/ot/table/Panose.java       |    2 +-
 .../graph/font/typecast/ot/table/PcltTable.java    |    2 +-
 .../graph/font/typecast/ot/table/PostTable.java    |    2 +-
 .../graph/font/typecast/ot/table/ScriptRecord.java |    2 +-
 .../font/typecast/ot/table/SignatureBlock.java     |    2 +-
 .../font/typecast/ot/table/TableDirectory.java     |    2 +-
 .../graph/font/typecast/ot/table/VdmxTable.java    |    2 +-
 .../graph/font/typecast/ot/table/VheaTable.java    |    2 +-
 .../graph/font/typecast/ot/table/VmtxTable.java    |    2 +-
 .../graph/font/typecast/t2/T2Interpreter.java      |    6 +-
 .../graph/font/typecast/tt/engine/Parser.java      |    2 +-
 src/jogl/classes/jogamp/opengl/Debug.java          |   82 +-
 .../opengl/DesktopGLDynamicLibraryBundleInfo.java  |    3 +-
 .../jogamp/opengl/ExtensionAvailabilityCache.java  |  196 +-
 src/jogl/classes/jogamp/opengl/GLContextImpl.java  |  575 ++-
 .../jogamp/opengl/GLDrawableFactoryImpl.java       |    3 +-
 .../classes/jogamp/opengl/GLDrawableHelper.java    |  201 +-
 src/jogl/classes/jogamp/opengl/GLDrawableImpl.java |    8 +-
 .../jogamp/opengl/GLDynamicLibraryBundleInfo.java  |   18 +-
 .../jogamp/opengl/GLGraphicsConfigurationUtil.java |    4 +-
 src/jogl/classes/jogamp/opengl/GLPbufferImpl.java  |   21 +-
 src/jogl/classes/jogamp/opengl/GLWorkerThread.java |   33 +-
 src/jogl/classes/jogamp/opengl/MemoryObject.java   |    4 +-
 src/jogl/classes/jogamp/opengl/ProjectFloat.java   |  496 +-
 .../jogamp/opengl/SharedResourceRunner.java        |    4 +-
 src/jogl/classes/jogamp/opengl/ThreadingImpl.java  |  154 +-
 ...dingPlugin.java => ToolkitThreadingPlugin.java} |   11 +-
 .../android/av/AndroidGLMediaPlayerAPI14.java      |  262 ++
 .../jogamp/opengl/awt/AWTThreadingPlugin.java      |   55 +-
 src/jogl/classes/jogamp/opengl/awt/AWTUtil.java    |   20 +-
 src/jogl/classes/jogamp/opengl/awt/Java2D.java     |   73 +-
 .../DesktopES2DynamicLibraryBundleInfo.java}       |   82 +-
 src/jogl/classes/jogamp/opengl/egl/EGLContext.java |   90 +-
 .../classes/jogamp/opengl/egl/EGLDisplayUtil.java  |  133 +
 .../classes/jogamp/opengl/egl/EGLDrawable.java     |  123 +-
 .../jogamp/opengl/egl/EGLDrawableFactory.java      |  157 +-
 .../opengl/egl/EGLDynamicLibraryBundleInfo.java    |   36 +-
 .../opengl/egl/EGLES1DynamicLibraryBundleInfo.java |    7 +-
 .../opengl/egl/EGLES2DynamicLibraryBundleInfo.java |    7 +-
 .../jogamp/opengl/egl/EGLExternalContext.java      |    2 +-
 .../jogamp/opengl/egl/EGLGLCapabilities.java       |   61 +-
 .../opengl/egl/EGLGraphicsConfiguration.java       |   72 +-
 .../egl/EGLGraphicsConfigurationFactory.java       |  255 +-
 src/jogl/classes/jogamp/opengl/gl2/Util.java       |  244 -
 .../classes/jogamp/opengl/glu/mipmap/Mipmap.java   |    8 +-
 .../jogamp/opengl/macosx/cgl/MacOSXCGLContext.java |   71 +-
 .../opengl/macosx/cgl/MacOSXCGLDrawable.java       |    4 +-
 .../macosx/cgl/MacOSXCGLDrawableFactory.java       |   50 +-
 .../cgl/MacOSXCGLDynamicLibraryBundleInfo.java     |    3 +
 .../macosx/cgl/MacOSXCGLGraphicsConfiguration.java |   27 +-
 .../cgl/MacOSXCGLGraphicsConfigurationFactory.java |    4 +-
 .../macosx/cgl/MacOSXExternalCGLContext.java       |    5 +-
 .../macosx/cgl/MacOSXPbufferCGLDrawable.java       |    8 +-
 .../MacOSXAWTCGLGraphicsConfigurationFactory.java  |   13 +-
 .../macosx/cgl/awt/MacOSXJava2DCGLContext.java     |    2 +-
 .../jogamp/opengl/util/av/EGLMediaPlayerImpl.java  |  169 +
 .../jogamp/opengl/util/av/GLMediaPlayerImpl.java   |  575 +++
 .../jogamp/opengl/util/av/NullGLMediaPlayer.java   |  173 +
 .../av/impl/FFMPEGDynamicLibraryBundleInfo.java    |  270 ++
 .../opengl/util/av/impl/FFMPEGMediaPlayer.java     |  544 +++
 .../opengl/util/av/impl/OMXGLMediaPlayer.java      |  228 +
 .../opengl/util/glsl/fixedfunc/FixedFuncHook.java  |   15 +-
 .../util/glsl/fixedfunc/FixedFuncPipeline.java     |   27 +-
 .../jogamp/opengl/util/pngj/FilterType.java        |   94 +
 .../opengl/util/pngj/FilterWriteStrategy.java      |   97 +
 .../classes/jogamp/opengl/util/pngj/ImageInfo.java |  208 +
 .../classes/jogamp/opengl/util/pngj/ImageLine.java |  175 +
 .../classes/jogamp/opengl/util/pngj/PngHelper.java |  213 +
 .../opengl/util/pngj/PngIDatChunkInputStream.java  |  153 +
 .../opengl/util/pngj/PngIDatChunkOutputStream.java |   31 +
 .../classes/jogamp/opengl/util/pngj/PngReader.java |  415 ++
 .../classes/jogamp/opengl/util/pngj/PngWriter.java |  462 ++
 .../opengl/util/pngj/PngjBadCrcException.java      |   20 +
 .../jogamp/opengl/util/pngj/PngjException.java     |   23 +
 .../opengl/util/pngj/PngjInputException.java       |   20 +
 .../opengl/util/pngj/PngjOutputException.java      |   20 +
 .../opengl/util/pngj/PngjUnsupportedException.java |   24 +
 .../opengl/util/pngj/ProgressiveOutputStream.java  |   71 +
 .../util/pngj/chunks/ChunkCopyBehaviour.java       |   24 +
 .../opengl/util/pngj/chunks/ChunkHelper.java       |  134 +
 .../jogamp/opengl/util/pngj/chunks/ChunkList.java  |  282 ++
 .../util/pngj/chunks/ChunkLoadBehaviour.java       |   10 +
 .../jogamp/opengl/util/pngj/chunks/ChunkRaw.java   |   83 +
 .../jogamp/opengl/util/pngj/chunks/PngChunk.java   |  152 +
 .../opengl/util/pngj/chunks/PngChunkBKGD.java      |  122 +
 .../opengl/util/pngj/chunks/PngChunkCHRM.java      |   88 +
 .../opengl/util/pngj/chunks/PngChunkGAMA.java      |   56 +
 .../opengl/util/pngj/chunks/PngChunkHIST.java      |   67 +
 .../opengl/util/pngj/chunks/PngChunkICCP.java      |   85 +
 .../opengl/util/pngj/chunks/PngChunkIDAT.java      |   25 +
 .../opengl/util/pngj/chunks/PngChunkIEND.java      |   26 +
 .../opengl/util/pngj/chunks/PngChunkIHDR.java      |  126 +
 .../opengl/util/pngj/chunks/PngChunkITXT.java      |  119 +
 .../opengl/util/pngj/chunks/PngChunkPHYS.java      |  108 +
 .../opengl/util/pngj/chunks/PngChunkPLTE.java      |   93 +
 .../opengl/util/pngj/chunks/PngChunkSBIT.java      |  124 +
 .../opengl/util/pngj/chunks/PngChunkSPLT.java      |  139 +
 .../opengl/util/pngj/chunks/PngChunkSRGB.java      |   61 +
 .../opengl/util/pngj/chunks/PngChunkTEXT.java      |   34 +
 .../opengl/util/pngj/chunks/PngChunkTIME.java      |   83 +
 .../opengl/util/pngj/chunks/PngChunkTRNS.java      |  129 +
 .../opengl/util/pngj/chunks/PngChunkTextVar.java   |   61 +
 .../opengl/util/pngj/chunks/PngChunkUNKNOWN.java   |   51 +
 .../opengl/util/pngj/chunks/PngChunkZTXT.java      |   62 +
 .../opengl/util/pngj/chunks/PngMetadata.java       |  135 +
 .../jogamp/opengl/util/pngj/chunks/package.html    |    9 +
 .../classes/jogamp/opengl/util/pngj/package.html   |   11 +
 .../opengl/windows/wgl/WGLGLCapabilities.java      |   56 +-
 .../classes/jogamp/opengl/windows/wgl/WGLUtil.java |   95 +
 .../windows/wgl/WindowsDummyWGLDrawable.java       |    2 +-
 .../windows/wgl/WindowsExternalWGLContext.java     |    9 +-
 .../windows/wgl/WindowsExternalWGLDrawable.java    |    5 +-
 .../windows/wgl/WindowsOnscreenWGLDrawable.java    |    1 -
 .../opengl/windows/wgl/WindowsWGLContext.java      |   36 +-
 .../opengl/windows/wgl/WindowsWGLDrawable.java     |   28 +-
 .../windows/wgl/WindowsWGLDrawableFactory.java     |   47 +-
 .../wgl/WindowsWGLDynamicLibraryBundleInfo.java    |    3 +
 .../wgl/WindowsWGLGraphicsConfiguration.java       |   36 +-
 .../WindowsWGLGraphicsConfigurationFactory.java    |   32 +-
 .../WindowsAWTWGLGraphicsConfigurationFactory.java |  115 +-
 .../classes/jogamp/opengl/x11/glx/GLXUtil.java     |   35 +-
 .../jogamp/opengl/x11/glx/X11DummyGLXDrawable.java |    7 +-
 .../opengl/x11/glx/X11ExternalGLXContext.java      |   19 +-
 .../opengl/x11/glx/X11ExternalGLXDrawable.java     |   13 +-
 .../jogamp/opengl/x11/glx/X11GLCapabilities.java   |   69 +-
 .../jogamp/opengl/x11/glx/X11GLXContext.java       |   98 +-
 .../jogamp/opengl/x11/glx/X11GLXDrawable.java      |    2 +-
 .../opengl/x11/glx/X11GLXDrawableFactory.java      |   57 +-
 .../x11/glx/X11GLXDynamicLibraryBundleInfo.java    |    4 +
 .../x11/glx/X11GLXGraphicsConfiguration.java       |   25 +-
 .../glx/X11GLXGraphicsConfigurationFactory.java    |   49 +-
 .../opengl/x11/glx/X11OnscreenGLXDrawable.java     |    4 +-
 src/jogl/native/JoglCommon.c                       |  124 +-
 src/jogl/native/JoglCommon.h                       |   36 +
 src/jogl/native/libav/ffmpeg_tool.h                |  106 +
 .../jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c |  717 +++
 .../macosx/MacOSXWindowSystemInterface-pbuffer.m   |  112 +-
 .../native/macosx/MacOSXWindowSystemInterface.m    |   65 +-
 .../native/openmax/com_sun_openmax_OMXInstance.c   |  255 --
 .../jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c  |  208 +
 src/jogl/native/openmax/omx_tool.c                 |  152 +-
 src/jogl/native/openmax/omx_tool.h                 |   26 +-
 src/jogl/native/timespec.c                         |   14 +
 src/jogl/native/timespec.h                         |    1 +
 .../nativewindow/MutableGraphicsConfiguration.java |    2 +-
 .../jogamp/nativewindow/WrappedSurface.java        |   16 +-
 .../nativewindow/awt/AWTGraphicsConfiguration.java |    2 +-
 .../nativewindow/awt/AWTGraphicsDevice.java        |    2 +-
 .../nativewindow/awt/AWTGraphicsScreen.java        |    4 +-
 .../nativewindow/awt/AWTWindowClosingProtocol.java |   23 +-
 .../jogamp/nativewindow/awt}/JAWTWindow.java       |   34 +-
 .../nativewindow/egl/EGLGraphicsDevice.java        |    2 +-
 .../nativewindow/macosx/MacOSXGraphicsDevice.java  |    2 +-
 .../jogamp/nativewindow/swt/SWTAccessor.java       |    8 +-
 .../windows/WindowsGraphicsDevice.java             |    2 +-
 .../nativewindow/x11/X11GraphicsConfiguration.java |   15 +-
 .../nativewindow/x11/X11GraphicsDevice.java        |    3 +-
 .../nativewindow/x11/X11GraphicsScreen.java        |    5 +-
 .../AbstractGraphicsConfiguration.java             |    2 +-
 .../media/nativewindow/AbstractGraphicsDevice.java |    4 +-
 .../javax/media/nativewindow/Capabilities.java     |   20 +-
 .../media/nativewindow/CapabilitiesImmutable.java  |    4 +-
 .../nativewindow/DefaultCapabilitiesChooser.java   |    3 +-
 .../nativewindow/DefaultGraphicsConfiguration.java |   26 +-
 .../nativewindow/GraphicsConfigurationFactory.java |   99 +-
 .../javax/media/nativewindow/NativeSurface.java    |   38 +-
 .../media/nativewindow/NativeWindowFactory.java    |   83 +-
 .../javax/media/nativewindow/ProxySurface.java     |   14 +
 .../javax/media/nativewindow/ToolkitLock.java      |    3 +-
 .../javax/media/nativewindow/VisualIDHolder.java   |  135 +
 .../media/nativewindow/WindowClosingProtocol.java  |   39 +-
 .../classes/jogamp/nativewindow/Debug.java         |   83 +-
 .../jogamp/nativewindow/NWJNILibLoader.java        |   11 +-
 .../nativewindow/NativeWindowFactoryImpl.java      |    5 +-
 .../classes/jogamp/nativewindow/awt/AWTMisc.java   |   12 +-
 .../jogamp/nativewindow/jawt/JAWTToolkitLock.java  |   54 -
 .../classes/jogamp/nativewindow/jawt/JAWTUtil.java |  100 +-
 .../nativewindow/jawt/macosx/MacOSXJAWTWindow.java |   31 +-
 .../jawt/windows/Win32SunJDKReflection.java        |    4 +-
 .../jawt/windows/WindowsJAWTWindow.java            |    4 +-
 .../nativewindow/jawt/x11/X11JAWTWindow.java       |    3 +-
 .../nativewindow/jawt/x11/X11SunJDKReflection.java |    4 +-
 .../jogamp/nativewindow/macosx/OSXUtil.java        |    4 +-
 .../jogamp/nativewindow/windows/GDISurface.java    |   13 +-
 .../jogamp/nativewindow/windows/GDIUtil.java       |    4 +-
 .../jogamp/nativewindow/x11/X11Capabilities.java   |   87 +
 .../x11/X11GraphicsConfigurationFactory.java       |   14 +-
 .../classes/jogamp/nativewindow/x11/X11Util.java   |   39 +-
 .../awt/X11AWTGraphicsConfigurationFactory.java    |   88 +-
 src/nativewindow/native/macosx/OSXmisc.m           |   63 +-
 .../native/{windows => win32}/GDImisc.c            |    0
 .../native/{windows => win32}/WindowsDWM.c         |    0
 .../native/{windows => win32}/WindowsDWM.h         |    0
 src/nativewindow/native/x11/XineramaHelper.c       |  202 +-
 .../native/x11/XineramaHelper.h}                   |   27 +-
 src/nativewindow/native/x11/Xmisc.c                |   13 +-
 src/newt/classes/com/jogamp/newt/NewtFactory.java  |    2 -
 src/newt/classes/com/jogamp/newt/Screen.java       |   14 +-
 src/newt/classes/com/jogamp/newt/Window.java       |   18 +-
 .../classes/com/jogamp/newt/awt/NewtCanvasAWT.java |   86 +-
 .../jogamp/newt/awt/applet/JOGLNewtApplet1Run.java |    9 +-
 .../jogamp/newt/awt/applet/JOGLNewtAppletBase.java |   25 +-
 .../classes/com/jogamp/newt/event/InputEvent.java  |   48 +-
 .../classes/com/jogamp/newt/event/MouseEvent.java  |    9 +-
 .../com/jogamp/newt/event/awt/AWTMouseAdapter.java |   15 +-
 .../classes/com/jogamp/newt/opengl/GLWindow.java   |   55 +-
 .../classes/com/jogamp/newt/util/MainThread.java   |  131 +-
 .../classes/com/jogamp/newt/util/MonitorMode.java  |    5 +-
 src/newt/classes/jogamp/newt/Debug.java            |   82 +-
 src/newt/classes/jogamp/newt/DisplayImpl.java      |   12 +-
 src/newt/classes/jogamp/newt/ScreenImpl.java       |  218 +-
 src/newt/classes/jogamp/newt/WindowImpl.java       |  743 +--
 .../classes/jogamp/newt/awt/NewtFactoryAWT.java    |    6 +-
 .../jogamp/newt/awt/event/AWTNewtEventFactory.java |    3 +-
 .../newt/awt/event/AWTParentWindowAdapter.java     |   19 +-
 .../jogamp/newt/driver/android/AndroidDisplay.java |   11 +-
 .../jogamp/newt/driver/android/AndroidScreen.java  |   16 +-
 .../jogamp/newt/driver/android/AndroidWindow.java  |  261 +-
 .../classes/jogamp/newt/driver/android/MD.java     |   20 +-
 .../newt/driver/android/NewtBaseActivity.java      |  223 +-
 .../android/event/AndroidNewtEventFactory.java     |  156 +-
 .../classes/jogamp/newt/driver/awt/AWTCanvas.java  |   20 +-
 .../classes/jogamp/newt/driver/awt/AWTDisplay.java |    3 +-
 .../classes/jogamp/newt/driver/awt/AWTEDTUtil.java |   68 +-
 .../classes/jogamp/newt/driver/awt/AWTScreen.java  |   36 +-
 .../classes/jogamp/newt/driver/awt/AWTWindow.java  |   42 +-
 .../jogamp/newt/driver/broadcom/egl/Display.java   |    3 +-
 .../jogamp/newt/driver/broadcom/egl/Screen.java    |   18 +-
 .../jogamp/newt/driver/broadcom/egl/Window.java    |   12 +-
 .../jogamp/newt/driver/intel/gdl/Screen.java       |   23 +-
 .../jogamp/newt/driver/intel/gdl/Window.java       |   13 +-
 .../classes/jogamp/newt/driver/kd/KDDisplay.java   |    9 +-
 .../classes/jogamp/newt/driver/kd/KDScreen.java    |   22 +-
 .../classes/jogamp/newt/driver/kd/KDWindow.java    |    9 +-
 .../jogamp/newt/driver/macosx/MacDisplay.java      |   10 +-
 .../jogamp/newt/driver/macosx/MacScreen.java       |   92 +-
 .../jogamp/newt/driver/macosx/MacWindow.java       |   71 +-
 .../jogamp/newt/driver/windows/WindowsDisplay.java |    3 +-
 .../jogamp/newt/driver/windows/WindowsScreen.java  |   25 +-
 .../jogamp/newt/driver/windows/WindowsWindow.java  |   37 +-
 .../classes/jogamp/newt/driver/x11/X11Display.java |    3 +-
 .../classes/jogamp/newt/driver/x11/X11Screen.java  |  155 +-
 .../classes/jogamp/newt/driver/x11/X11Window.java  |   27 +-
 src/newt/native/KDWindow.c                         |   10 +-
 src/newt/native/KeyEvent.h                         |   27 +
 src/newt/native/MacWindow.m                        |  319 +-
 src/newt/native/MouseEvent.h                       |   27 +
 src/newt/native/NewtCommon.h                       |   63 +
 src/newt/native/NewtMacWindow.h                    |   39 +-
 src/newt/native/NewtMacWindow.m                    |  328 +-
 src/newt/native/ScreenMode.h                       |   28 +
 src/newt/native/Window.h                           |   27 +
 src/newt/native/WindowEvent.h                      |   27 +
 src/newt/native/WindowsWindow.c                    |   80 +-
 .../driver/android/MD.java => native/X11Common.h}  |   83 +-
 src/newt/native/X11Display.c                       |  663 +++
 src/newt/native/X11Screen.c                        |  491 ++
 src/newt/native/X11Window.c                        | 1322 +-----
 .../native => test-native}/displayMultiple01.c     |    0
 .../native => test-native}/displayMultiple02.c     |    0
 src/test-native/ffmpeg/api-example.c               |  479 ++
 src/test-native/ffmpeg/avcodec_sample.c            |  203 +
 src/test-native/ffmpeg/avcodec_sample.sh           |    6 +
 .../native => test-native}/glExtensionsListGL2.c   |    0
 .../native => test-native}/glExtensionsListGL3.c   |    0
 src/test-native/gst/helloworld-auto.c              |  112 +
 src/test-native/gst/helloworld-playbin.c           |   75 +
 src/test-native/gst/helloworld-playbin2.c          |   75 +
 src/test-native/gst/helloworld.c                   |  142 +
 src/test-native/gst/make.sh                        |    5 +
 src/{test/native => test-native}/make.sh           |    0
 .../test-native/mesa-demos-patched}/EGL/egl.h      |   15 +-
 .../test-native/mesa-demos-patched}/EGL/eglext.h   |  172 +-
 .../mesa-demos-patched}/EGL/eglplatform.h          |   39 +-
 src/test-native/mesa-demos-patched/eglut/eglut.c   |  400 ++
 src/test-native/mesa-demos-patched/eglut/eglut.h   |   96 +
 .../mesa-demos-patched/eglut/eglut_screen.c        |  180 +
 .../mesa-demos-patched/eglut/eglut_x11.c           |  252 ++
 .../mesa-demos-patched/eglut/eglutint.h            |  104 +
 src/test-native/mesa-demos-patched/es2gears.c      |  751 +++
 src/test-native/mesa-demos-patched/es2redsquare.c  |  611 +++
 src/test-native/mesa-demos-patched/loop.sh         |    5 +
 src/test-native/mesa-demos-patched/make.sh         |   17 +
 src/test-native/mesa-demos-patched/shell_loop.sh   |   11 +
 .../jogamp/opengl/test/android/LauncherUtil.java   |  329 ++
 .../opengl/test/android/MovieCubeActivity0.java    |  125 +
 .../test/android/MovieCubeActivityLauncher0.java   |   79 +
 .../opengl/test/android/MovieSimpleActivity0.java  |  119 +
 .../opengl/test/android/MovieSimpleActivity1.java  |  204 +
 .../android/MovieSimpleActivityLauncher00a.java    |   82 +
 .../android/MovieSimpleActivityLauncher00b.java    |   82 +
 .../android/MovieSimpleActivityLauncher01a.java    |   82 +
 .../android/MovieSimpleActivityLauncher01b.java    |   82 +
 .../android/MovieSimpleActivityLauncher02.java     |   82 +
 .../opengl/test/android/NEWTElektronActivity.java  |    9 +-
 .../test/android/NEWTElektronActivityLauncher.java |   45 +
 .../opengl/test/android/NEWTGearsES1Activity.java  |    8 +-
 .../test/android/NEWTGearsES1ActivityLauncher.java |   44 +
 .../opengl/test/android/NEWTGearsES2Activity.java  |   28 +-
 .../test/android/NEWTGearsES2ActivityLauncher.java |   74 +
 .../test/android/NEWTGearsES2TransActivity.java    |   18 +-
 .../android/NEWTGearsES2TransActivityLauncher.java |   50 +
 .../opengl/test/android/NEWTGraphUI1pActivity.java |    5 +-
 .../android/NEWTGraphUI1pActivityLauncher.java     |   44 +
 .../opengl/test/android/NEWTGraphUI2pActivity.java |    5 +-
 .../android/NEWTGraphUI2pActivityLauncher.java     |   44 +
 .../test/android/NEWTRedSquareES1Activity.java     |   11 +-
 .../android/NEWTRedSquareES1ActivityLauncher.java  |   44 +
 .../test/android/NEWTRedSquareES2Activity.java     |   14 +-
 .../android/NEWTRedSquareES2ActivityLauncher.java  |   21 +
 .../opengl/test/bugs/Bug427GLJPanelTest1.java      |    2 +-
 .../test/junit/graph/TestRegionRendererNEWT01.java |   14 +-
 .../test/junit/graph/TestTextRendererNEWT01.java   |  126 +-
 .../junit/graph/demos/GPURegionGLListener01.java   |    1 -
 .../junit/graph/demos/GPURegionGLListener02.java   |    1 -
 .../graph/demos/GPURendererListenerBase01.java     |   24 +-
 .../junit/graph/demos/GPUTextGLListener0A.java     |    1 -
 .../graph/demos/GPUTextRendererListenerBase01.java |   64 +-
 .../junit/graph/demos/GPUUISceneGLListener0A.java  |   34 +-
 .../opengl/test/junit/graph/demos/MSAATool.java    |   26 +-
 .../opengl/test/junit/graph/demos/ui/Label.java    |    3 +-
 .../opengl/test/junit/graph/demos/ui/RIButton.java |    2 +-
 .../junit/graph/demos/ui/SceneUIController.java    |   10 +-
 .../test/junit/graph/demos/ui/UIGLListener01.java  |   47 +-
 .../junit/graph/demos/ui/UIListenerBase01.java     |    7 +-
 .../opengl/test/junit/graph/demos/ui/UIShape.java  |    2 +-
 .../jogl/acore/TestAWTCloseX11DisplayBug565.java   |   89 +
 .../test/junit/jogl/acore/TestGLProfile01NEWT.java |   73 +-
 .../test/junit/jogl/acore/TestGPUMemSec01NEWT.java |   76 +-
 .../junit/jogl/acore/TestInitConcurrentNEWT.java   |   13 +-
 ...fer01NEWT.java => TestMapBufferRead01NEWT.java} |   20 +-
 .../jogl/acore/TestNEWTCloseX11DisplayBug565.java  |  108 +
 .../test/junit/jogl/acore/TestNVSwapGroupNEWT.java |    2 +-
 .../junit/jogl/acore/TestPBufferDeadlockAWT.java   |    4 +-
 .../junit/jogl/acore/TestSharedContextListAWT.java |   24 +-
 .../jogl/acore/TestSharedContextListNEWT.java      |   23 +-
 .../jogl/acore/TestSharedContextListNEWT2.java     |   25 +-
 .../jogl/acore/TestSharedContextNewtAWTBug523.java |   15 +
 .../jogl/acore/TestSharedContextVBOES1NEWT.java    |   23 +-
 .../jogl/acore/TestSharedContextVBOES2NEWT.java    |   23 +-
 .../jogl/acore/TestSharedContextVBOES2NEWT2.java   |   23 +-
 .../junit/jogl/acore/TestShutdownCompleteAWT.java  |    6 +-
 .../junit/jogl/acore/TestShutdownCompleteNEWT.java |    6 +-
 .../junit/jogl/acore/TestShutdownSharedAWT.java    |    6 +-
 .../junit/jogl/acore/TestShutdownSharedNEWT.java   |    6 +-
 .../opengl/test/junit/jogl/awt/TestAWT01GLn.java   |   20 +-
 .../TestAWTCardLayoutAnimatorStartStopBug532.java  |  229 +
 .../TestBug461OffscreenSupersamplingSwingAWT.java  |    4 +-
 .../opengl/test/junit/jogl/awt/TestBug551AWT.java  |  147 +
 .../test/junit/jogl/awt/TestSwingAWT01GLn.java     |   20 +-
 ...tisampleDemo01.java => MultisampleDemoES1.java} |   54 +-
 ...tisampleAWT.java => TestMultisampleES1AWT.java} |   10 +-
 ...sampleNEWT.java => TestMultisampleES1NEWT.java} |   19 +-
 .../test/junit/jogl/demos/TestTextureSequence.java |  120 +
 .../opengl/test/junit/jogl/demos/es1/GearsES1.java |   13 +-
 .../junit/jogl/demos/{gl2 => es1}/OneTriangle.java |   41 +-
 .../jogl/demos/es1/newt/TestGearsES1NEWT.java      |   11 +-
 .../jogl/demos/es1/newt/TestRedSquareES1NEWT.java  |   11 +-
 .../jogl/demos/es2/ElektronenMultiplizierer.java   |   13 +-
 .../opengl/test/junit/jogl/demos/es2/GearsES2.java |   23 +-
 .../test/junit/jogl/demos/es2/RedSquareES2.java    |   13 +-
 .../test/junit/jogl/demos/es2/TexCubeES2.java      |  507 +++
 .../test/junit/jogl/demos/es2/av/MovieCube.java    |  237 +
 .../test/junit/jogl/demos/es2/av/MovieSimple.java  |  559 +++
 .../awt/TestGearsES2AWT.java}                      |   78 +-
 .../es2/newt/TestElektronenMultipliziererNEWT.java |   13 +-
 .../jogl/demos/es2/newt/TestGearsES2NEWT.java      |  178 +-
 .../jogl/demos/es2/newt/TestRedSquareES2NEWT.java  |   60 +-
 .../junit/jogl/demos/es2/shader/texsequence_xxx.fp |   22 +
 .../junit/jogl/demos/es2/shader/texsequence_xxx.vp |   17 +
 .../junit/jogl/demos/gl2/awt/TestGearsAWT.java     |   30 +-
 .../demos/gl2/awt/TestGearsAWTAnalyzeBug455.java   |   12 +-
 .../jogl/demos/gl2/awt/TestGearsGLJPanelAWT.java   |   13 +-
 .../demos/gl2/awt/TestGearsGLJPanelAWTBug450.java  |   12 +-
 .../junit/jogl/demos/gl2/newt/TestGearsNEWT.java   |   17 +-
 .../demos/gl2/newt/TestGearsNewtAWTWrapper.java    |    8 +-
 .../test/junit/jogl/glsl/TestFBOMRTNEWT01.java     |   40 +-
 .../junit/jogl/glsl/TestGLSLShaderState01NEWT.java |   34 +-
 .../junit/jogl/glsl/TestGLSLShaderState02NEWT.java |   47 +-
 .../test/junit/jogl/glsl/TestGLSLSimple01NEWT.java |    3 -
 .../test/junit/jogl/glsl/TestRulerNEWT01.java      |   11 +-
 .../TestTransformFeedbackVaryingsBug407NEWT.java   |  134 +-
 .../jogl/glu/TestBug463ScaleImageMemoryAWT.java    |    2 +-
 ...TestSwingAWTRobotUsageBeforeJOGLInitBug411.java |   11 +-
 .../test/junit/jogl/offscreen/ReadBuffer2File.java |    3 +-
 .../test/junit/jogl/offscreen/Surface2File.java    |   16 +-
 .../jogl/offscreen/TestOffscreen02BitmapNEWT.java  |   38 +-
 .../test/junit/jogl/swt/TestSWTAWT01GLn.java       |   27 +-
 ...TestSWT02GLn.java => TestSWTAccessor02GLn.java} |   33 +-
 ...01GLn.java => TestSWTEclipseGLCanvas01GLn.java} |   31 +-
 ...01GLn.java => TestSWTJOGLGLCanvas01GLnAWT.java} |   97 +-
 .../texture/TestGrayTextureFromFileAWTBug417.java  |    6 +-
 .../test/junit/jogl/texture/TestTexture01AWT.java  |    6 +-
 .../TestGLReadBufferUtilTextureIOWrite01NEWT.java} |   99 +-
 .../TestGLReadBufferUtilTextureIOWrite02NEWT.java  |  146 +
 .../test/junit/jogl/util/TestPNGImage01NEWT.java   |   41 +
 .../test/junit/newt/TestEventSourceNotAWTBug.java  |    2 +-
 .../test/junit/newt/TestFocus01SwingAWTRobot.java  |   13 +-
 .../test/junit/newt/TestFocus02SwingAWTRobot.java  |   20 +-
 .../test/junit/newt/TestScreenMode00NEWT.java      |   34 +-
 .../test/junit/newt/TestScreenMode01NEWT.java      |   12 -
 .../junit/newt/TestWindowClosingProtocol01AWT.java |   20 +-
 .../newt/TestWindowClosingProtocol02NEWT.java      |   16 +-
 .../newt/TestWindowClosingProtocol03NewtAWT.java   |   10 +-
 .../junit/newt/parenting/TestParenting01NEWT.java  |   12 +-
 .../junit/newt/parenting/TestParenting01aAWT.java  |    2 +-
 .../TestParentingFocusTraversal01AWT.java          |    9 +-
 .../TestParentingOffscreenLayer01GLCanvasAWT.java  |   23 +-
 ...TestParentingOffscreenLayer02NewtCanvasAWT.java |   24 +-
 .../opengl/test/junit/util/AWTRobotUtil.java       |   87 +-
 .../opengl/test/junit/util/GLSLSimpleProgram.java  |    6 +-
 .../jogamp/opengl/test/junit/util/MiscUtils.java   |    9 +
 .../jogamp/opengl/test/junit/util/UITestCase.java  |   31 +-
 src/test/jogamp/newt/WindowImplAccess.java         |    2 +-
 www/index.html                                     |  527 ++-
 www/media/EverplanesLogo_160x160.png               |  Bin 0 -> 45282 bytes
 www/media/Frog-Craft3_2.160w.png                   |  Bin 0 -> 27158 bytes
 www/media/Frog-Craft3_2.png                        |  Bin 0 -> 280766 bytes
 www/media/JebGL_logo.160w.png                      |  Bin 0 -> 11378 bytes
 www/media/JebGL_logo.png                           |  Bin 0 -> 31923 bytes
 www/{ => media}/NetBeansOpenGLPackLogo160.png      |  Bin
 www/{ => media}/artofillusion.jpg                  |  Bin
 www/{ => media}/avengina.jpg                       |  Bin
 www/media/c3d-studio.jpg                           |  Bin 0 -> 9860 bytes
 www/{ => media}/chronotext.jpg                     |  Bin
 www/{ => media}/elflightengine-160x122.png         |  Bin
 www/{ => media}/fenggui.jpg                        |  Bin
 www/{ => media}/field.png                          |  Bin
 www/{ => media}/fusion-laboratory.jpg              |  Bin
 www/media/geogebra-screenshot-tangents.png         |  Bin 0 -> 5980 bytes
 www/{ => media}/gephi.jpg                          |  Bin
 www/media/glg2d-demo.png                           |  Bin 0 -> 10295 bytes
 www/{ => media}/glstudio.jpg                       |  Bin
 www/{ => media}/impact.jpg                         |  Bin
 www/{ => media}/insparia.jpg                       |  Bin
 www/{ => media}/jackflowers.jpg                    |  Bin
 www/{ => media}/jake2.jpg                          |  Bin
 www/media/jogl-applet-moviecube01-small.png        |  Bin 0 -> 19167 bytes
 www/media/jogl-applet-moviecube01.png              |  Bin 0 -> 118588 bytes
 www/media/jreality-logo-discreteksurfaces.png      |  Bin 0 -> 28465 bytes
 www/{ => media}/madlix.png                         |  Bin
 www/media/map_of_illarion.png                      |  Bin 0 -> 44172 bytes
 www/{ => media}/mbt.jpg                            |  Bin
 www/media/pebbles.png                              |  Bin 0 -> 31238 bytes
 www/{ => media}/processing.jpg                     |  Bin
 www/{ => media}/raceview.jpg                       |  Bin
 www/{ => media}/scilab.png                         |  Bin
 www/{ => media}/sculpteo_3_robot_72dpi_sm.jpg      |  Bin
 www/{ => media}/specksim.jpg                       |  Bin
 www/{ => media}/strap.jpg                          |  Bin
 www/{ => media}/vehicle.jpg                        |  Bin
 www/{ => media}/vldocking.jpg                      |  Bin
 www/{ => media}/worldwind.jpg                      |  Bin
 www/{ => media}/zg3d.png                           |  Bin
 www/pebbles.png                                    |  Bin 35714 -> 0 bytes
 www/sun-contributor-agreement.pdf                  |  Bin 18368 -> 0 bytes
 www/tck-license.html                               |   39 -
 www/viewerVR.png                                   |  Bin 60130 -> 0 bytes
 737 files changed, 47306 insertions(+), 11990 deletions(-)

diff --git a/.classpath b/.classpath
index 3a9a469..064f059 100644
--- a/.classpath
+++ b/.classpath
@@ -26,12 +26,11 @@
 			<attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="jogl/build/newt/obj"/>
 		</attributes>
 	</classpathentry>
-	<classpathentry kind="src" path="src/android"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
 	<classpathentry combineaccessrules="false" kind="src" path="/gluegen"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/Ant"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.USER_LIBRARY/SWT"/>
-	<classpathentry kind="lib" path="/gluegen/make/lib/android-sdk/9/android.jar" sourcepath="/gluegen/make/lib/android-sdk/9/android-java-src.zip"/>
+	<classpathentry kind="lib" path="/gluegen/make/lib/android-sdk/15/android.jar" sourcepath="/gluegen/make/lib/android-sdk/15/android-java-src.zip"/>
 	<classpathentry kind="output" path="build/eclipse-classes"/>
 </classpath>
diff --git a/.externalToolBuilders/jogl builder.launch b/.externalToolBuilders/jogl builder.launch
index 6c3ea63..ef0f5e7 100644
--- a/.externalToolBuilders/jogl builder.launch	
+++ b/.externalToolBuilders/jogl builder.launch	
@@ -14,12 +14,7 @@
 <listEntry value="4"/>
 </listAttribute>
 <booleanAttribute key="org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND" value="false"/>
-<listAttribute key="org.eclipse.jdt.launching.CLASSPATH">
-<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<runtimeClasspathEntry containerPath="org.eclipse.jdt.launching.JRE_CONTAINER" path="1" type="4"/>
"/>
-<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<runtimeClasspathEntry id="org.eclipse.ant.ui.classpathentry.extraClasspathEntries">
<memento/>
</runtimeClasspathEntry>
"/>
-</listAttribute>
 <stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
-<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="false"/>
 <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="jogl"/>
 <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/jogl/make/build.xml}"/>
 <stringAttribute key="org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS" value="full,incremental,auto,clean"/>
diff --git a/LICENSE.txt b/LICENSE.txt
index 695e1dd..3550ab2 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -271,7 +271,7 @@ A.3) The JOGL source tree contains code from David Schweinsberg
 A.4) The JOGL source tree contains fonts from Ubuntu
      which is covered by the UBUNTU FONT LICENCE Version 1.0
 
-   Ubunut Font Family
+   Ubuntu Font Family
    ==================
 
    The Ubuntu Font Family are libre fonts funded by Canonical Ltd on behalf of the Ubuntu project. 
@@ -336,3 +336,28 @@ A.5) The JOGL source tree also contains header files from NVIDIA,
    NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF NVIDIA HAS BEEN ADVISED 
    OF THE POSSIBILITY OF SUCH DAMAGE.
    
+A.6) The JOGL source tree contains code from Hernan J. Gonzalez and Shawn Hartsock
+     which is covered by the Apache License Version 2.0
+
+   PNGJ
+   ====
+
+   PNGJ: Java library for reading and writing PNG images.
+
+   Version 0.85  (1 April 2012)
+
+   <http://code.google.com/p/pngj/>
+
+   Author: Hernan J. Gonzalez and Shawn Hartsock
+
+   Copyright (C) 2004 The Apache Software Foundation. All rights reserved.
+
+   Apache Licenses
+   http://www.apache.org/licenses/
+
+   Apache License Version 2.0
+   http://www.apache.org/licenses/LICENSE-2.0
+   Or within this repository: doc/licenses/Apache.LICENSE-2.0
+    src/jogl/classes/jogamp/opengl/util/pngj/**
+
+
diff --git a/doc/Platform.Applets.txt b/doc/Platform.Applets.txt
new file mode 100644
index 0000000..c3de6de
--- /dev/null
+++ b/doc/Platform.Applets.txt
@@ -0,0 +1,23 @@
+
+Applets
+=========
+
+[1] Windows 7 x64 Native/NV, VirtualBox 4.1.6/Chromium(NV):
+[2] Linux x64 [ubuntu 10/11]
+[3] MacOSX 10.7
+
+  Tested:
+    - AWT Applet w/ GLCanvas (VersionApplet)
+    - NEWT Applet w/ GLWindow (JOGLNewtApplet1Run)
+    - NApplet OK
+    - LApplet OK
+    - JApplet/Dual OK
+    - back/fwd (reload) works
+
+  Browser:
+    - Internet Explorer [8 and 9] 32bit [1]
+    - Safari 5.1.1 32bit [1], [3]
+    - Firefox [6.0, 8.0.1] 32bit, [11.0a1] 64bit [1], [2], [3]
+    - Chrome [15.0.874.121m, 16.0.912.41] 32bit [1], [2]
+
+
diff --git a/doc/Platform.GLES.txt b/doc/Platform.GLES.txt
new file mode 100644
index 0000000..0bcd3bc
--- /dev/null
+++ b/doc/Platform.GLES.txt
@@ -0,0 +1,112 @@
+
+GL2ES2 on Desktop
+=================
+
+GL2ES2 Profile with GL_ARB_ES2_compatibility:
+    Extension is supported and recognized properly.
+    It can be queried via GLContext.isGLES2Compatible()
+    and impacts many ES2 related GL2ES2 wrapper functions
+    like glShaderBinary(..).
+    Having ES2 compatibility results in a full ES2 implementation
+    even if using GL2ES2 via a desktop profile.
+    Of course, ES2 extensions are not supported in this case.
+
+
+Native GLES2 on Desktop
+=======================
+
+Ensure that the native ES2/EGL libraries are available in your LD_LIBRARY_PATH
+(or equivalent). Note that JOGL favors the spec lib names for it's lib name order:
+  ES2: libGLESv2.so.2, libGLESv2.so, GLES20, GLESv2_CM
+  EGL: libEGL.so.1, libEGL.so, EGL
+
+To utilize native ES2 on desktop (See TestGLProfile02NEWT and TestGearsES2NEWT)
+you have to request the actual profile 'GLES2' otherwise
+a request for e.g. GL2ES2 will utilize the highest common desktop profile.
+
+<...
+        if(!GLProfile.isAvailable(GLProfile.GLES2)) {
+            System.out.println("GLProfile GLES2 n/a");
+            return;
+        }
+        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2));
+...>
+
+Linux:
+    PVRVFrame 2.09.29.0649
+        Debian Wheezy/testing x64, NV 290.10, 32bit libraries: OK
+            GL_VENDOR     Imagination Technologies (Host GL: `NVIDIA Corporation`)
+            GL_RENDERER   PowerVR PVRVFrame 8.1 SGX (Host GL: `GeForce GTX 460/PCI/SSE2`)
+            GL_VERSION    OpenGL ES 2.0 ( SDK build: 2.09.29.0646 )
+            GL_EXTENSIONS 
+                          GL_OES_byte_coordinates GL_OES_fixed_point GL_OES_query_matrix GL_OES_single_precision GL_OES_matrix_get GL_OES_read_format 
+                          GL_IMG_read_format GL_OES_point_sprite GL_OES_query_matrix GL_OES_texture_env_crossbar GL_OES_texture_mirrored_repeat GL_OES_blend_subtract 
+                          GL_OES_blend_func_separate GL_OES_blend_equation_separate GL_OES_stencil_wrap GL_OES_extended_matrix_palette 
+                          GL_IMG_multisampled_render_to_texture GL_OES_vertex_half_float GL_OES_compressed_ETC1_RGB8_texture GL_OES_compressed_paletted_texture 
+                          GL_OES_depth24 GL_OES_depth_texture GL_OES_required_internalformat GL_OES_vertex_array_object GL_OES_packed_depth_stencil 
+                          GL_EXT_discard_framebuffer GL_OES_texture_float GL_OES_texture_half_float GL_OES_texture_cube_map GL_OES_rgb8_rgba8 GL_OES_stencil8 
+                          GL_OES_fragment_precision_high GL_OES_element_index_uint GL_IMG_texture_compression_pvrtc GL_OES_mapbuffer GL_OES_texture_npot GL_EXT_multi_draw_arrays
+            GLX_EXTENSIONS
+
+
+        Debian Wheezy/testing x64, NV 290.10, 64bit libraries: Failure (eglCreateContext EGL_BAD_ATTRIBUTE)
+
+        Ubuntu 11.10 x64, AMD Catalyst 12.1, 32bit libraries: 
+            X Error of failed request:  BadMatch (invalid parameter attributes)
+              Major opcode of failed request:  137 (GLX)
+              Minor opcode of failed request:  5 (X_GLXMakeCurrent)
+              Serial number of failed request:  51
+              Current serial number in output stream:  51
+            dlopen tries: libGL.so
+
+    OpenGL ES 2.0 Mesa (libegl1-mesa*, libgles2-mesa*)
+        Debian Wheezy/testing x64, NV 290.10, 64bit libraries, libgles2-mesa 7.11.2-1: OK
+            GL_VENDOR     Mesa Project
+            GL_RENDERER   Software Rasterizer
+            GL_VERSION    OpenGL ES 2.0 Mesa 7.11.2
+            GL_EXTENSIONS 
+                          GL_EXT_blend_minmax GL_EXT_multi_draw_arrays GL_EXT_texture_filter_anisotropic GL_OES_depth24 GL_OES_element_index_uint GL_OES_fbo_render_mipmap 
+                          GL_OES_mapbuffer GL_OES_rgb8_rgba8 GL_OES_standard_derivatives GL_OES_stencil8 GL_OES_texture_3D GL_OES_texture_npot GL_OES_depth_texture 
+                          GL_OES_packed_depth_stencil GL_EXT_texture_type_2_10_10_10_REV 
+            GLX_EXTENSIONS
+                          EGL_KHR_surfaceless_opengl EGL_KHR_surfaceless_gles1 EGL_KHR_surfaceless_gles2 
+
+
+        Ubuntu 11.10 x64, AMD Catalyst 12.1, 64bit libraries, libgles2-mesa 7.11-0ubuntu3: Error (swrast error, null values)
+
+Windows:
+    PVRVFrame 2.09.29.0649
+       Windows7 64bit, NV 290.10, 32bit libraries: OK 
+            GL_VENDOR     Imagination Technologies (Host GL: `NVIDIA Corporation`)
+            GL_RENDERER   PowerVR PVRVFrame 8.1 SGX (Host GL: `GeForce GTX 460/PCIe/SSE2`)
+            GL_VERSION    OpenGL ES 2.0 ( SDK build: 2.09.29.0646 )
+            GL_EXTENSIONS
+                          GL_OES_byte_coordinates GL_OES_fixed_point GL_OES_query_matrix GL_OES_single_precision GL_OES_matrix_get GL_OES_read_format 
+                          GL_IMG_read_format GL_OES_point_sprite GL_OES_query_matrix GL_OES_texture_env_crossbar GL_OES_texture_mirrored_repeat GL_OES_blend_subtract 
+                          GL_OES_blend_func_separate GL_OES_blend_equation_separate GL_OES_stencil_wrap GL_OES_extended_matrix_palette 
+                          GL_IMG_multisampled_render_to_texture GL_OES_vertex_half_float GL_OES_compressed_ETC1_RGB8_texture GL_OES_compressed_paletted_texture 
+                          GL_OES_depth24 GL_OES_depth_texture GL_OES_required_internalformat GL_OES_vertex_array_object GL_OES_packed_depth_stencil 
+                          GL_EXT_discard_framebuffer GL_OES_texture_float GL_OES_texture_half_float GL_OES_texture_cube_map GL_OES_rgb8_rgba8 GL_OES_stencil8 
+                          GL_OES_fragment_precision_high GL_OES_element_index_uint GL_IMG_texture_compression_pvrtc GL_OES_mapbuffer GL_OES_texture_npot GL_EXT_multi_draw_arrays
+            GLX_EXTENSIONS
+
+    ANGLE
+       Windows7 64bit, NV 290.10, 32bit libraries: OK
+            GL_VENDOR     Google Inc.
+            GL_RENDERER   ANGLE (NVIDIA GeForce GTX 460)
+            GL_VERSION    OpenGL ES 2.0 (ANGLE 1.0.0.937)
+            GL_EXTENSIONS
+                          GL_OES_element_index_uint GL_OES_packed_depth_stencil GL_OES_rgb8_rgba8 GL_OES_standard_derivatives GL_OES_texture_half_float 
+                          GL_OES_texture_half_float_linear GL_OES_texture_float GL_OES_texture_float_linear GL_OES_texture_npot GL_EXT_read_format_bgra 
+                          GL_EXT_robustness GL_EXT_texture_compression_dxt1 GL_EXT_texture_format_BGRA8888 GL_EXT_texture_storage 
+                          GL_ANGLE_framebuffer_blit 
+                          GL_ANGLE_framebuffer_multisample GL_ANGLE_pack_reverse_row_order GL_ANGLE_texture_compression_dxt3 
+                          GL_ANGLE_texture_compression_dxt5 GL_ANGLE_texture_usage GL_ANGLE_translated_shader_source GL_NV_fence
+            GLX_EXTENSIONS
+                          EGL_NV_post_sub_buffer 
+                          EGL_ANGLE_query_surface_pointer EGL_ANGLE_d3d_share_handle_client_buffer EGL_ANGLE_surface_d3d_texture_2d_share_handle 
+                          EGL_EXT_create_context_robustness
+            GLSL          true, shader-compiler: true
+
+    
+
diff --git a/doc/Platforms.txt b/doc/Platforms.txt
new file mode 100644
index 0000000..7fbb65b
--- /dev/null
+++ b/doc/Platforms.txt
@@ -0,0 +1,62 @@
+
+- OS / Arch
+    - Linux i586 (x86_32) and amd64 (x86_64)
+        - Distribution
+            - Debian Wheezy / testing (*)
+            - Ubuntu 10.04, 11.10 (*)
+            - CentOS / RedHat 6.2
+
+        - OpenGL
+            - AMD Proprietary (*)
+            - NVidia Proprietary (*)
+            - Mesa3D (sw, dri, ..)
+            - PowerVR (ES2) 32bit only
+
+    - Linux armv7
+        - Distribution
+            - Ubuntu 10.04
+        - OpenGL
+            - Mesa3D (sw, dri, ..)
+            - PowerVR SGX 530
+
+    - Android armv7
+        - Version
+            - Version 2.3 Gingerbread (SDK API Level 9)
+
+        - OpenGL
+            - ARM Mali
+            - PowerVR SGX 540
+            - NVidia Tegra2
+
+    - Solaris x86_64
+        - Distribution
+            - Solaris 10
+            - OpenIndiana 151a (*)
+            - Illumian 1.0
+
+        - OpenGL
+            - NVidia Proprietary (*)
+
+    - Mac OS X x86_64
+        - Version
+            - 10.5
+            - 10.6.8 (*)
+            - 10.7.2 (*)
+        - OpenGL
+            - AMD Proprietary
+            - NVidia Proprietary (*)
+        
+    - Windows i586 (x86_32) and amd64 (x86_64)
+        - Version
+            - Windows XP (maybe buggy)
+            - Windows Vista
+            - Windows7 (*)
+
+        - OpenGL
+            - AMD Proprietary (*)
+            - NVidia Proprietary (*)
+            - Intel Sandy Bridge
+            - ANGLE (ES2) 32bit only
+            - PowerVR (ES2) 32bit only
+
+(*) Regular tested component / platform
diff --git a/doc/userguide/index.html b/doc/userguide/index.html
index aa0645b..cdb26f1 100644
--- a/doc/userguide/index.html
+++ b/doc/userguide/index.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
@@ -25,233 +25,337 @@
             </div>
             <div id="main">
                 <div id="text" class="fill">
-                    <h2><font color="red">WARNING: This document has not been updated for a long time.</font></h2>
+                    <b><font color="red">WARNING: This document is under review.</font></b>
                     <br/>
                     <br/>
-<UL>
-
-  <LI> Overview
-  <LI> Developing with JOGL
-  <UL>
-    <LI> Building the source tree
-    <LI> Local installation for development
-    <LI> Java Web Start integration
-    <LI> Applet support
-  </UL>
-  <LI> GLDrawable and GLContext
-  <LI> Creating a GLAutoDrawable
-  <LI> Writing a GLEventListener
-  <LI> Using the Composable Pipeline
-  <LI> Heavyweight and Lightweight Issues
-  <LI> Multithreading Issues
-  <LI> Pbuffers
-  <LI> GLU
-  <LI> More Resources
-  <LI> Platform notes
-  <UL>
-    <LI> All Platforms
-    <LI> Windows
-    <LI> Linux
-    <LI> Solaris, Linux (X11 platforms)
-    <LI> Macintosh OS X
-  </UL>
-  <LI> Version History
-
-</UL>
-
-<H2> Overview </H2>
-
-<P>
-
-Jogl is a Java programming language binding for the OpenGL 3D graphics
-API. It supports integration with the Java platform's AWT and Swing
-widget sets while providing a minimal and easy-to-use API that handles
-many of the issues associated with building multithreaded OpenGL
-applications. Jogl provides access to the latest OpenGL routines
-(OpenGL 2.0 with vendor extensions) as well as platform-independent
+<ul>
+
+  <li> <a href="#overview">Overview</a> </li>
+  <li> <a href="#access">Accessing JOGL</a>
+  <ul>
+    <li> <a href="#building">Building the source tree</a></li>
+    <li> <a href="#localinstallation">Local installation</a>
+      <ul>
+        <li> <a href="#archivefiles">7z Archives</a></li>
+        <li> <a href="#jarfilesandclasspath">JAR Files & CLASSPATH</a>
+        <ul>
+            <li> <a href="#atomicjarfiles">Atomic JAR files</a></li>
+        </ul></li>
+        <li> <a href="#automatednativelibraryloading">Automated Native Library Loading</a></li>
+        <li> <a href="#traditionallibraryloading">Traditional Native Library Loading</a></li>
+        <li> <a href="#ideusers">Settings for IDE's users</a></li>
+        <li> <a href="#badpractice">Bad practice</a></li>
+        <li> <a href="#notefordebianusers">Note for Debian Linux users</a></li>
+      </ul></li>
+    <li> <a href="#onlinedeployment">Online Deployment</a>
+    <ul>
+      <li> <a href="#applets">Applets</a></li>
+      <li> <a href="#jnlpwebstart">JNLP / Web Start</a></li>
+    </ul></li>
+  </ul></li>
+  <li> <a href="#joglapi">Using the JOGL API</a>
+  <ul>
+    <li> <a href="#gldrawableandglcontext">GLDrawable and GLContext</a></li>
+    <li> <a href="#glprofile">GLProfile</a></li>
+    <li> <a href="#creatingaglautodrawable">Creating a GLAutoDrawable</a></li>
+    <li> <a href="#writingagleventlistener">Writing a GLEventListener</a></li>
+    <li> <a href="#checkingextensionsandfunctionsavailability">Checking extensions and functions availability</a></li>
+    <li> <a href="#useofniobuffers">Use of NIO buffers</a></li>
+    <li> <a href="#documentationofclang">Documentation of C language functions matching with Jogl methods</a></li>
+    <li> <a href="#performance">Performance</a></li>
+    <li> <a href="#composablepipeline">Using the Composable Pipeline</a></li>
+    <li> <a href="#heavylightweightissues">Heavyweight and Lightweight Issues</a></li>
+    <li> <a href="#swtawtissues">SWT/AWT issues</a></li>
+    <li> <a href="#multithreadingissues">AWT Multithreading Issues</a></li>
+    <li> <a href="#pbuffers">Pbuffers</a></li>
+    <li> <a href="#glu">GLU</a></li>
+    <li> <a href="#moreresources">More Resources</a></li>
+  </ul></li>
+  <li> <a href="#platformnotes">Platform notes</a>
+  <ul>
+    <li> <a href="#allplatforms">All Platforms</a></li>
+    <li> <a href="#windows">Windows</a></li>
+    <li> <a href="#x11unix">X11 Platforms (Linux, Solaris, ..)</a></li>
+    <li> <a href="#macosx">Macintosh OS X</a></li>
+  </ul></li>
+  <li> <a href="#versionhistory">Version History</a></li>
+
+</ul>
+
+<h2> <a name="overview">Overview</a> </h2>
+
+<p>
+    The JOGL project hosts the development version of the Java™ Binding for the OpenGL® API,
+    and is designed to provide hardware-supported 3D graphics to applications written in Java.
+</p>
+<p>
+    It provides full access to the APIs in the OpenGL 1.3 - 3.0, 3.1 - 3.3, ≥ 4.0, ES 1.x and ES 2.x specification
+    as well as nearly all vendor extensions.
+    <a href="../Overview-OpenGL-Evolution-And-JOGL.html">OpenGL Evolution & JOGL</a>
+    (<a href="../bouml/html-svg/fig128069.svg">UML</a>) gives you a brief overview of OpenGL, 
+    its profiles and how we map them to JOGL.
+</p>
+<p>
+    It integrates with the AWT, Swing and SWT widget sets, as well with custom windowing toolkits using the NativeWindow API.
+    <a href="../NEWT-Overview.html">JOGL also provides its own native windowing toolkit, NEWT</a>.
+</p>
+
+<p>
+AWT integration is available via AWT GLCanvas and NEWT's NewtCanvasAWT,
+where Swing integration is available via GLJPanel.
+</p>
+<p>
+SWT integration is available via SWT GLCanvas and by using the SWT/AWT brigde.
+</p>
+<p>
+Other windowing systems or widgets sets can be implemented by using the NativeWindow API.
+</p>
+
+<p>
+
+Jogl provides access to the latest OpenGL routines
+(OpenGL 4.x with nearly all vendor extensions) as well as platform-independent
 access to hardware-accelerated offscreen rendering ("pbuffers"). Jogl
 also provides some of the most popular features introduced by other
 Java bindings for OpenGL like GL4Java, LWJGL and Magician, including a
 composable pipeline model which can provide faster debugging for
-Java-based OpenGL applications than the analogous C program.
-
-</P>
-<P>
-
-Jogl was designed for the most recent versions of the Java platform
-and for this reason supports only J2SE 1.4 and later. It also only
-supports truecolor (15 bits per pixel and higher) rendering; it does
+Java-based OpenGL applications than the analogous C program and a native windowing 
+toolkit independent of AWT called NEWT.
+
+</p>
+
+Jogl is designed for the most recent versions of the Java platform
+and for this reason supports only:
+<ul>
+   <li>Java 1.6 (Level 6.0)
+     <ul>
+        <li> J2SE ≥ 1.6 (OpenJDK, Oracle, ..)</li>
+        <li> JavaSE ≥ 1.6 For Embedded (Oracle) </li>
+     </ul></li>
+   <li>Android SDK API Level 9 (Version 2.3 Gingerbread)</li>
+</ul>
+
+<p>
+It also only supports truecolor (15 bits per pixel and higher) rendering; it does
 not support color-indexed modes. It was designed with New I/O (NIO) in
-mind and uses NIO internally in the implementation. The Jogl binding
-is itself written almost completely in the Java programming language.
-There are roughly 150 lines of handwritten C code in the entire Jogl
-source base (100 of which work around bugs in older OpenGL drivers on
-Windows); the rest of the native code is autogenerated during the
+mind and often uses NIO internally in the implementation. Nevertheless non 
+NIO/direct buffers/arrays are supported as well, since they allow faster processing on 
+CPU intensive tasks.  
+The Jogl binding is itself written almost completely in the Java programming language.
+Most of the native code is autogenerated during the
 build process by a new tool called <a
-href="http://kenai.com/projects/gluegen/pages/Home/">GlueGen</a>, the source code of
-which is available from its own java.net project.
-
-</P>
-<P>
+href="../../../gluegen/www/">GlueGen</a>, the source code of
+which is available from its own jogamp.org project.
 
-The JOGL source tree in its current form is an experimental workspace
-for the <a href="http://jcp.org/en/jsr/detail?id=231">JSR-231</a> Java
-Bindings for OpenGL JSR. JOGL is not the official reference
-implementation, but an evolving workspace. Snapshots of the JOGL
-source tree are run through the JSR-231 Technology Compatibility Kit
-(TCK) to become the official reference implementation (RI). As of this
-writing the JSR has not been finalized, so the first official RI of
-the JSR has not yet been produced.
+</p>
 
-</P>
+<h2> <a name="access">Accessing JOGL</a> </h2>
 
-<H2> Developing with JOGL </H2>
+<h3> <a name="building">Building the source tree</a> </h3>
 
-<H3> Building the source tree </H3>
-
-<P>
+<p>
 
 Most developers using JOGL will download the most current 
-<a href="http://download.java.net/media/jogl/builds/archive/">release build</a>. 
+<a href="../../../deployment/jogamp-current/archive/">release build</a>. 
 Separate instructions are available on how to 
-<a href="http://download.java.net/media/jogl/doc/HowToBuild.html">build the source tree</a>.
+<a href="../HowToBuild.html">build the source tree</a>.
+
+</p>
 
-</P>
+<h3> <a name="localinstallation">Local Installation</a> </h3>
 
-<H3> Local installation for development </H3>
+See <a href="../deployment/JOGL-DEPLOYMENT.html">deployment</a> for deployment details.
 
-<P>
+<h4> <a name="archivefiles">7zip Archives</a> </h4>
+<p>
 
-The JOGL distribution for developers comes in the form of a zip
-archive which contains the Java classes to call OpenGL from Java, as
+A 7zip archive for all platforms and all JogAmp modules including JOGL
+is available, named <code>jogamp-all-platforms.7z</code>, 
+as available <a href="../../../deployment/jogamp-current/archive/jogamp-all-platforms.7z">here</a>.
+It contains the Java classes to call OpenGL from Java, as
 well as the associated JNI native libraries. JOGL depends on some
 run-time support classes and native code provided by the GlueGen
-project; these classes and native code are also provided in the zip
+project; these classes and native code are also provided in the 7zip
 bundles.
 
-</P>
-<P>
+</p>
 
-If you are developing a new application which uses JOGL, download the
-zip archive for your platform (for example.,
-jogl-[version]-windows-i586.zip) and unzip it. Modify your CLASSPATH
-environment variable to include the full paths to jogl.all.jar,
-nativewindow.all.jar, gluegen-rt.jar, and optionally newt.all.jar; for
-example,
-".;C:\Some\Other\Package\foo.jar;C:\Users\myhome\jogl-[version]-windows-i586\lib\jogl.all.jar;C:\Users\myhome\jogl-[version]-windows-i586\lib\nativewindow.all.jar;C:\Users\myhome\jogl-[version]-windows-i586\lib\gluegen-rt.jar;C:\Users\myhome\jogl-[version]-windows-i586\lib\newt.all.jar".
+<h4> <a name="jarfilesandclasspath">JAR Files & CLASSPATH</a> </h4>
+
+Modify your <code>CLASSPATH</code>
+environment variable to include the full paths to 
+<code>gluegen-rt.jar</code> and <code>jogl.all.jar</code>, for example
+<pre>
+".;C:\Some\Other\Package\foo.jar;C:\Users\myhome\jogamp-all-platforms\jar\gluegen-rt.jar;C:\Users\myhome\jogamp-all-platforms\jar\jogl.all.jar".
+</pre>
 (If you did not previously set the CLASSPATH environment variable, you
 may want to make sure that ".", the current directory, is on your new
-CLASSPATH.) Modify your PATH environment variable (Windows),
-LD_LIBRARY_PATH environment variable (Solaris and Linux), or
-DYLD_LIBRARY_PATH environment variable (Mac OS X) to contain the full
-path to the "lib" directory; for example, on Windows, add
-"C:\Users\myhome\jogl-[version]-windows-i586\lib" to your PATH using
-the System control panel, Advanced tab, Environment Variables
-button. At this point your Java installation should be able to see the
-JOGL class files. Users of IDEs such as NetBeans and Eclipse should
-consult the IDE's documentation to see how to add jar files and native
-libraries to their current project.
+CLASSPATH.) The path separator is ":" under Solaris, Mac and Linux. 
+
+<h5> <a name="atomicjarfiles">Atomic JAR files</a> </h5>
 
-</P>
-<P>
+<p>
 
-Note that the per-platform zip archives contain many more jar files
-than just the three or four mentioned above. The additional jars
+Note that the 7zip archive contain more jar files
+than just the above mentioned. Additional atomic jars <code>jogamp-all-platforms/jar/atomic/</code>
 illustrate how JOGL may be partitioned to achieve a smaller deployment
-size, in particular on smaller devices.
+size, in particular on smaller devices. See <a href="../deployment/JOGL-DEPLOYMENT.html">deployment</a> for details.
+
+</p>
+
+<h4> <a name="automatednativelibraryloading">Automated Native Library Loading</a> </h4>
+
+<p>
+
+JOGL 2.0 has a brand new feature allowing to automatically extract the proper native 
+libraries required to use JOGL from JARs containing them without relying on the Java 
+library path or any platform-dependent environment variable allowing to set the location 
+of native libraries. This allows desktop applications as well as traditional Applets 
+to utilize the native library JAR files the same way Webstart/JNLP does.
+
+</p>
+
+<p>
+To allow the native JAR file library loading to work, ensure that all JogAmp JAR files
+are left unmodified within their common directory.
+</p>
+
+<p>
+In case the native library JAR files cannot be opened, it falls back to the traditional 
+native library loading mechanism via the java library path.
+</p>
+
+<p>
+
+This feature is enabled by default and - for whatever reason - it can be disabled by setting the 
+property <code>jogamp.gluegen.UseTempJarCache</code>
+to false (as a VM argument, <code>-Djogamp.gluegen.UseTempJarCache=false</code> in command line).
 
-</P>
-<P>
+</p>
+
+<h4> <a name="traditionallibraryloading">Traditional Native Library Loading</a> </h4>
+
+<p>
+
+If you don't use <a href="#automatednativelibraryloading">automatic native libraries loading</a>,
+as enabled by default, you must set either the VM property <code>java.library.path</code> 
+or the platform-dependent environment variable used for the location of native libraries,
+<code>PATH</code> on Windows, <code>LD_LIBRARY_PATH</code> on Unix (Linux, Solaris, ..)
+and <code>DYLD_LIBRARY_PATH</code> on Mac OS X.
+The environment variable shall contain the full path to the "lib" directory; for example, on Windows, add
+<code>"C:\Users\myhome\jogamp-all-platforms\lib\windows-amd64"</code> to your PATH using
+the System control panel, Advanced tab, Environment Variables
+button. At this point your Java installation should be able to see the Jogl class files.
+
+</p>
+
+<h4> <a name="ideusers">Settings for IDE's users</a> </h4>
+
+<p>
+
+Eclipse users must add the JARs containing Java libraries into the Java 
+Build Path of their project. They must set the native library location 
+of these JARs if they have disabled the automatic extraction of native 
+libraries. Netbeans users must add the JARs containing Java libraries 
+into their project. In the “project” tab, select the "Libraries" node, 
+select the item "Add JAR/Folder" and select the required JARs. Users of 
+other IDEs should consult the IDE's documentation to see how to add jar 
+files and native libraries to their current project.
+
+</p>
+
+<h4> <a name="badpractice">Bad practice</a> </h4>
+
+<p>
 
 Dropping the JOGL jars and native libraries into the extension
 directory of the JRE is <b>strongly discouraged</b>. Doing so will
 cause conflicts with third-party applications launched via Java Web
 Start, and causes confusion later when upgrading the distribution.
 
-</P>
-<P>
+</p>
+<p>
 
 If you are on the Linux platform, please see the Linux-specific
 platform notes, below, with information on incompatibility between the
-JPackage Java RPMs and JOGL.
+JPackage Java RPMs and JOGL. 
 
-</P>
+</p>
 
-<H3> Java Web Start integration </H3>
+<h4> <a name="notefordebianusers">Note for Debian Linux users</a> </h4>
 
-<P>
+<p>
 
-The recommended distribution vehicle for applications using JOGL is
-Java Web Start. JOGL-based applications do not even need to be signed;
-all that is necessary is to reference the JOGL extension JNLP file.
-Because the JOGL jar files are signed, an unsigned application can
-reference the signed JOGL library and continue to run inside the
-sandbox.
+DEB packages are available for this distribution on its official repositories.
 
-</P>
-<P>
+</p>
 
-Please read <a href="../deployment/JOGL-DEPLOYMENT.html">JOGL Deployment</a>.
+<h3> <a name="onlinedeployment">Online Deployment</a> </h3>
 
-<H3> Applet support </H3>
+The recommended distribution vehicle for <i>online</i> applications using JOGL is
+either using Applets or Java Web Start. JOGL-based applications do not even need to be signed;
+all that is necessary is to reference the online resources using the appropriate URLs.
 
-<P>
-
-Lilian Chamontin, in conjunction with several other members of the
-JOGL community, has contributed a JOGL applet installer. This
-installer uses some clever tricks to allow deployment of unsigned
-applets which use JOGL into existing web browsers and JREs as far back
-as 1.4.2, which is the earliest version of Java supported by JOGL.
+<p>
+Please read <a href="../deployment/JOGL-DEPLOYMENT.html">JOGL Deployment</a>.
+</p>
 
-</P>
-<P>
+<h4> <a name="applets">Applets</a> </h4>
 
-The JOGLAppletInstaller is distributed inside jogl.jar as a utility
-class in com.jogamp.opengl.util. It requires that the developer host a
-local, signed copy of jogl.jar and all of the jogl-natives jars; the
-certificates must be the same on all of these jars. Note that in the
-release builds of JOGL all of these jars are signed by Sun
-Microsystems, so the developer can deploy applets without needing any
-certificates.
+<p>
+You might want to have a look at our <a href="../../../deployment/jogamp-current/jogl-test-applets.html">Test page for JOGL Applet</a>
+</p>
 
-</P>
-<P>
+Here are documented Applet launch examples:
+<ol>
+  <li> <a href="../../../deployment/jogamp-current/jogl-applet-runner-newt-gears-normal-napplet.html">Pure Applet</a> (<b>recommended</b>)</li>
+  <li> <a href="../../../deployment/jogamp-current/jogl-applet-runner-newt-gears-normal.html">JNLP Applet w/ AppletLauncher-fallback </a></li>
+</ol>
 
-The JOGLAppletInstaller javadoc describes the basic steps for
-deployment of an applet utilizing JOGL. Please refer to this
-documentation for more information. A live example of deploying an
-unsigned JOGL applet will be added to this documentation shortly once
-the first signed build of the JOGLAppletInstaller has been shipped.
+<h4> <a name="jnlpwebstart">JNLP / Webstart</a> </h4>
 
-</P>
+<p>
+Here is a documented <a href="../../../deployment/jogamp-current/jogl-applet-runner-newt-gears-normal.html">JNLP Applet w/ AppletLauncher-fallback </a>,
+which also documents how to utilize JOGL via WebStart with slight modifications.
+</p>
 
-<H2> GLDrawable and GLContext </H2>
+<h2> <a name="joglapi">Using the JOGL API</a> </h2>
 
-<P>
+<h3> <a name="gldrawableandglcontext">GLDrawable and GLContext</a> </h3>
+<p>
 
-The JSR-231 APIs specify interfaces two low-level OpenGL abstractions:
+The APIs specify interfaces two low-level OpenGL abstractions:
 drawables and contexts. An OpenGL drawable is effectively a surface
 upon which OpenGL rendering will be performed. In order to perform
 rendering, an OpenGL rendering context is needed. Contexts and
 drawables typically go hand-in-hand. More than one context may be
-created for a particular drawable. In the JSR-231 abstractions, a
+created for a particular drawable. In these abstractions, a
 context is always associated with exactly one drawable.
 
-</P>
-<P>
+</p>
+
+<p>
 
 Most end users will not need to use these abstractions directly.
 However, when sharing textures, display lists and other OpenGL objects
 between widgets, the concrete identifier for the "namespace" for these
 objects is the GLContext.
 
-</P>
+</p>
+
+<h3> GLProfile </h3>
+
+<p>
+
+GLProfile instances maps OpenGL profiles introduced in OpenGL 3, please read <a href="../Overview-OpenGL-Evolution-And-JOGL.html">this</a> for more details.
 
-<H2> Creating a GLAutoDrawable </H2>
+</p>
 
-<P>
+<h3> Creating a GLAutoDrawable </h3>
 
-Jogl provides two basic widgets into which OpenGL rendering can be
+<p>
+
+Jogl provides three basic widgets into which OpenGL rendering can be
 performed. The GLCanvas is a heavyweight AWT widget which supports
 hardware acceleration and which is intended to be the primary widget
 used by applications. The GLJPanel is a fully Swing-compatible
@@ -269,41 +373,41 @@ JDK has sped up the GLJPanel significantly when the Java2D OpenGL
 pipeline is enabled; see <a
 href="http://www.javagaming.org/forums/index.php?topic=10813.0">this
 forum discussion</a> for more details.
+GLWindow is a NEWT widget which supports hardware acceleration and which 
+is intended to be the primary widget used by AWT-less applications.
 
-</P>
-<P>
+</p>
 
-Both the GLCanvas and GLJPanel implement a common interface called
+GLCanvas, GLWindow and GLJPanel implement a common interface called
 GLAutoDrawable so applications can switch between them with minimal
 code changes. The GLAutoDrawable interface provides
 
-<UL>
+<ul>
 
-  <LI> access to the GL object for calling OpenGL routines
+  <li> access to the GL object for calling OpenGL routines</li>
 
-  <LI> a callback mechanism (GLEventListener) for performing OpenGL
-  rendering
+  <li> a callback mechanism (GLEventListener) for performing OpenGL
+  rendering</li>
 
-  <LI> a <CODE>display()</CODE> method for forcing OpenGL rendering to
-  be performed synchronously
+  <li> a <code>display()</code> method for forcing OpenGL rendering to
+  be performed synchronously</li>
 
-  <LI> AWT- and Swing-independent abstractions for getting and setting
-  the size of the widget and adding and removing event listeners
+  <li> AWT- and Swing-independent abstractions for getting and setting
+  the size of the widget and adding and removing event listeners</li>
 
-</UL>
+</ul>
 
-</P>
-<P>
+<p>
 
-When creating GLCanvas and GLJPanel instances, the user may request a
+When creating GLCanvas, GLWindow and GLJPanel instances, the user may request a
 certain set of OpenGL parameters in the form of a GLCapabilities
 object, customize the format selection algorithm by specifying a
 GLCapabilitiesChooser, share textures and display lists with other
 GLDrawables, and specify the display device on which the
-GLAutoDrawable will be created (GLCanvas only).
+GLAutoDrawable will be created (GLCanvas and GLWindow only).
 
-</P>
-<P>
+</p>
+<p>
 
 A GLCapabilities object specifies the OpenGL parameters for a
 newly-created widget, such as the color, alpha,, z-buffer and
@@ -312,8 +416,8 @@ double-buffered. The default capabilities are loosely specified but
 provide for truecolor RGB, a reasonably large depth buffer,
 double-buffered, with no alpha, stencil, or accumulation buffers. 
 
-</P>
-<P>
+</p>
+<p>
 
 An application can override the default pixel format selection
 algorithm by providing a GLCapabilitiesChooser to the GLCanvas or
@@ -328,8 +432,8 @@ array. The DefaultGLCapabilitiesChooser uses the window system's
 recommendation when it is available, and otherwise attempts to use a
 platform-independent selection algorithm.
 
-</P>
-<P>
+</p>
+<p>
 
 The GLJPanel can be made non-opaque according to Swing's rendering
 model, so it can act as an overlay to other Swing or Java2D drawing.
@@ -340,11 +444,11 @@ rendering underneath it will then show through areas where OpenGL has
 produced an alpha value less than 1.0. See the JGears and JRefract
 demos for examples of how to use this functionality.
 
-</P>
+</p>
 
-<H2> Writing a GLEventListener </H2>
+<h3> Writing a GLEventListener </h3>
 
-<P>
+<p>
 
 Applications implement the GLEventListener interface to perform OpenGL
 drawing via callbacks. When the methods of the GLEventListener are
@@ -352,26 +456,26 @@ called, the underlying OpenGL context associated with the drawable is
 already current. The listener fetches the GL object out of the
 GLAutoDrawable and begins to perform rendering.
 
-</P>
-<P>
+</p>
+<p>
 
-The <CODE>init()</CODE> method is called when a new OpenGL context is
+The <code>init()</code> method is called when a new OpenGL context is
 created for the given GLAutoDrawable. Any display lists or textures
 used during the application's normal rendering loop can be safely
-initialized in <CODE>init()</CODE>. It is important to note that
+initialized in <code>init()</code>. It is important to note that
 because the underlying AWT window may be destroyed and recreated while
 using the same GLCanvas and GLEventListener, the GLEventListener's
-<CODE>init()</CODE> method may be called more than once during the
+<code>init()</code> method may be called more than once during the
 lifetime of the application. The init() method should therefore be
 kept as short as possible and only contain the OpenGL initialization
-required for the <CODE>display()</CODE> method to run properly. It is
+required for the <code>display()</code> method to run properly. It is
 the responsibility of the application to keep track of how its various
 OpenGL contexts share display lists, textures and other OpenGL objects
 so they can be either be reinitialized or so that reinitialization can
-be skipped when the <CODE>init()</CODE> callback is called.
+be skipped when the <code>init()</code> callback is called.
 
-</P>
-<P>
+</p>
+<p>
 
 Note also that the GLEventListener should be added to the
 GLAutoDrawable before the GLAutoDrawable is shown or rendered to for
@@ -381,24 +485,24 @@ maintain internal state to keep track of whether init() has been
 called on a particular GLEventListener since the last time an OpenGL
 context was created for that GLAutoDrawable.
 
-</P>
-<P>
+</p>
+<p>
 
-The <CODE>display()</CODE> method is called to perform per-frame
-rendering. The <CODE>reshape()</CODE> method is called when the
+The <code>display()</code> method is called to perform per-frame
+rendering. The <code>reshape()</code> method is called when the
 drawable has been resized; the default implementation automatically
 resizes the OpenGL viewport so often it is not necessary to do any
-work in this method.  The <CODE>displayChanged()</CODE> method is
+work in this method.  The <code>displayChanged()</code> method is
 designed to allow applications to support on-the-fly screen mode
 switching, but support for this is not yet implemented so the body of
 this method should remain empty.
 
-</P>
-<P>
+</p>
+<p>
 
 It is strongly recommended that applications always refetch the GL
 object out of the GLAutoDrawable upon each call to the
-<CODE>init()</CODE>, <CODE>display()</CODE> and <CODE>reshape()</CODE>
+<code>init()</code>, <code>display()</code> and <code>reshape()</code>
 methods and pass the GL object down on the stack to any drawing
 routines, as opposed to storing the GL in a field and referencing it
 from there. The reason is that multithreading issues inherent to the
@@ -409,29 +513,78 @@ thread that does not have a current context. This will usually cause
 the application to crash. For more information please see the section
 on multithreading.
 
-</P>
+</p>
+
+<h3> Checking extensions and functions availability </h3>
+
+<p>
+
+GLBase.isFunctionAvailable(String glFunctionName) and 
+GLBase.isExtensionAvailable(String glExtensionName) allow to check whether 
+OpenGL functions and extensions are available.
+
+</p>
+
+<h3> Use of NIO buffers </h3>
+
+<p>
+
+Use com.jogamp.common.nio.Buffers to create any NIO buffer intented to be 
+used by JOGL in order to avoid native ordering and size problems. Jogl does 
+not modify the position of a buffer passed to its methods but such a position 
+affects its behaviour. Direct NIO buffers are faster and should be used when 
+performances are important. Indirect NIO buffers can be used for non critical 
+operations, for example to retrieve the value of an OpenGL constant. Keep in 
+mind that direct NIO buffers are page-aligned and allocated in the native heap 
+(whereas indirect NIO buffers are allocated in Java heap). Use the VM argument 
+"-XX:MaxDirectMemorySize" to increase the maximum size of the direct memory if 
+the creation of direct NIO buffers fails, use the VM argument "-Xmx" to increase 
+the maximum size of Java heap if the creation of undirect NIO buffers fails.
+
+</p>
 
-<H2> Using the Composable Pipeline </H2>
+<h3> Documentation of C language functions matching with Jogl methods </h3>
 
-<P>
+<p>
+
+Jogl documentation often refers to C language functions. You can find the 
+documentation of these functions in OpenGL references pages <a href="http://www.opengl.org/sdk/docs/">here</a>.
+
+</p>
+
+<h3> Performance </h3>
+
+<p>
+
+JOGL has a low memory footprint. It uses direct NIO buffers in order to avoid 
+copying data both in Java heap and in the native heap when calling native functions. 
+JOGL accesses OpenGL through JNI; as a JNI call only takes a few nanoseconds, it 
+does not drive programs using JOGL noticeably slower than their C/C++ equivalents.
+
+</p>
+
+<h2> Using the Composable Pipeline </h2>
+
+<p>
 
 Jogl supports the "composable pipeline" paradigm introduced by the
 Magician Java binding for OpenGL. The DebugGL pipeline calls
-<CODE>glGetError</CODE> after each OpenGL call, reporting any errors
+<code>glGetError</code> after each OpenGL call, reporting any errors
 found. It can greatly speed up development time because of its
 fine-grained error checking as opposed to the manual error checking
 usually required in OpenGL programs written in C. The TraceGL prints
 logging information upon each OpenGL call and is helpful when an
 application crash makes it difficult to see where the error occurred.
 
-</P>
-<P>
+</p>
+<p>
 
-To use these pipelines, call <CODE>GLAutoDrawable.setGL</CODE> at the
-beginning of the <CODE>init</CODE> method in your GLEventListener. For
+To use these pipelines, call <code>GLAutoDrawable.setGL</code> at the
+beginning of the <code>init</code> method in your GLEventListener. For
 example,
+</p>
 
-<PRE>
+<pre>
 class MyListener implements GLEventListener {
   public void init(GLDrawable drawable) {
     drawable.setGL(new DebugGL(drawable.getGL()));
@@ -440,10 +593,9 @@ class MyListener implements GLEventListener {
 
   // ...
 }
-</PRE>
+</pre>
 
-</P>
-<P>
+<p>
 
 Note that the GLAutoDrawable.setGL() method simply calls setGL() on
 the default OpenGL context created by the GLAutoDrawable, so
@@ -453,11 +605,49 @@ in the context object itself. The composable pipeline needs to be
 re-installed every time GLContext.makeCurrent() returns
 CONTEXT_CURRENT_NEW.
 
-</P>
+</p>
+
+<p>
+N.B: DebugGL and TraceGL have been splitted into several classes matching 
+with all GL subclasses.
+</p>
+
+<pre>
+
+if (drawable.getGL().isGL4bc()) {
+    final GL4bc gl4bc = drawable.getGL().getGL4bc();
+    drawable.setGL(new DebugGL4bc(gl4bc));
+} 
+else {
+    if (drawable.getGL().isGL4()) {
+        final GL4 gl4 = drawable.getGL().getGL4();
+        drawable.setGL(new DebugGL4(gl4));
+    }
+    else {
+          if (drawable.getGL().isGL3bc()) {
+              final GL3bc gl3bc = drawable.getGL().getGL3bc();
+              drawable.setGL(new DebugGL3bc(gl3bc));
+          }
+          else {
+              if (drawable.getGL().isGL3()) {
+                  final GL3 gl3 = drawable.getGL().getGL3();
+                  drawable.setGL(new DebugGL3(gl3));
+              }
+              else {
+                  if (drawable.getGL().isGL2()) {
+                      final GL2 gl2 = drawable.getGL().getGL2();
+                      drawable.setGL(new DebugGL2(gl2));
+                  }
+              }
+          }
+     }
+}
+
+</pre>
 
-<H2> Heavyweight and Lightweight Issues </H2>
+<h2> Heavyweight and Lightweight Issues </h2>
 
-<P>
+<p>
 
 As mentioned above, JOGL supplies both a heavyweight (GLCanvas) and a
 lightweight (GLJPanel) widget to be able to provide the fastest
@@ -473,18 +663,18 @@ see the Swing Connection article mentioned above for details on mixing
 heavyweight and lightweight widgets. A couple of common pitfalls are
 described here.
 
-</P>
-<P>
+</p>
+<p>
 
 When using JPopupMenus or Swing tool tips in conjunction with the
 GLCanvas, it is necessary to disable the use of lightweight widgets
 for the popups. See the methods
-<CODE>ToolTipManager.setLightWeightPopupEnabled</CODE>,
-<CODE>JPopupMenu.setLightWeightPopupEnabled</CODE>, and
-<CODE>JPopupMenu.setDefaultLightWeightPopupEnabled</CODE>.
+<code>ToolTipManager.setLightWeightPopupEnabled</code>,
+<code>JPopupMenu.setLightWeightPopupEnabled</code>, and
+<code>JPopupMenu.setDefaultLightWeightPopupEnabled</code>.
 
-</P>
-<P>
+</p>
+<p>
 
 There are occasionally problems with certain LayoutManagers and
 component configurations where if a GLCanvas is placed in the middle
@@ -503,8 +693,8 @@ matter, but for others like the BoxLayout it does. See the test case
 attached to Issue 135 for an example. Replacing the GLCanvas with an
 ordinary Canvas yields the same behavior.
 
-</P>
-<P>
+</p>
+<p>
 
 One suggestion was to override getPreferredSize() so that if a
 preferred size has not been set by the user, to default to (0,
@@ -520,18 +710,18 @@ demo breaks in the same way it originally did. Therefore this solution
 is fragile because it isn't clear which of these methods are used
 internally by the AWT and for what purposes.
 
-</P>
-<P>
+</p>
+<p>
 
 There are two possible solutions, both application-specific. The best
 and most portable appears to be to put the GLCanvas into a JPanel and
 set the JPanel's preferred size to (0, 0). The JPanel will cause this
 constraint to be enforced on its contained GLCanvas. The other
-workaround is to call <CODE>setPreferredSize(new Dimension(0,
-0))</CODE> on a newly-created GLCanvas; this method is new in 1.5.
+workaround is to call <code>setPreferredSize(new Dimension(0,
+0))</code> on a newly-created GLCanvas; this method is new in 1.5.
 
-</P>
-<P>
+</p>
+<p>
 
 Another issue that occasionally arises on Windows is flickering during
 live resizing of a GLCanvas. This is caused by the AWT's repainting
@@ -539,17 +729,35 @@ the background of the Canvas and can not be overridden on a per-Canvas
 basis, for example when subclassing Canvas into GLCanvas.  The
 repainting of the background of Canvases on Windows can be disabled by
 specifying the system property
-<CODE>-Dsun.awt.noerasebackground=true</CODE>. Whether to specify this
+<code>-Dsun.awt.noerasebackground=true</code>. Whether to specify this
 flag depends on the application and should not be done universally,
 but instead on a case-by-case basis. Some more detail is in the thread
 <a href="http://javagaming.org/forums/index.php?topic=8770.0">"TIP:
 JOGL + Swing flicker"</a> in the JOGL forum.
 
-</P>
+</p>
+
+<h2> SWT/AWT issues </h2>
+
+<p>
+
+The AWT GLCanvas has to be created once the size of the frame that contains it 
+is no more zero. It is highly advised to do it inside a component listener 
+so that it is called when the frame is resized. This listener has to be 
+immediately removed after the creation of the canvas.
+
+Laying out the frame (by calling <code>doLayout()</code>) before starting the animator (or calling <code>display()</code>) is necessary because 
+the width of the canvas cannot be equal to zero and the SWT/AWT helper returns 
+AWT frames with a strange behavior (width and height equal to zero, lazy layout 
+and validation).
 
-<H2> Multithreading Issues </H2>
+</p>
 
-<P>
+<h2> AWT Multithreading Issues </h2>
+
+Below statements incorrect!
+
+<p>
 
 Jogl was designed to interoperate with the AWT, an inherently
 multithreaded GUI toolkit. OpenGL, in contrast, was originally
@@ -558,50 +766,50 @@ reason Jogl provides a framework in which it is possible to write
 correct multithreaded OpenGL applications using the GLEventListener
 paradigm.
 
-</P>
-<P>
+</p>
+<p>
 
 If an application written using Jogl interacts in any way with the
 mouse or keyboard, the AWT is processing these events and the
 multithreaded aspects of the program must be considered.
 
-</P>
-<P>
+</p>
+<p>
 
 OpenGL applications usually behave in one of two ways: either they
 repaint only on demand, for example when mouse input comes in, or they
 repaint continually, regardless of whether user input is coming in. In
 the repaint-on-demand model, the application can merely call
-<CODE>GLAutoDrawable.display()</CODE> manually at the end of the mouse
+<code>GLAutoDrawable.display()</code> manually at the end of the mouse
 or keyboard listener to cause repainting to be done. Alternatively if
 the application knows the concrete type of the GLDrawable it can call
 repaint() to have the painting scheduled for a later time.
 
-</P>
-<P>
+</p>
+<p>
 
 In the continuous repaint model, the application typically has a main
-loop which is calling <CODE>GLAutoDrawable.display()</CODE>
+loop which is calling <code>GLAutoDrawable.display()</code>
 repeatedly, or is using the Animator class, which does this
 internally. In both of these cases the OpenGL rendering will be done
 on this thread rather than the internal AWT event queue thread which
 dispatches mouse and keyboard events.
 
-</P>
-<P>
+</p>
+<p>
 
 Both of these models (repaint-on-demand and repaint continually) still
 require the user to think about which thread keyboard and mouse events
 are coming in on, and which thread is performing the OpenGL rendering.
-OpenGL rendering <B>may not</B> occur directly inside the mouse or
+OpenGL rendering <b>may not</b> occur directly inside the mouse or
 keyboard handlers, because the OpenGL context for the drawable is not
 current at this point (hence the warning about storing a GL object in
 a field, where it can be fetched and accidentally used by another
 thread). However, a mouse or keyboard listener may invoke
-<CODE>GLAutoDrawable.display()</CODE>.
+<code>GLAutoDrawable.display()</code>.
 
-</P>
-<P>
+</p>
+<p>
 
 It is generally recommended that applications perform as little work
 as possible inside their mouse and keyboard handlers to keep the GUI
@@ -609,16 +817,16 @@ responsive. However, since OpenGL commands can not be run from
 directly within the mouse or keyboard event listener, the best
 practice is to store off state when the listener is entered and
 retrieve this state during the next call to
-<CODE>GLEventListener.display()</CODE>.
+<code>GLEventListener.display()</code>.
 
-</P>
-<P>
+</p>
+<p>
 
 Furthermore, it is recommended that if there are long computational
-sequences in the GLEventListener's <CODE>display</CODE> method which
+sequences in the GLEventListener's <code>display</code> method which
 reference variables which may be being simultaneously modified by the
 AWT thread (mouse and keyboard listeners) that copies of these
-variables be made upon entry to <CODE>display</CODE> and these copies
+variables be made upon entry to <code>display</code> and these copies
 be referenced throughout display() and the methods it calls. This will
 prevent the values from changing while the OpenGL rendering is being
 performed. Errors of this kind show up in many ways, including certain
@@ -628,13 +836,13 @@ the scene. Restructuring the display() method as described has solved
 all instances of this kind of error that have been seen with Jogl to
 date.
 
-</P>
-<P>
+</p>
+<p>
 
 Prior to Jogl 1.1 b10, the Jogl library attempted to give applications
 strict control over which thread or threads performed OpenGL
-rendering. The <CODE>setRenderingThread()</CODE>,
-<CODE>setNoAutoRedrawMode()</CODE> and <CODE>display()</CODE> APIs
+rendering. The <code>setRenderingThread()</code>,
+<code>setNoAutoRedrawMode()</code> and <code>display()</code> APIs
 were originally designed to allow the application to create its own
 animation thread and avoid OpenGL context switching on platforms that
 supported it. Unfortunately, serious stability issues caused by
@@ -643,8 +851,8 @@ platform implementation have arisen on three of Jogl's major supported
 platforms: Windows, Linux and Mac OS X. In order to address these
 bugs, the threading model in Jogl 1.1 b10 and later has changed.
 
-</P>
-<P>
+</p>
+<p>
 
 All GLEventListener callbacks and other internal OpenGL context
 management are now performed on one thread. (In the current
@@ -652,17 +860,17 @@ implementation, this thread is the AWT event queue thread, which is a
 thread internal to the implementation of the AWT and which is always
 present when the AWT is being used. Future versions of Jogl may change
 the thread on which the OpenGL work is performed.) When the
-<CODE>GLAutoDrawable.display()</CODE> method is called from user code,
+<code>GLAutoDrawable.display()</code> method is called from user code,
 it now performs the work synchronously on the AWT event queue thread,
 even if the calling thread is a different thread. The
-<CODE>setRenderingThread()</CODE> optimization is now a no-op. The
-<CODE>setNoAutoRedrawMode()</CODE> API still works as previously
+<code>setRenderingThread()</code> optimization is now a no-op. The
+<code>setNoAutoRedrawMode()</code> API still works as previously
 advertised, though now that all work is done on the AWT event queue
 thread it no longer needs to be used in most cases. (It was previously
 useful for working around certain kinds of OpenGL driver bugs.)
 
-</P>
-<P>
+</p>
+<p>
 
 Most applications will not see a change in behavior from this change
 in the Jogl implementation. Applications which use thread-local
@@ -670,28 +878,28 @@ storage or complex multithreading and synchronization may see a change
 in their control flow requiring code changes. While it is strongly
 recommended to change such applications to work under the new
 threading model, the old threading model can be used by specifying the
-system property <CODE>-Djogl.1thread=auto</CODE> or
-<CODE>-Djogl.1thread=false</CODE>. The "auto" setting is equivalent to
+system property <code>-Djogl.1thread=auto</code> or
+<code>-Djogl.1thread=false</code>. The "auto" setting is equivalent to
 the behavior in 1.1 b09 and before, where on ATI cards the
 single-threaded mode would be used. The "false" setting is equivalent
 to disabling the single-threaded mode. "true" is now the default
 setting.
 
-</P>
-<P>
+</p>
+<p>
 
-In the JSR-231 APIs the single-threaded behavior continues to be the
-default and the <CODE>setRenderingThread()</CODE> and
-<CODE>setNoAutoRedrawMode()</CODE> APIs have been removed. The public
-<CODE>Threading</CODE> class still provides some control over the
+In the APIs the single-threaded behavior continues to be the
+default and the <code>setRenderingThread()</code> and
+<code>setNoAutoRedrawMode()</code> APIs have been removed. The public
+<code>Threading</code> class still provides some control over the
 internal use of threads in the library as well as external access to
 these mechanisms.
 
-</P>
+</p>
 
-<H2> Pbuffers </H2>
+<h2> Pbuffers </h2>
 
-<P>
+<p>
 
 Jogl exposes hardware-accelerated offscreen rendering (pbuffers) with
 a minimal and platform-agnostic API. Several recent demos have been
@@ -700,18 +908,18 @@ However, the pbuffer support in Jogl remains one of the more
 experimental aspects of the package and the APIs may need to change in
 the future.
 
-</P>
-<P>
+</p>
+<p>
 
 To create a pbuffer, call
-<CODE>GLDrawableFactory.createGLPbuffer()</CODE>. It is wise to call
-<CODE>GLDrawableFactory.canCreateGLPbuffer()</CODE> first to ensure
+<code>GLDrawableFactory.createGLPbuffer()</code>. It is wise to call
+<code>GLDrawableFactory.canCreateGLPbuffer()</code> first to ensure
 the graphics card has pbuffer support first. The pbuffer is created
 immediately and is available for rendering as soon as
-<CODE>createGLPbuffer</CODE> returns.
+<code>createGLPbuffer</code> returns.
 
-</P>
-<P>
+</p>
+<p>
 
 A pbuffer is used in conjunction with the GLEventListener mechanism by
 calling its display() method. Rendering, as always, occurs while the
@@ -721,11 +929,11 @@ which can make it easier to operate upon the resulting pixels. These
 APIs are however highly experimental and not yet implemented on all
 platforms.
 
-</P>
+</p>
 
-<H2> GLU </H2>
+<h2> GLU </h2>
 
-<P>
+<p>
 
 Jogl contains support for the GLU (OpenGL Utility Library) version
 1.3. Jogl originally supported GLU by wrapping the C version of the
@@ -735,110 +943,99 @@ pure Java port is enabled by default, and addresses stability issues
 on certain Linux distributions as well as the lack of native GLU 1.3
 support on the Windows platform. In case of problems with the Java
 port, the C version of the GLU library may be used by specifying the
-system property <CODE>-Djogl.glu.nojava</CODE> on the command
+system property <code>-Djogl.glu.nojava</code> on the command
 line. All of the same functionality is exposed with both the Java and
 C versions of the GLU library; currently NURBS support is the only
 missing feature on both sides. If you run into problems with the Java
 port of the GLU library please file a bug using the Issue Tracker on
 the Jogl home page.
 
-</P>
-<P>
+</p>
+<p>
 
-To use the GLU, simply instantiate a GLU object via <CODE>new
-GLU()</CODE> at the beginning of your program. The methods on the GLU
+To use the GLU, simply instantiate a GLU object via <code>new
+GLU()</code> at the beginning of your program. The methods on the GLU
 object may be called at any point when an OpenGL context is current.
 Because the GLU implementation is not thread-safe, one GLU object
 should be created for each GLEventListener or other entity performing
 OpenGL rendering in a given thread.
 
-</P>
+</p>
+<p>
+
+N.B: Some GLU features are only implemented in the subclass GLUgl2.
+
+</p>
 
-<H2> More Resources </H2>
+<h2> More Resources </h2>
 
-<P>
+<p>
+Our <a href="../../../wiki/">Wiki pages</a>,
+have a look at the 
+<a href="../../../wiki/index.php/Jogl_Tutorial">Jogl Tutorial</a> resource listing.
+</p>
 
-The <A HREF="http://javagaming.org/forums/index.php?board=25.0">JOGL
-forum</A> on <A HREF="http://javagaming.org/">javagaming.org</A> is
-the best place to ask questions about the library. Many users, as well
+<p>
+
+The <a href="http://forum.jogamp.org/">JOGL forum</a> 
+is the best place to ask questions about the library. Many users, as well
 as the Jogl developers, read this forum frequently, and the archived
 threads contain a lot of useful information (which still needs to be
 distilled into documentation).
 
-</P>
-<P>
+</p>
+<p>
 
-The <A HREF="http://download.java.net/media/jogl/demos/www/">JOGL demos</A> provide
+The <a href="../../../jogl-demos/www/">JOGL demos</a> provide
 several examples of usage of the library.
 
-</P>
-<P>
-
-Pepijn Van Eeckhoudt, Kevin Duling and Abdul Bezrati have done <A
-HREF="http://pepijn.fab4.be/software/nehe-java-ports/">JOGL ports of
-many of the the NeHe demos</A>. These are small examples of various
-pieces of OpenGL functionality. See also the <A
-HREF="http://nehe.gamedev.net/">NeHe web site</A>.
-
-</P>
-<P>
+</p>
+<p>
 
-Pepijn also did a <A
-HREF="http://www.glexcess.com/files/glexcess.jar">JOGL port</a> of
-Paolo Martella's <A HREF="http://www.glexcess.com/">GLExcess</A>
-demo. To see the news update about this port, go to the main GLExcess
-site and scroll down.
+Pepijn Van Eeckhoudt, Kevin Duling and Abdul Bezrati have done <a
+href="http://pepijn.fab4.be/software/nehe-java-ports/">JOGL ports of
+many of the the NeHe demos</a>. These are small examples of various
+pieces of OpenGL functionality. See also the <a
+href="http://nehe.gamedev.net/">NeHe web site</a>.
 
-</P>
-<P>
+</p>
 
-Gregory Pierce's <A
-HREF="http://javagaming.org/forums/index.php?topic=1474.0">introduction
-to JOGL</a> is a useful tutorial on starting to use the JOGL library.
+<p>
 
-</P>
-<P>
+For release information about the JOGL library, please see the 
+<a href="../../../wiki/index.php/Jogamp_Versioning_and_Releases">Jogamp Versioning and Release</a>.
 
-For release information about the JOGL library, please see the <A
-HREF="http://javagaming.org/forums/index.php?topic=1596.0">JOGL Release
-Information</A> thread on the JOGL forum on javagaming.org.
+</p>
+<p>
 
-</P>
-<P>
+Please post on the <a href="http://forum.jogamp.org/">JOGL forum</a> 
+if you have a resource you'd like to add to this documentation
+or like to edit the <a href="../../../wiki/index.php">Wiki Pages</a> yourself.
 
-Please post on the JOGL forum if you have a resource you'd like to add
-to this documentation.
+</p>
 
-</P>
+<h2> Platform Notes </h2>
 
-<H2> Platform Notes </H2>
+<h3> All Platforms </h3>
 
-<H3> All Platforms </H3>
-
-<P>
+<p>
 
 The following issues, among others, are outstanding on all platforms:
 
-</P>
+</p>
 
-<UL>
+<ul>
 
-<LI> A few remaining stability issues, mostly on older graphics cards.
+<li> A few remaining stability issues, mostly on older graphics cards.</li>
 
-<LI> JOGL now supports experimental integration and interoperability
-with the Java2D/OpenGL pipeline in Java SE 6 (Mustang), enabling a
-much faster GLJPanel as well as other features. Please see <a
-href="http://www.javagaming.org/forums/index.php?topic=10813.0">this
-forum discussion</a> for more details.
-
-</UL>
+</ul>
 
-<H3> Windows </H3>
+<h3> Windows </h3>
 
-<P>
+<p>
 
 For correct operation, it is necessary to specify the system property
-<CODE>-Dsun.java2d.noddraw=true</CODE> when running JOGL applications
+<code>-Dsun.java2d.noddraw=true</code> when running JOGL applications
 on Windows; this system property disables the use of DirectDraw by
 Java2D. There are driver-level incompatibilities between DirectDraw
 and OpenGL which manifest themselves as application crashes, poor
@@ -848,167 +1045,51 @@ same application, not even just in the same window, so disabling
 Java2D's DirectDraw pipeline and forcing it to use its GDI pipeline is
 the only way to work around these issues. Java Web Start applications
 may set this system property by adding the following line to the
-<CODE><resources></CODE> section of the JNLP file: <PRE>
-<property name="sun.java2d.noddraw" value="true"/> </PRE>
-
-</P>
-<P>
-
-There is a serious memory leak in ATI's OpenGL drivers which is
-exhibited on Windows XP on Mobility Radeon 9700 hardware. It's
-possible it will be present on other hardware as well though it was
-not reproducible at the time of this writing on desktop Radeon
-hardware or older ATI mobile chips. The bug is documented in <A
-HREF="https://jogl.dev.java.net/issues/show_bug.cgi?id=166">JOGL Issue
-166</A> and a bug has been filed with ATI. You can confirm the
-presence of the bug either with the test case in that bug report or by
-simply running the Gears demo; if the process size grows over time in
-the Task Manager, the memory leak is present on your hardware. For the
-time being, you can work around this memory leak by specifying the
-system property <CODE>-Djogl.GLContext.nofree</CODE> on the command
-line when launching your JOGL applications. There is no good
-general-purpose workaround for this bug which behaves well on all
-hardware.
-
-</P>
-
-<H3> Linux </H3>
-
-<P>
-
-The Sun JDK "compatibility" RPMs (java-1.5.0-sun-compat,
-java-1.6.0-sun-compat) provided by jpackage.org are incompatible with
-JOGL. These RPMs symlink an internal JDK directory to /usr/lib, which
-overrides how both NVidia and ATI currently provide their drivers to
-some Linux distributions, which is through an override in
-/etc/ld.so.conf (actually, in /etc/ld.so.conf.d). The implicit
-presence of /usr/lib on LD_LIBRARY_PATH forces the /usr/lib/libGL.so.1
-version of OpenGL to be used, which is typically Mesa and which will
-provide only software rendering.
-
-</P>
-<P>
-
-Unfortunately the JPackage maintainers have so far been unreceptive to
-changing their installation mechanism; see <a
-href="https://www.zarb.org/pipermail/jpackage-discuss/2007-January/010871.html">this
-mailing list posting</a>. Until this is resolved, we strongly
-discourage the use of the JPackage installers for the Sun JDK.
-Instead, download the JRE or JDK installers directly from Sun's
-website.
-
-</P>
-<P>
-
-Archived forum postings illustrating this problem are <a
-href="http://www.javagaming.org/forums/index.php?topic=15610.0">here</a>
-and <a
-href="http://www.javagaming.org/forums/index.php?topic=16105.0">here</a>.
-
-</P>
-
-<H3> Solaris, Linux (X11 platforms) </H3>
-
-<P>
-
-Support has been added to the JOGL library for allowing multiple
-threads to each have an OpenGL context current simultaneously, for
-example to implement multi-head CAVE-like environments. Normally a
-global AWT lock is held between calls to GLContext.makeCurrent() /
-release() for on-screen heavyweight contexts (for example, those
-associated with a Canvas or GLCanvas). We have found this to be
-necessary for stability purposes on all supported X11 platforms, even
-with relatively robust drivers such as those from NVidia.
-
-</P>
-<P>
-
-To enable multiple GLContexts to be made current simultaneously on X11
-platforms, specify the command line argument
-<CODE>-Djogl.GLContext.optimize</CODE> when starting the JVM. Note
-that this may incur robustness problems, in particular when resizing
-or moving windows. We have also found that ATI's proprietary drivers
-do not work at all with this flag, apparently because they cause GLX
-tokens to be sent to the X server for various GL calls even for direct
-contexts. For this reason if the GLX vendor is ATI then this flag
-currently has no effect.
-
-</P>
-
-<H3> Mac OS X </H3>
-
-<P>
-
-There are some problems with visual artifacts and stability problems
-with some of the Jogl demos on Mac OS X. It appears that at least some
-of these problems are due to bugs in Apple's OpenGL support. Bugs have
-been filed about these problems and it is hoped they will be addressed
-in the near future.
-
-</P>
-<P>
-
-The Mac OS X port of Jogl, in particular the GL interface and its
-implementation, can be used either with the provided GLCanvas widget
-or with the Cocoa NSOpenGLView. In order to use it with Cocoa the
-following steps should be taken:
-
-<UL>
-
-<LI> Create an "external" OpenGL context using the
-<CODE>GLDrawableFactory.createExternalGLContext()</CODE> API. The
-context object must be created while a real underlying OpenGL context
-is current.
-
-<LI> Fetch the GL instance out of the context using getGL() as usual.
-Only use the GL instance when the OpenGL context from the NSOpenGLView
-is current.
+<code><resources></code> section of the JNLP file: <code>
+<property name="sun.java2d.noddraw" value="true"/> </code>
 
-</UL>
+</p>
 
-<B>NOTE:</B> the Cocoa interoperability has not been retested
-recently, though similar interoperability has been tested on other
-platforms. Please report any problems found with using Jogl with an
-NSOpenGLView.
+<h3> X11 Platforms (Linux, Solaris, ..) </h3>
 
-</P>
-<P>
+<h3> Mac OS X </h3>
 
 The following issues remain with the Mac OS X port:
 
-<UL>
+<ul>
 
-<LI> Due to the mechanism by which the Cocoa graphics system selects
+<li> Due to the mechanism by which the Cocoa graphics system selects
 OpenGL pixel formats, the GLCapabilitiesChooser mechanism can not be
 implemented on Mac OS X as on other platforms. Currently the
 underlying Cocoa pixel format selection is used on an
 NSOpenGLPixelFormat derived from the settings in the GLCapabilities,
-and the GLCapabilitiesChooser is ignored.
+and the GLCapabilitiesChooser is ignored. </li>
+
+</ul>
+
+<h2> Version History </h2>
 
-</UL>
+<p>
 
-</P>
+JOGL's version history can be found online in the 
+<a href="../../../wiki/index.php/Jogamp_Versioning_and_Releases">Jogamp Versioning and Release</a>.
 
-<H2> Version History </H2>
+</p>
 
-<P>
+<p>
 
-JOGL's version history can be found online in the <a
-href="http://javagaming.org/forums/index.php?topic=1596.0">"JOGL Release
-Information"</a> thread in the JOGL forum. Comments about the 1.1
-release train are in the thread <a
-href="http://javagaming.org/forums/index.php?topic=4217.0">"JOGL 1.1
-released"</a>.
+The whole evolution of JOGL is described <a href="../Overview-OpenGL-Evolution-And-JOGL.html">here</a>.
 
+</p>
 
                 </div>
             </div>
             <div id="footer">
                 <div id="footer_left">
-                    <span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">JogAmp.org</span>
-                    by <a xmlns:cc="http://creativecommons.org/ns#" href="http://jogamp.org" property="cc:attributionName" rel="cc:attributionURL">http://jogamp.org</a>
+                    <span>JogAmp.org</span>
+                    by <a href="../../">http://jogamp.org</a>
                     is licensed under a <br/>
-                    <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>.
+                    <a href="http://creativecommons.org/licenses/by/3.0/us/">Creative Commons Attribution 3.0 License</a>.
                 </div>
             </div>
         </div>
diff --git a/etc/profile.jogl b/etc/profile.jogl
index 86eeb60..1177aaa 100755
--- a/etc/profile.jogl
+++ b/etc/profile.jogl
@@ -35,6 +35,7 @@ JOGL_TEST="jogl.test.jar"
 JOGL_JAR_ALL="jogl.all.jar"
 JOGL_JAR_ALL_NOAWT="jogl.all-noawt.jar"
 JOGL_JAR_ALL_MOBILE="jogl.all-mobile.jar"
+JOGL_JAR_SWT="atomic/jogl.swt.jar"
 
 JOGL_LIB_ALL="libnativewindow_x11.so libnativewindow_awt.so libjogl_desktop.so libjogl_mobile.so libjogl_cg.so libnewt.so"
 JOGL_LIB_ALL_NOAWT="libnativewindow_x11.so libjogl_desktop.so libjogl_mobile.so libjogl_cg.so libnewt.so"
@@ -76,7 +77,8 @@ export JOGL_LIB_DIR
 JOGL_ALL_AWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL $JOGL_TEST)
 JOGL_ALL_NOAWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL_NOAWT $JOGL_TEST)
 JOGL_MOBILE_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_ALL_MOBILE)
-export JOGL_ALL_AWT_CLASSPATH JOGL_ALL_NOAWT_CLASSPATH JOGL_MOBILE_CLASSPATH
+JOGL_SWT_CLASSPATH=$(concat_jogl_list $JOGL_BUILD_DIR $JOGL_JAR_SWT)
+export JOGL_ALL_AWT_CLASSPATH JOGL_ALL_NOAWT_CLASSPATH JOGL_MOBILE_CLASSPATH JOGL_SWT_CLASSPATH
 
 if [ ! -z "$JOGL_PROFILE" ] ; then
     case "$JOGL_PROFILE" in
diff --git a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html
index 0f7fb0f..3b77157 100644
--- a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html
@@ -15,7 +15,6 @@ Demoscene Passivist's Elektronen-Multiplizierer
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.ElektronenMultiplizierer">
@@ -30,7 +29,6 @@ Demoscene Passivist's Elektronen-Multiplizierer
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           java_arguments="-Dsun.java2d.noddraw=true"
diff --git a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html
index 4f03bdc..2a500c9 100644
--- a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html
+++ b/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer.html
@@ -16,7 +16,6 @@ Demoscene Passivist's Elektronen-Multiplizierer
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -40,7 +39,6 @@ Demoscene Passivist's Elektronen-Multiplizierer
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
diff --git a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html
index e321741..59115ca 100644
--- a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01-napplet.html
@@ -15,7 +15,6 @@ JOGL Graph Text Demo 01
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.graph.demos.GPUTextGLListener0A">
@@ -33,7 +32,6 @@ JOGL Graph Text Demo 01
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUTextGLListener0A"
diff --git a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html
index e9f54ad..1c7d347 100644
--- a/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html
+++ b/jnlp-files/jogl-applet-runner-newt-GraphTextDemo01.html
@@ -16,7 +16,6 @@ JOGL Graph Text Demo 01
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -43,7 +42,6 @@ JOGL Graph Text Demo 01
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
diff --git a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html
index 784678e..6efeefc 100644
--- a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01-napplet.html
@@ -15,7 +15,6 @@ JOGL Graph UI-Scene Demo 01
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A">
@@ -32,7 +31,6 @@ JOGL Graph UI-Scene Demo 01
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A"
diff --git a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html
index b887314..6b32b11 100644
--- a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html
+++ b/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html
@@ -16,7 +16,6 @@ JOGL Graph UI-Scene Demo 01
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -42,7 +41,6 @@ JOGL Graph UI-Scene Demo 01
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
diff --git a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html b/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html
similarity index 72%
copy from jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html
copy to jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html
index 0f7fb0f..def7b72 100644
--- a/jnlp-files/jogl-applet-runner-newt-ElektronenMultiplizierer-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-MovieCube-napplet.html
@@ -1,40 +1,38 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <html>
 <head>
-<title>Demoscene Passivist's Elektronen-Multiplizierer (NApplet)</title>
+<title>JogAmp's MovieCube - GLMediaPlayer Demo 01 (NApplet)</title>
 </head>
 <body  BGCOLOR="#ffffff">
 
 <P>
-Demoscene Passivist's Elektronen-Multiplizierer
+JogAmp's MovieCube - GLMediaPlayer Demo 01
 </P>
 
 <P>
 <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
-      width="640" height="480">
+      width="510" height="300">
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
-   <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.ElektronenMultiplizierer">
+   <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube">
    <param name="gl_profile" value="GL2ES2">
    <param name="gl_swap_interval" value="1">
    <param name="gl_debug" value="false">
    <param name="gl_trace" value="false">
    <comment>
      <embed code="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
-          width="640" height="480"
+          width="510" height="300"
           type="application/x-java-applet;version=1.6"
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           java_arguments="-Dsun.java2d.noddraw=true"
-          gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.ElektronenMultiplizierer"
+          gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube"
           gl_profile="GL2ES2"
           gl_swap_interval="1"
           gl_debug="false"
@@ -47,10 +45,16 @@ Demoscene Passivist's Elektronen-Multiplizierer
 </P>
 
 <P>
-ElektronenMultiplizierer Keys:<br>
+MovieCube Keys:<br>
 <ul>
-        <li> Cursor-Left  - time backwards</li>
-        <li> Cursor-Right - time forward</li>
+        <li> Cursor-Left  - bwd  1s</li>
+        <li> Cursor-Up    - fwd 10s</li>
+        <li> Cursor-Right - fwd  1s</li>
+        <li> Cursor-Down  - bwd 10s</li>
+        <li> Escape       - Restart w/ normal speed</li>
+        <li> Space        - Toggle Pause</li>
+        <li> S            - Half Speed</li>
+        <li> F            - Double Speed</li>
 </ul>
 </P>
 <P>
diff --git a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html b/jnlp-files/jogl-applet-runner-newt-MovieCube.html
similarity index 77%
copy from jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html
copy to jnlp-files/jogl-applet-runner-newt-MovieCube.html
index b887314..6b1654e 100644
--- a/jnlp-files/jogl-applet-runner-newt-GraphUISceneDemo01.html
+++ b/jnlp-files/jogl-applet-runner-newt-MovieCube.html
@@ -1,62 +1,56 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <html>
 <head>
-<title>JOGL Graph UI-Scene Demo 01</title>
+<title>JogAmp's MovieCube - GLMediaPlayer Demo 01</title>
 </head>
 <body  BGCOLOR="#ffffff">
 
 <P>
-JOGL Graph UI-Scene Demo 01
+JogAmp's MovieCube - GLMediaPlayer Demo 01
 </P>
 
 <P>
 <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
-      width="640" height="480">
+      width="510" height="300">
    <param name="code" value="org.jdesktop.applet.util.JNLPAppletLauncher">
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
-   <param name="subapplet.displayname" value="JOGL Graph UI Demo01">
+   <param name="subapplet.displayname" value="MovieCube">
    <param name="noddraw.check" value="true">
    <param name="progressbar" value="true">
    <param name="jnlpNumExtensions" value="1">
    <param name="jnlpExtension1" value="jogl-all-awt.jnlp">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
-   <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A">
+   <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube">
    <param name="gl_profile" value="GL2ES2">
    <param name="gl_swap_interval" value="1">
-   <param name="gl_alpha" value="4">
-   <param name="gl_multisamplebuffer" value="4">
    <param name="gl_debug" value="false">
    <param name="gl_trace" value="false">
    <param name="jnlp_href" value="jogl-applet-runner-newt.jnlp">
    <comment>
      <embed code="org.jdesktop.applet.util.JNLPAppletLauncher"
-          width="640" height="480"
+          width="510" height="300"
           type="application/x-java-applet;version=1.6"
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
-          subapplet.displayname="JOGL Graph UI Demo01"
+          subapplet.displayname="MovieCube"
           noddraw.check="true"
           progressbar="true"
           jnlpNumExtensions="1"
           jnlpExtension1="jogl-all-awt.jnlp"
           java_arguments="-Dsun.java2d.noddraw=true"
-          gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A"
+          gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube"
           gl_profile="GL2ES2"
           gl_swap_interval="1"
-          gl_alpha="4"
-          gl_multisamplebuffer="4"
           gl_debug="false"
           gl_trace="false"
           jnlp_href="jogl-applet-runner-newt.jnlp">
@@ -68,9 +62,16 @@ JOGL Graph UI-Scene Demo 01
 </P>
 
 <P>
-Graph UI-Scene Demo Keys:<br>
+MovieCube Keys:<br>
 <ul>
-    <li> none - use mouse </li>
+        <li> Cursor-Left  - bwd  1s</li>
+        <li> Cursor-Up    - fwd 10s</li>
+        <li> Cursor-Right - fwd  1s</li>
+        <li> Cursor-Down  - bwd 10s</li>
+        <li> Escape       - Restart w/ normal speed</li>
+        <li> Space        - Toggle Pause</li>
+        <li> S            - Half Speed</li>
+        <li> F            - Double Speed</li>
 </ul>
 </P>
 <P>
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html
index 6e2a70f..91e9893 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-launcheronly.html
@@ -22,7 +22,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:<br>
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -45,7 +44,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:<br>
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
@@ -59,7 +57,7 @@ JOGL NEWT JNLP Applet Runner Special Keys:<br>
           gl_profile="GL2ES2"
           gl_swap_interval="1"
           gl_debug="false"
-          gl_trace="false"
+          gl_trace="false">
         <noembed>Sorry, no Java support detected.</noembed>
      </embed>
    </comment>
@@ -78,7 +76,6 @@ The applet above is instantiated with the following code:
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -101,7 +98,6 @@ The applet above is instantiated with the following code:
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
@@ -115,7 +111,7 @@ The applet above is instantiated with the following code:
           gl_profile="GL2ES2"
           gl_swap_interval="1"
           gl_debug="false"
-          gl_trace="false"
+          gl_trace="false">
         <noembed>Sorry, no Java support detected.</noembed>
      </embed>
    </comment>
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html
index 7a01e87..9db6d8c 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html
@@ -21,7 +21,6 @@ JOGL NEWT Applet Runner Special Keys:<br>
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2">
@@ -36,7 +35,6 @@ JOGL NEWT Applet Runner Special Keys:<br>
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"
@@ -61,7 +59,6 @@ The applet above is instantiated with the following code:
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2">
@@ -76,7 +73,6 @@ The applet above is instantiated with the following code:
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html
similarity index 94%
copy from jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html
copy to jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html
index 7a01e87..ba2f69e 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-normal-napplet2.html
@@ -1,7 +1,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <html>
 <head>
-<title>JOGL NEWT Applet Runner - GearsES2 - normal - Normal Applet</title>
+<title>JOGL NEWT Applet Runner - GearsES2 - normal - Normal Applet - Closeable</title>
 </head>
 <body  BGCOLOR="#ffffff">
 
@@ -13,6 +13,7 @@ JOGL NEWT Applet Runner Special Keys:<br>
     <li> r - in/out browser window </li>
     <li> a - on/off always-on-top </li>
 </ul>
+If Applet is out of browser window, it is closeable.
 </P>
 
 <P>
@@ -21,12 +22,12 @@ JOGL NEWT Applet Runner Special Keys:<br>
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2">
    <param name="gl_profile" value="GL2ES2">
    <param name="gl_swap_interval" value="1">
+   <param name="gl_closeable" value="true">
    <param name="gl_debug" value="false">
    <param name="gl_trace" value="false">
    <comment>
@@ -36,12 +37,12 @@ JOGL NEWT Applet Runner Special Keys:<br>
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"
           gl_profile="GL2ES2"
           gl_swap_interval="1"
+          gl_closeable="true"
           gl_debug="false"
           gl_trace="false">
         <noembed>Sorry, no Java support detected.</noembed>
@@ -61,12 +62,12 @@ The applet above is instantiated with the following code:
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2">
    <param name="gl_profile" value="GL2ES2">
    <param name="gl_swap_interval" value="1">
+   <param name="gl_closeable" value="true">
    <param name="gl_debug" value="false">
    <param name="gl_trace" value="false">
    <comment>
@@ -76,12 +77,12 @@ The applet above is instantiated with the following code:
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"
           gl_profile="GL2ES2"
           gl_swap_interval="1"
+          gl_closeable="true"
           gl_debug="false"
           gl_trace="false">
         <noembed>Sorry, no Java support detected.</noembed>
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-normal.html b/jnlp-files/jogl-applet-runner-newt-gears-normal.html
index 7d6adc4..c8d654d 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-normal.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-normal.html
@@ -36,7 +36,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:<br>
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -60,7 +59,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:<br>
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
@@ -94,7 +92,6 @@ The applet above is instantiated with the following code:
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -118,7 +115,6 @@ The applet above is instantiated with the following code:
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
@@ -159,7 +155,6 @@ Where the referenced JNLP file <em>jogl-applet-runner-newt.jnlp</em> looks as fo
       <j2se href="http://java.sun.com/products/autodl/j2se" version="1.4+"/>
       <property name="sun.java2d.noddraw" value="true"/>
       <jar href="jar/jogl.test.jar" main="true"/>
-      <jar href="jar/junit.jar" />
       <extension name="jogl-all-awt" href="http://jogamp.org/deployment/jogamp-current/jogl-all-awt.jnlp" />
     </resources>
 
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html b/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html
index 4190fb6..3c1895b 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-special-napplet.html
@@ -12,7 +12,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:
    <param name="code" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
    <param name="archive" value="jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
    <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2">
@@ -34,7 +33,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:
           pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
           archive="jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           java_arguments="-Dsun.java2d.noddraw=true"
           gl_event_listener_class="com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2"
diff --git a/jnlp-files/jogl-applet-runner-newt-gears-special.html b/jnlp-files/jogl-applet-runner-newt-gears-special.html
index 7141adb..dcbe898 100644
--- a/jnlp-files/jogl-applet-runner-newt-gears-special.html
+++ b/jnlp-files/jogl-applet-runner-newt-gears-special.html
@@ -13,7 +13,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:
    <param name="archive" value="jar/applet-launcher.jar,
                                 jar/gluegen-rt.jar,
                                 jar/jogl.all.jar,
-                                jar/junit.jar,
                                 jar/jogl.test.jar">
    <param name="codebase_lookup" value="false">
    <param name="subapplet.classname" value="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run">
@@ -44,7 +43,6 @@ JOGL NEWT JNLP Applet Runner Special Keys:
           archive="jar/applet-launcher.jar,
                    jar/gluegen-rt.jar,
                    jar/jogl.all.jar,
-                   jar/junit.jar,
                    jar/jogl.test.jar"
           codebase_lookup" value="false"
           subapplet.classname="com.jogamp.newt.awt.applet.JOGLNewtApplet1Run"
diff --git a/jnlp-files/jogl-applet-runner-newt.jnlp b/jnlp-files/jogl-applet-runner-newt.jnlp
index f58cc66..259e39f 100644
--- a/jnlp-files/jogl-applet-runner-newt.jnlp
+++ b/jnlp-files/jogl-applet-runner-newt.jnlp
@@ -13,7 +13,6 @@
       <j2se href="http://java.sun.com/products/autodl/j2se" version="1.4+"/>
       <property name="sun.java2d.noddraw" value="true"/>
       <jar href="jar/jogl.test.jar" main="true"/>
-      <jar href="jar/junit.jar" />
       <extension name="jogl-all-awt" href="jogl-all-awt.jnlp" />
     </resources>
 
diff --git a/jnlp-files/jogl-test-applets.html b/jnlp-files/jogl-test-applets.html
index 70bf1c0..81902a8 100644
--- a/jnlp-files/jogl-test-applets.html
+++ b/jnlp-files/jogl-test-applets.html
@@ -70,7 +70,8 @@ See Legend below table
             <td>
                 <a href="jogl-applet-runner-newt-gears-normal.html">Dual</a><br/>
                 <a href="jogl-applet-runner-newt-gears-normal-launcheronly.html">LApplet</a><br/>
-                <a href="jogl-applet-runner-newt-gears-normal-napplet.html">NApplet</a><br/>
+                <a href="jogl-applet-runner-newt-gears-normal-napplet.html">NApplet</a>
+                 (<a href="jogl-applet-runner-newt-gears-normal-napplet2.html">closeable</a>)<br/>
             </td>
             <td>
                 Classic OpenGL Gears for ES2 
@@ -93,6 +94,20 @@ See Legend below table
                 running as a translucent Applet hanging over the page.
             </td>
         </tr>
+        <tr>
+            <td>
+                <a href="../../jogl/www/media/jogl-applet-moviecube01.png">
+                    <img src="../../jogl/www/media/jogl-applet-moviecube01-small.png" width="200" alt="Full Size"/>
+                </a>
+            </td>
+            <td>
+                <a href="jogl-applet-runner-newt-MovieCube.html">Dual</a><br/>
+                <a href="jogl-applet-runner-newt-MovieCube-napplet.html">NApplet</a><br/>
+            </td>
+            <td>
+                Movie Cube using JOGL's GLMediaPlayer.
+            </td>
+        </tr>
     </tbody></table>
   </td>
 
diff --git a/make/build-common.xml b/make/build-common.xml
index 79d55b5..1ac6f70 100644
--- a/make/build-common.xml
+++ b/make/build-common.xml
@@ -192,18 +192,9 @@
         </condition>
         <echo message="isSWTRuntimeAvailable=${isSWTRuntimeAvailable}" />
 
-        <property name="target.sourcelevel" value="1.5" />
-        <property name="host.sourcelevel"   value="1.5" />
-
         <!-- property name="javadoc.link" value="http://java.sun.com/j2se/1.4.2/docs/api/" /-->
-        <property name="javadoc.link" value="http://download.oracle.com/javase/1.5.0/docs/api/" />
-
-        <!-- NOTE: the value of the debug and optimise attributes will not be overridden if already set externally -->
-        <property name="javacdebug"       value="true" /> 
-        <property name="javacdebuglevel"  value="source,lines" /> 
-        <!--property name="javacdebuglevel"  value="source,lines,vars" /--> 
-        <!-- property name="javac.memorymax"  value="128m" /-->  <!-- I ran out of memory with these .. linux x86_64 6u14 -->
-        <property name="javac.memorymax"  value="512m" /> 
+        <!-- property name="javadoc.link" value="http://download.oracle.com/javase/1.5.0/docs/api/" /-->
+        <property name="javadoc.link" value="http://docs.oracle.com/javase/6/docs/api/" />
 
         <!-- Names of directories relative to the project root.
              Some of these are used in FileMappers later for dependence information
@@ -291,10 +282,12 @@
         <property name="jogl.glumipmap.jar"             value="${build.jogl}/jogl.glu.mipmap.jar" />
         <property name="jogl.util.fixedfuncemu.jar"     value="${build.jogl}/jogl.util.fixedfuncemu.jar" />
         <property name="jogl.awt.jar"                   value="${build.jogl}/jogl.awt.jar" />
+        <property name="jogl.swt.jar"                   value="${build.jogl}/jogl.swt.jar" />
         <property name="jogl.util.awt.jar"              value="${build.jogl}/jogl.util.awt.jar" />
         <property name="jogl.os.x11.jar"                value="${build.jogl}/jogl.os.x11.jar" />
         <property name="jogl.os.win.jar"                value="${build.jogl}/jogl.os.win.jar" />
         <property name="jogl.os.osx.jar"                value="${build.jogl}/jogl.os.osx.jar" />
+        <property name="jogl.os.android.jar"            value="${build.jogl}/jogl.os.android.jar" />
         <property name="jogl.gldesktop.jar"             value="${build.jogl}/jogl.gldesktop.jar" />
         <property name="jogl.gldesktop.dbg.jar"         value="${build.jogl}/jogl.gldesktop.dbg.jar" />
         <property name="jogl.glugldesktop.jar"          value="${build.jogl}/jogl.glu.gldesktop.jar" />
@@ -312,6 +305,7 @@
             <pathelement location="${jogl.glumipmap.jar}" />
             <pathelement location="${jogl.util.fixedfuncemu.jar}" />
             <pathelement location="${jogl.awt.jar}" />
+            <pathelement location="${jogl.swt.jar}" />
             <pathelement location="${jogl.util.awt.jar}" />
             <pathelement location="${jogl.os.x11.jar}" />
             <pathelement location="${jogl.os.win.jar}" />
@@ -350,6 +344,17 @@
             <pathelement location="${jogl.util.fixedfuncemu.jar}" />
             <pathelement location="${jogl.omx.jar}" />
         </path>
+        <path id="jogl_all-android_atoms.classpath">
+            <pathelement location="${jogl.core.jar}" />
+            <pathelement location="${jogl.glmobile.jar}" />
+            <pathelement location="${jogl.glmobile.dbg.jar}" />
+            <pathelement location="${jogl.util.jar}" />
+            <pathelement location="${jogl.glutess.jar}" />
+            <pathelement location="${jogl.glumipmap.jar}" />
+            <pathelement location="${jogl.util.fixedfuncemu.jar}" />
+            <pathelement location="${jogl.os.android.jar}" />
+            <pathelement location="${jogl.omx.jar}" />
+        </path>
         <!-- 
             ${jogl.core.jar} ${jogl.glutess.jar} ${jogl.glumipmap.jar} ${jogl.glugldesktop.jar} ${jogl.os.x11.jar} ${jogl.os.win.jar} ${jogl.os.osx.jar} ${jogl.gldesktop.jar} ${jogl.gldesktop.dbg.jar} ${jogl.glmobile.jar} ${jogl.glmobile.dbg.jar} ${jogl.omx.jar} ${jogl.util.jar} ${jogl.util.gldesktop.jar} ${jogl.util.awt.jar} ${jogl.util.fixedfuncemu.jar} ${jogl.sdk.jar} -->
 
@@ -394,6 +399,7 @@
         <!-- JavaSE combinations -->
         <property name="gluegen-rt.jar"                 value="${build.gluegen}/gluegen-rt.jar" />
         <property name="jogl.test.jar"                  value="${jar}/jogl.test.jar"/>
+        <property name="jogl.test.apk"                  value="${jar}/jogl.test.apk"/>
 
         <!-- JavaSE combinations . AWT -->
         <property name="jogl.all.jar"                   value="${jar}/jogl.all.jar" />
@@ -402,6 +408,7 @@
         <property name="jogl.all-noawt.jar"             value="${jar}/jogl.all-noawt.jar" />
         <property name="jogl.all-mobile.jar"            value="${jar}/jogl.all-mobile.jar" />
         <property name="jogl.all-android.jar"           value="${jar}/jogl.all-android.jar" />
+        <property name="jogl.all-android.apk"           value="${jar}/jogl.all-android.apk" />
 
         <path id="swt_gluegen.classpath">
             <pathelement location="${gluegen-rt.jar}" />
@@ -415,6 +422,13 @@
             <path refid="nativewindow_all_atoms.classpath" />
         </path>
 
+        <path id="android_nativewindow_gluegen.classpath">
+            <pathelement location="${android.jar}" />
+            <pathelement location="${gluegen-rt.jar}" />
+            <pathelement location="${swt.jar}" />
+            <path refid="nativewindow_all_atoms.classpath" />
+        </path>
+
         <!-- NEWT Compilation .. -->
         <path id="jogl_nativewindow_gluegen.classpath">
             <pathelement location="${android.jar}" />
@@ -457,6 +471,7 @@
         </path>
         <property name="junit_jogl_awt.run.jars"
                   value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt.jar}${path.separator}${jogl.all.jar}${path.separator}${jogl.test.jar}"/>
+        <property name="junit_jogl_awt.run.remote.jars" value="${junit.jar}${path.separator}${env.TARGET_ANT_HOME}/lib/ant.jar${path.separator}${env.TARGET_ANT_HOME}/lib/ant-junit.jar${path.separator}${gluegen-rt.jar}${path.separator}${jogl.all.jar}${path.separator}${jogl.test.jar}"/>
 
         <!-- Test Run w/o AWT .. -->
         <path id="junit_jogl_noawt.run.classpath">
@@ -469,6 +484,8 @@
         </path>
         <property name="junit_jogl_noawt.run.jars"
                   value="${junit.jar}${path.separator}${ant.jar}${path.separator}${ant-junit.jar}${path.separator}${gluegen-rt.jar}${path.separator}${jogl.all-noawt.jar}${path.separator}${jogl.test.jar}"/>
+        <property name="junit_jogl_noawt.run.remote.jars" value="${junit.jar}${path.separator}${env.TARGET_ANT_HOME}/lib/ant.jar${path.separator}${env.TARGET_ANT_HOME}/lib/ant-junit.jar${path.separator}${gluegen-rt.jar}${path.separator}${jogl.all-noawt.jar}${path.separator}${jogl.test.jar}"/>
+        <property name="junit.run.remote.apks" value="${gluegen.root}/${rootrel.build}/jogamp.android-launcher.apk${path.separator}${ant-junit-all.apk}${path.separator}${gluegen.root}/${rootrel.build}/gluegen-rt.apk${path.separator}${jogl.all-android.apk}${path.separator}${jogl.test.apk}"/>
 
         <!-- Test Run w/ SWT .. -->
         <path id="junit_jogl_swt.run.classpath">
diff --git a/make/build-jogl.xml b/make/build-jogl.xml
index 511f147..f80efdf 100644
--- a/make/build-jogl.xml
+++ b/make/build-jogl.xml
@@ -83,10 +83,13 @@
         <echo message="setup.addNativeNVidiaCG: ${setup.addNativeNVidiaCG}" />
 
         <property name="java.part.gluegen-gl" 
-                  value="com/jogamp/gluegen/opengl/** com/jogamp/gluegen/runtime/opengl/*"/>
+                  value="com/jogamp/gluegen/opengl/**"/>
+
+        <property name="java.part.gluegen-gl-rt" 
+                  value="com/jogamp/gluegen/runtime/opengl/*"/>
 
         <property name="java.part.core" 
-                  value="javax/media/opengl/* javax/media/opengl/fixedfunc/* javax/media/opengl/glu/* javax/media/opengl/glu/gl2es1/* com/jogamp/gluegen/runtime/opengl/* com/jogamp/opengl/* jogamp/opengl/* jogamp/opengl/glu/* jogamp/opengl/glu/error/*"/>
+                  value="${java.part.gluegen-gl-rt} javax/media/opengl/* javax/media/opengl/fixedfunc/* javax/media/opengl/glu/* javax/media/opengl/glu/gl2es1/* com/jogamp/opengl/* jogamp/opengl/* jogamp/opengl/glu/* jogamp/opengl/glu/error/*"/>
         <property name="java.part.core.exclude" value="javax/media/opengl/Debug* javax/media/opengl/Trace*"/>
 
         <property name="java.part.nv-cg"
@@ -105,7 +108,7 @@
                   value="jogamp/opengl/glu/gl2/** jogamp/opengl/glu/nurbs/** jogamp/opengl/glu/registry/** javax/media/opengl/glu/gl2/**"/>
 
         <property name="java.part.openmax"
-                  value="com/jogamp/openmax/** jogamp/openmax/**"/>
+                  value="jogamp/opengl/omx/**"/>
 
         <property name="java.part.sdk"
                   value="com/jogamp/opengl/util/glsl/sdk/**"/>
@@ -119,6 +122,9 @@
         <property name="java.part.cgl"
                   value="jogamp/opengl/macosx/cgl/*"/>
 
+        <property name="java.part.android"
+                  value="jogamp/opengl/android/**"/>
+
         <property name="java.part.gldesktop"
                   value="jogamp/opengl/**/gl2/** jogamp/opengl/**/gl3/** jogamp/opengl/**/gl4/**"/>
 
@@ -139,9 +145,12 @@
 
         <property name="java.part.awt"
                   value="javax/media/opengl/awt/** jogamp/opengl/**/awt/**"/>
+        
+        <property name="java.part.swt"
+                  value="com/jogamp/opengl/**/swt/**"/>
 
         <property name="java.part.util"
-                  value="com/jogamp/opengl/util/* com/jogamp/opengl/util/texture/** com/jogamp/opengl/util/packrect/** jogamp/opengl/util/*"/>
+                  value="com/jogamp/opengl/util/* com/jogamp/opengl/util/texture/** com/jogamp/opengl/util/av/* com/jogamp/opengl/util/packrect/** jogamp/opengl/util/* jogamp/opengl/util/av/** jogamp/opengl/util/pngj/**"/>
 
         <property name="java.part.util.awt"
                   value="com/jogamp/opengl/util/**/awt/** com/jogamp/opengl/util/AWTAnimatorImpl*"/>
@@ -180,13 +189,25 @@
            <isset property="setup.noAWT"/> 
         </condition>
 
+        <condition property="java.excludes.swt"
+                   value="${java.part.swt}">
+           <isset property="setup.noSWT"/> 
+        </condition>
+
+        <condition property="java.excludes.android"
+                   value="${java.part.android}">
+           <not>
+               <isset property="isAndroid"/> 
+           </not>
+        </condition>
+
         <property name="java.excludes.javadoc.packagenames"
                   value="jogamp.opengl.gl2.fixme.*,com.jogamp.audio.windows.waveout.TestSpatialization"/>
 
         <property name="java.excludes.fixme" 
                   value="jogamp/opengl/gl2/fixme/** com/jogamp/audio/windows/waveout/TestSpatialization.java" />
 
-        <property name="java.excludes.all" value="${java.excludes.fixme} ${java.excludes.awt}" />
+        <property name="java.excludes.all" value="${java.excludes.fixme} ${java.excludes.awt} ${java.excludes.swt} ${java.excludes.android}" />
         <echo message="java.excludes.all: ${java.excludes.all}" />
     </target>
 
@@ -200,6 +221,7 @@
         <property name="rootrel.src.java"         value="src/jogl/classes" />
         <property name="rootrel.src.c"            value="src/jogl/native" />
         <property name="rootrel.src.c.openmax"    value="src/jogl/native/openmax" />
+        <property name="rootrel.src.c.libav"      value="src/jogl/native/libav" />
 
         <property name="rootrel.src.generated"    value="${rootrel.build}/jogl/gensrc" />
         <property name="rootrel.generated.c.jogl" value="${rootrel.src.generated}/native/jogl" />
@@ -210,12 +232,13 @@
         <property name="src.c"    value="${project.root}/${rootrel.src.c}" />
         
         <!-- The generated source directories. -->
-        <property name="src.generated" value="${build.jogl}/gensrc" />
-        <property name="src.generated.java" value="${src.generated}/classes" />
-        <property name="src.generated.java.cg" value="${src.generated.java}/com/jogamp/opengl/cg" />
-        <property name="src.generated.c" value="${src.generated}/native/jogl" />
-        <property name="src.generated.c.openmax" value="${src.generated}/native/openmax" />
-        <property name="src.generated.c.cg" value="${src.generated}/native/jogl_cg" />
+        <property name="src.generated"            value="${build.jogl}/gensrc" />
+        <property name="src.generated.java"       value="${src.generated}/classes" />
+        <property name="src.generated.java.cg"    value="${src.generated.java}/com/jogamp/opengl/cg" />
+        <property name="src.generated.c"          value="${src.generated}/native/jogl" />
+        <property name="src.generated.c.openmax"  value="${src.generated}/native/openmax" />
+        <property name="src.generated.c.libav"    value="${src.generated}/native/libav" />
+        <property name="src.generated.c.cg"        value="${src.generated}/native/jogl_cg" />
         
         <!-- The compiler output directories. -->
         <property name="classes"                    value="${build.jogl}/classes" />
@@ -320,6 +343,7 @@
         <mkdir dir="${src.generated.c}/Windows" />
         <mkdir dir="${src.generated.c}/X11" />
         <mkdir dir="${src.generated.c.openmax}" />
+        <mkdir dir="${src.generated.c.libav}" />
         <mkdir dir="${classes}" />
         <mkdir dir="${obj.jogl}" />
         <mkdir dir="${obj.joglsub}" />
@@ -382,12 +406,6 @@
         <!--property name="java.generate.skip" value="true"/-->
     </target>
 
-    <target name="java.generate.cleantemp">
-        <delete includeEmptyDirs="true" quiet="true">
-            <fileset dir="${tempdir}/gensrc" />
-        </delete>
-    </target>
-
     <target name="java.generate.copy2temp">
         <copy todir="${tempdir}">
             <fileset dir="${build.jogl}"
@@ -686,18 +704,36 @@
       -->
     <target name="build.gluegen-gl.jar" depends="init, common.gluegen.build, setup-manifestfile">
         <javac destdir="${classes}"
-               includes="${java.part.gluegen-gl}"
+               includes="${java.part.gluegen-gl-rt}"
                fork="yes"
+               includeAntRuntime="true"
                memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
+               debug="${javacdebug}" debuglevel="${javacdebuglevel}">
+            <classpath refid="gluegen-gl.classpath"/>
+            <src path="${src.java}" />
+        </javac>
+
+        <javac destdir="${classes}"
+               includes="${java.part.gluegen-gl}"
+               fork="yes"
                includeAntRuntime="true"
-               source="${target.sourcelevel}" debug="${javacdebug}" debuglevel="${javacdebuglevel}">
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${host.sourcelevel}" 
+               target="${host.targetlevel}" 
+               bootclasspath="${host.rt.jar}"
+               debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="gluegen-gl.classpath"/>
             <src path="${src.java}" />
         </javac>
 
         <jar manifest="${build.jogl}/manifest.mf" destfile="${gluegen-gl.jar}" filesonly="true">
             <fileset dir="${classes}"
-                     includes="${java.part.gluegen-gl}"/>
+                     includes="${java.part.gluegen-gl-rt} ${java.part.gluegen-gl}"/>
         </jar>
     </target>
 
@@ -990,29 +1026,34 @@
        - will be generated.
       -->
     <target name="java.compile.firstpass" depends="java.generate,java.generate.cg">
-        <antcall target="java.generate.cleantemp" inheritRefs="true" />
-
         <!-- Perform the first pass Java compile. -->
         <javac destdir="${classes}"
                includes="javax/media/opengl/fixedfunc/** javax/media/opengl/GLDrawableFactory.java javax/media/opengl/GLDrawable.java javax/media/opengl/GLContext.java javax/media/opengl/GL.java javax/media/opengl/GL2ES1.java javax/media/opengl/GL2ES2.java javax/media/opengl/GL2GL3.java javax/media/opengl/GL2.java javax/media/opengl/GLES1.java javax/media/opengl/GLES2.java javax/media/opengl/GL3.java javax/media/opengl/GL3bc.java javax/media/opengl/GL4.java javax/media/opengl/GL4bc.java"
                fork="yes"
-               memoryMaximumSize="${javac.memorymax}"
                includeAntRuntime="false"
-               source="${target.sourcelevel}" debug="${javacdebug}" debuglevel="${javacdebuglevel}">
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
+               debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="nativewindow_gluegen.classpath"/>
             <src path="${src.java}" />
             <src path="${src.generated.java}" />
         </javac>
     </target>
 
-    <target name="java.compile.secondpass.javase">
+    <target name="java.compile.secondpass.javase" unless="isAndroid">
         <!-- Perform the second pass Java compile; everything except portion of fixed function emulation depending on generated code. -->
         <javac destdir="${classes}"
                excludes="com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java,${java.excludes.all}"
-               source="${target.sourcelevel}"
                fork="yes"
-               memoryMaximumSize="${javac.memorymax}"
                includeAntRuntime="false"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
                debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="nativewindow_gluegen.classpath"/>
             <src path="${src.java}" />
@@ -1020,16 +1061,38 @@
         </javac>
     </target>
 
-    <target name="java.compile.secondpass" depends="java.generate.composable.pipeline, java.compile.secondpass.javase" />
+    <target name="java.compile.secondpass.android" if="isAndroid">
+        <!-- Perform the second pass Java compile; everything except portion of fixed function emulation depending on generated code. -->
+        <javac destdir="${classes}"
+               excludes="com/jogamp/opengl/util/glsl/fixedfunc/FixedFuncUtil.java,${java.excludes.all}"
+               fork="yes"
+               includeAntRuntime="false"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
+               debug="${javacdebug}" debuglevel="${javacdebuglevel}">
+            <classpath refid="android_nativewindow_gluegen.classpath"/>
+            <src path="${src.java}" />
+            <src path="${src.generated.java}" />
+        </javac>
+    </target>
+
+        <!-- Perform the second pass Java compile; everything except portion of fixed function emulation depending on generated code. -->
+    <target name="java.compile.secondpass" depends="java.generate.composable.pipeline, java.compile.secondpass.javase, java.compile.secondpass.android" />
 
     <target name="java.compile.thirdpass.javase">
         <!-- Perform the third pass Java compile; everything including fixed function emulation. -->
         <javac destdir="${classes}"
                excludes="${java.excludes.all}"
-               source="${target.sourcelevel}"
                fork="yes"
-               memoryMaximumSize="${javac.memorymax}"
                includeAntRuntime="false"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
                debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="nativewindow_gluegen.classpath"/>
             <src path="${src.java}" />
@@ -1092,7 +1155,7 @@
       </linker>
 
       <linker id="linker.cfg.linux.armv7.jogl.x11" extends="linker.cfg.linux.armv7">
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="X11"/>
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="X11"/>
       </linker>
 
       <linker id="linker.cfg.android.jogl" extends="linker.cfg.android">
@@ -1129,16 +1192,18 @@
       </linker>
 
       <linker id="linker.cfg.macosx.jogl" extends="linker.cfg.macosx">
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
+        <linkerarg value="AppKit" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="QuartzCore" />
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="Cocoa" />
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="OpenGL" />
       </linker>
 
       <!--linker id="linker.cfg.macosx.jogl.cg" extends="linker.cfg.macosx.jogl">
-        <linkerarg value="-framework"/>
+        <linkerarg value="-weak_framework"/>
         <linkerarg value="Cg"/>
       </linker-->
 
@@ -1189,8 +1254,44 @@
       <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
       <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
     </target>
+    
+    <target name="c.configure.linux.hppa" if="isLinuxHppa">
+      <echo message="Linux.HPPA" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
+    
+    <target name="c.configure.linux.mips" if="isLinuxMips">
+      <echo message="Linux.MIPS" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
+    
+    <target name="c.configure.linux.mipsel" if="isLinuxMipsel">
+      <echo message="Linux.MIPSEL" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
+    
+    <target name="c.configure.linux.ppc" if="isLinuxPpc">
+      <echo message="Linux.PPC" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
 
-    <target name="c.configure.linux" depends="c.configure.linux.armv7,c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.ia64,c.configure.x11" if="isLinux" />
+    <target name="c.configure.linux.s390" if="isLinuxs390">
+      <echo message="Linux.S390" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
+
+    <target name="c.configure.linux.sparc" if="isLinuxSparc">
+      <echo message="Linux.SPARC" />
+      <property name="compiler.cfg.id"                     value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.os"                    value="linker.cfg.linux.jogl.x11" />
+    </target>
+
+    <target name="c.configure.linux" depends="c.configure.linux.armv7,c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.ia64,c.configure.linux.hppa,c.configure.linux.mips,c.configure.linux.mipsel,c.configure.linux.ppc,c.configure.linux.s390,c.configure.linux.sparc,c.configure.x11" if="isLinux" />
 
     <target name="c.configure.android" if="isAndroid">
       <echo message="Android" />
@@ -1286,8 +1387,9 @@
           <include name="${rootrel.src.c}/GLXGetProcAddressARB.c" if="isX11"/>
           <!-- FIXME: the Mixer should be moved to another library -->
           <!--include name="${rootrel.src.c}/Mixer.cpp" if="isWindows"/-->
+          <include name="${rootrel.src.c.libav}/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c"/>
           <include name="${rootrel.src.c.openmax}/omx_tool.c"  if="setup.addNativeOpenMAX"/>
-          <include name="${rootrel.src.c.openmax}/com_jogamp_openmax_OMXInstance.c"  if="setup.addNativeOpenMAX"/>
+          <include name="${rootrel.src.c.openmax}/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c"  if="setup.addNativeOpenMAX"/>
 
           <include name="${rootrel.generated.c.jogl}/gl4/GL4bcImpl_JNI.c"/>
           <!--include name="${rootrel.generated.c.jogl}/GLU_JNI.c"/ EMPTY -->
@@ -1302,8 +1404,9 @@
           <include name="${rootrel.src.c}/JoglCommon.c"/>
           <include name="${rootrel.src.c}/GLDebugMessageHandler.c"/>
           <include name="${rootrel.src.c}/GLXGetProcAddressARB.c" if="isX11"/>
+          <include name="${rootrel.src.c.libav}/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c"/>
           <include name="${rootrel.src.c.openmax}/omx_tool.c"  if="setup.addNativeOpenMAX"/>
-          <include name="${rootrel.src.c.openmax}/com_jogamp_openmax_OMXInstance.c"  if="setup.addNativeOpenMAX"/>
+          <include name="${rootrel.src.c.openmax}/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c"  if="setup.addNativeOpenMAX"/>
 
           <include name="${rootrel.generated.c.jogl}/egl/EGL_JNI.c"/>
           <include name="${rootrel.generated.c.jogl}/egl/EGLExtImpl_JNI.c"/>
@@ -1349,6 +1452,7 @@
                 <includepath path="stub_includes/khr"/>
                 <includepath path="stub_includes/egl"/>
                 <includepath path="stub_includes/opengl"/>
+                <includepath path="stub_includes/libav" /> <!-- headers required by our libav/ffmpeg MediaPlayer impl. -->
                 <includepath path="stub_includes/openmax" if="setup.addNativeOpenMAX"/>
                 <includepath path="stub_includes/cg" if="setup.addNativeNVidiaCG"/>        
       
@@ -1358,6 +1462,7 @@
                 <includepath path="${src.generated.c}/X11" if="isX11"/>
                 <includepath path="${src.generated.c}/MacOSX" if="isOSX"/>
                 <includepath path="${src.generated.c}/Windows" if="isWindows"/>
+                <includepath path="${src.generated.c.libav}" />
                 <includepath path="${src.generated.c.openmax}" if="setup.addNativeOpenMAX"/>
       
                 <!-- This must come last to not override real include paths -->
@@ -1396,12 +1501,11 @@
       </sequential>
     </macrodef>  
 
-    <target name="c.build.jogl.prepare.openMAX" if="setup.addNativeOpenMAX">
-      <javah destdir="${src.generated.c.openmax}" classpath="${javah.classpath}" class="com.jogamp.openmax.OMXInstance" />
-    </target>
-
-    <target name="c.build.jogl.prepare" depends="c.build.jogl.prepare.openMAX">
+    <target name="c.build.jogl.prepare">
       <javah destdir="${build.jogl}/gensrc/native/jogl" classpath="${javah.classpath}" class="jogamp.opengl.GLDebugMessageHandler" />
+      <javah destdir="${build.jogl}/gensrc/native/jogl" classpath="${javah.classpath}" class="jogamp.opengl.GLContextImpl" />
+      <javah destdir="${src.generated.c.libav}" classpath="${javah.classpath}" class="jogamp.opengl.util.av.impl.FFMPEGMediaPlayer" />
+      <javah destdir="${src.generated.c.openmax}" classpath="${javah.classpath}" class="jogamp.opengl.util.av.impl.OMXGLMediaPlayer" />
       <!-- Generate the waveout Mixer header -->
       <!-- FIXME: this is temporary until we move this to another workspace -->
       <!--javah destdir="${build.jogl}/gensrc/native/jogl" classpath="${javah.classpath}" class="com.jogamp.audio.windows.waveout.Mixer" /-->
@@ -1484,11 +1588,17 @@
         </jar>
     </target>
 
+    <target name="build-jars-android" depends="setup-manifestfile" if="isAndroid">
+        <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.os.android.jar}" filesonly="true">
+            <fileset dir="${classes}" includes="${java.part.android}"/>
+        </jar>
+    </target>
+
     <target name="build-jars-mobile-javase" depends="setup-manifestfile">
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.glmobile.jar}" filesonly="true">
             <fileset dir="${classes}"
                      includes="${java.part.egl} ${java.part.es1} ${java.part.es2}"
-                     excludes="${java.part.awt} ${java.part.es1.dbg} ${java.part.es2.dbg}"/>
+                     excludes="${java.part.awt} ${java.part.swt} ${java.part.es1.dbg} ${java.part.es2.dbg}"/>
         </jar>
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.glmobile.dbg.jar}" filesonly="true">
             <fileset dir="${classes}"
@@ -1507,6 +1617,13 @@
         </jar>
     </target>
 
+    <target name="build-jars-swt-javase" depends="setup-manifestfile" unless="setup.noSWT">
+        <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.swt.jar}" filesonly="true">
+            <fileset dir="${classes}"
+                     includes="${java.part.swt}" />
+        </jar>
+    </target>
+
     <target name="build-jars-desktop-javase" depends="setup-manifestfile,build-jars-os-desktop-javase">
         <!--os specific gldesktop-->
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.gldesktop.jar}" filesonly="true">
@@ -1527,11 +1644,12 @@
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.util.gldesktop.jar}" filesonly="true">
             <fileset dir="${classes}"
                      includes="${java.part.util.gldesktop}"
-                     excludes="${java.part.awt} ${java.part.util.awt}"/>
+                     excludes="${java.part.awt} ${java.part.util.awt} ${java.part.swt}"/>
         </jar>
     </target>
 
-    <target name="build-jars-javase" depends="setup-manifestfile, build-jars-mobile-javase, build-jars-desktop-javase, build-jars-awt-javase">
+    <target name="build-jars-javase" depends="setup-manifestfile, build-jars-android, build-jars-mobile-javase, 
+                                              build-jars-desktop-javase, build-jars-awt-javase, build-jars-swt-javase">
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.core.jar}" filesonly="true">
             <fileset dir="${classes}"
                      includes="${java.part.core}"
@@ -1553,6 +1671,7 @@
             <fileset dir="${classes}"
                      includes="${java.part.util} ${java.part.util.glsl} ${java.part.util.graph}"
                      excludes="${java.part.util.awt} ${java.part.util.gldesktop} ${java.part.util.fixedfuncemu}"/>
+            <fileset dir="resources/assets" includes="jogl/util/**" />
         </jar>
         <jar manifest="${build.jogl}/manifest.mf" destfile="${jogl.util.fixedfuncemu.jar}" filesonly="true">
             <fileset dir="${classes}"
@@ -1594,10 +1713,11 @@
                  sourcepath="${src.java};${src.generated.java}"        
                  destdir="${javadoc}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="512m"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
-         bottom="${javadoc.bottom}" >
+                 bottom="${javadoc.bottom}" >
           <classpath refid="nativewindow_gluegen.classpath"/>
           <taglet name="net.highteq.nativetaglet.NativeTaglet" path="${gluegen.jar}" />
         </javadoc>
@@ -1609,8 +1729,9 @@
                  sourcepath="${src.java};${src.generated.java}"
                  destdir="${javadoc.spec}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="512m"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
                  bottom="${javadoc.bottom}" >
           <classpath refid="nativewindow_gluegen.classpath"/>
@@ -1624,8 +1745,9 @@
                  sourcepath="${src.java};${src.generated.java}"        
                  destdir="${javadoc.dev}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="512m"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
          bottom="${javadoc.bottom}" >
           <classpath refid="nativewindow_gluegen.classpath"/>
@@ -1641,7 +1763,6 @@
       -->
     <target name="clean" description="Remove all build products" depends="declare.common">
         <delete includeEmptyDirs="true" quiet="true">
-            <fileset dir="${tempdir}" />
             <fileset dir="${build.jogl}" />
             <fileset dir="${javadoc}" />
             <fileset dir="${javadoc.spec}" />
diff --git a/make/build-nativewindow.xml b/make/build-nativewindow.xml
index 7a06cef..2331088 100644
--- a/make/build-nativewindow.xml
+++ b/make/build-nativewindow.xml
@@ -66,23 +66,20 @@
 
         <!-- partitioning -->
 
-        <property name="java.part.swt"
-                  value="jogamp/nativewindow/swt/**"/>
-
         <property name="java.part.core"
-                  value="javax/media/nativewindow/* javax/media/nativewindow/util/* javax/media/nativewindow/egl/* com/jogamp/nativewindow/* jogamp/nativewindow/* jogamp/nativewindow/jvm/* ${java.part.swt}"/>
+                  value="javax/media/nativewindow/* javax/media/nativewindow/util/* com/jogamp/nativewindow/* com/jogamp/nativewindow/egl/* com/jogamp/nativewindow/swt/** jogamp/nativewindow/*"/>
 
         <property name="java.part.awt"
-                  value="javax/media/nativewindow/awt/* jogamp/nativewindow/jawt/** jogamp/nativewindow/**/awt/**"/>
+                  value="com/jogamp/nativewindow/awt/* jogamp/nativewindow/jawt/** jogamp/nativewindow/**/awt/**"/>
 
         <property name="java.part.x11"
-                  value="jogamp/nativewindow/x11/* javax/media/nativewindow/x11/*" />
+                  value="com/jogamp/nativewindow/x11/* jogamp/nativewindow/x11/*" />
 
         <property name="java.part.windows"
-                  value="jogamp/nativewindow/windows/* javax/media/nativewindow/windows/*" />
+                  value="com/jogamp/nativewindow/windows/* jogamp/nativewindow/windows/*" />
 
         <property name="java.part.macosx"
-                  value="jogamp/nativewindow/macosx/* javax/media/nativewindow/macosx/*" />
+                  value="com/jogamp/nativewindow/macosx/* jogamp/nativewindow/macosx/*" />
 
         <!-- condition excludes -->
 
@@ -222,11 +219,12 @@
 
     <target name="java.generate.windowlib" if="windowlib.os.cfg">
         <echo message="Generating Windowing Lib implementation class" />
+        <antcall target="java.generate.copy2temp" inheritRefs="true" />
         <gluegen src="${stub.includes}/${window.os.system}/window-lib.c"
                  outputRootDir="${build.nativewindow}"
                  config="${windowlib.os.cfg}"
                  includeRefid="stub.includes.fileset.platform"
-                 literalInclude="${stub.includes.gluegen.gg}"
+                 literalInclude="${stub.includes.gluegen.gg}, ${src.c}/${window.os.system}"
                  emitter="com.jogamp.gluegen.JavaEmitter"
                  debug="false"
                  dumpCPP="false">
@@ -240,6 +238,7 @@
            -        handle different drives in an effective manner. -->
         <echo message="Generating JAWT interface class" />
         <echo message="java.home.dir=${java.home.dir}" />
+        <antcall target="java.generate.copy2temp" inheritRefs="true" />
         <gluegen src="${jawt.platform.header}"
                  outputRootDir="${build.nativewindow}"
                  config="${jawt.cfg}"
@@ -272,6 +271,8 @@
                  
         <!-- Use the GlueGen task to generate the Java files -->
 
+        <antcall target="java.generate.cleantemp" inheritRefs="true" />
+
         <echo message="Generating platform-specifics: X11" />
         <antcall target="java.generate.platforms" inheritRefs="true">
             <param name="window.os.system"                       value="x11"/>
@@ -311,10 +312,13 @@
         <!-- Perform the second pass Java compile; everything. -->
         <javac destdir="${classes}"
                excludes="${java.excludes.all}"
-               source="${target.sourcelevel}"
                fork="yes"
                includeAntRuntime="false"
                memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
                debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="swt_gluegen.classpath"/>
             <src path="${src.java}" />
@@ -365,52 +369,44 @@
       <linker id="linker.cfg.freebsd.nativewindow.x11" extends="linker.cfg.freebsd">
         <syslibset dir="/usr/local/lib" libs="X11"/>
         <syslibset dir="/usr/local/lib" libs="Xxf86vm" />
-        <syslibset dir="/usr/local/lib" libs="Xinerama"/>
         <syslibset dir="/usr/local/lib" libs="Xrender"/>
       </linker>
 
       <linker id="linker.cfg.freebsd.amd64.nativewindow.x11" extends="linker.cfg.freebsd.amd64">
         <syslibset dir="/usr/local/lib" libs="X11" />
         <syslibset dir="/usr/local/lib" libs="Xxf86vm" />
-        <syslibset dir="/usr/local/lib" libs="Xinerama"/>
         <syslibset dir="/usr/local/lib" libs="Xrender"/>
       </linker>
 
       <linker id="linker.cfg.linux.nativewindow.x11" extends="linker.cfg.linux">
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
       </linker>
 
       <linker id="linker.cfg.linux.x86.nativewindow.x11" extends="linker.cfg.linux.x86">
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
       </linker>
 
       <linker id="linker.cfg.linux.amd64.nativewindow.x11" extends="linker.cfg.linux.amd64">
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
       </linker>
 
       <linker id="linker.cfg.linux.armv7.nativewindow.x11" extends="linker.cfg.linux.armv7">
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="X11" />
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="Xxf86vm" />
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="Xinerama" />
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="Xrender" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="X11" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="Xxf86vm" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="Xrender" />
       </linker>
 
       <linker id="linker.cfg.solaris.nativewindow.x11" extends="linker.cfg.solaris">
         <linkerarg value="-L/usr/sfw/lib"/>
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
-        <syslibset libs="X11"/>
       </linker>
 
       <linker id="linker.cfg.solaris.sparcv9.nativewindow.x11" extends="linker.cfg.solaris.sparcv9">
@@ -418,9 +414,7 @@
         <linkerarg value="-L/usr/sfw/lib/sparcv9"/>
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
-        <syslibset libs="X11"/>
       </linker>
 
       <linker id="linker.cfg.solaris.amd64.nativewindow.x11" extends="linker.cfg.solaris.amd64">
@@ -428,9 +422,7 @@
         <linkerarg value="-L/usr/sfw/lib/amd64"/>
         <syslibset libs="X11"/>
         <syslibset libs="Xxf86vm" />
-        <syslibset libs="Xinerama"/>
         <syslibset libs="Xrender"/>
-        <syslibset libs="X11"/>
       </linker>
 
       <linker id="linker.cfg.win32.mingw.nativewindow" extends="linker.cfg.win32.mingw">
@@ -448,19 +440,20 @@
       </linker>
       
       <linker id="linker.cfg.macosx.nativewindow" extends="linker.cfg.macosx">
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
+        <linkerarg value="AppKit" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="QuartzCore" />
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="Cocoa" />
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="JavaNativeFoundation" />
-        <linkerarg value="-F" />
-        <linkerarg value="${java.osx.frameworks.dir}" />
+        <linkerarg value="-F${java.osx.frameworks.dir}" />
       </linker>
 
       <linker id="linker.cfg.hpux.nativewindow" extends="linker.cfg.hpux">
         <syslibset dir="/usr/lib" libs="X11"/>
-        <syslibset dir="/usr/lib" libs="Xinerama"/>
+        <syslibset dir="/usr/lib" libs="Xrender"/>
       </linker>
     </target>
 
@@ -506,7 +499,43 @@
       <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
     </target>
 
-    <target name="c.configure.linux" depends="c.configure.linux.armv7,c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.ia64,c.configure.x11" if="isLinux" />
+    <target name="c.configure.linux.hppa" if="isLinuxHppa">
+      <echo message="Linux.HPPA" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux.mips" if="isLinuxMips">
+      <echo message="Linux.MIPS" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux.mipsel" if="isLinuxMipsel">
+      <echo message="Linux.MIPSEL" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux.ppc" if="isLinuxPpc">
+      <echo message="Linux.PPC" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux.s390" if="isLinuxs390">
+      <echo message="Linux.S390" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux.sparc" if="isLinuxSparc">
+      <echo message="Linux.SPARC" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.nativewindow.x11" />
+    </target>
+
+    <target name="c.configure.linux" depends="c.configure.linux.armv7,c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.ia64,c.configure.linux.hppa,c.configure.linux.mips,c.configure.linux.mipsel,c.configure.linux.ppc,c.configure.linux.s390,c.configure.linux.sparc,c.configure.x11" if="isLinux" />
 
     <target name="c.configure.android" if="isAndroid">
       <echo message="Android" />
@@ -621,8 +650,8 @@
 
         <patternset id="c.src.files.windows">
           <include name="${rootrel.generated.c}/Windows/GDI*.c"/>
-          <include name="${rootrel.src.c}/windows/GDImisc.c"/>
-          <include name="${rootrel.src.c}/windows/WindowsDWM.c"/>
+          <include name="${rootrel.src.c}/win32/GDImisc.c"/>
+          <include name="${rootrel.src.c}/win32/WindowsDWM.c"/>
           <include name="${rootrel.src.c}/NativewindowCommon.c"/>
         </patternset>
 
@@ -632,6 +661,7 @@
         </patternset>
 
         <echo message="Compiling @{output.lib.name}" />
+        <echo message="java.lib.dir.platform: ${java.lib.dir.platform}" />      
 
         <!-- have to wrap cc task with outofdate, because otherwise cc links a new library
              even when no files have been compiled -->
@@ -665,7 +695,8 @@
                 <includepath path="${src.generated.c}/X11"     if="isX11"/>
                 <includepath path="${src.generated.c}/MacOSX"  if="isOSX"/>
                 <includepath path="${src.generated.c}/Windows" if="isWindows"/>
-                <includepath path="${src.c}/windows"           if="isWindows"/>
+                <includepath path="${src.c}/win32"             if="isWindows"/>
+                <includepath path="${src.c}/x11"               if="isX11"/>
                 <includepath path="${src.c}"/>
       
                 <!-- This must come last to not override real include paths -->
@@ -846,6 +877,7 @@
                  destdir="${javadoc}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
          bottom="${javadoc.bottom}" >
         </javadoc>
@@ -860,6 +892,7 @@
                  destdir="${javadoc.spec}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}"
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
                  bottom="${javadoc.bottom}" >
         </javadoc>
@@ -874,6 +907,7 @@
                  destdir="${javadoc.dev}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
          bottom="${javadoc.bottom}" >
         </javadoc>
@@ -887,11 +921,26 @@
       -->
     <target name="clean" description="Remove all build products" depends="declare.common">
         <delete includeEmptyDirs="true" quiet="true">
+            <fileset dir="${tempdir}" />
             <fileset dir="${build.nativewindow}" />
             <fileset dir="${javadoc}" />
             <fileset dir="${javadoc.spec}" />
             <fileset dir="${javadoc.dev}" />
         </delete>
+        <antcall target="java.generate.cleantemp" inheritRefs="true" />
+    </target>
+
+    <target name="java.generate.cleantemp">
+        <delete includeEmptyDirs="true" quiet="true">
+            <fileset dir="${tempdir}/gensrc" />
+        </delete>
+    </target>
+
+    <target name="java.generate.copy2temp">
+        <copy todir="${tempdir}">
+            <fileset dir="${build.nativewindow}"
+                     includes="gensrc/classes/**" />
+        </copy>
     </target>
 
     <!-- ================================================================== -->
diff --git a/make/build-newt.xml b/make/build-newt.xml
index 56ebfac..2bf04bb 100644
--- a/make/build-newt.xml
+++ b/make/build-newt.xml
@@ -206,10 +206,13 @@
         <!-- Perform the second pass Java compile; everything. -->
         <javac destdir="${classes}"
                excludes="${java.excludes.all}"
-               source="${target.sourcelevel}"
                fork="yes"
                includeAntRuntime="false"
                memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
                debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <src path="${src.java}" />
             <classpath refid="jogl_nativewindow_gluegen.classpath"/>
@@ -271,12 +274,12 @@
       </linker>
 
       <linker id="linker.cfg.linux.armv7.newt.x11" extends="linker.cfg.linux.armv7">
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="X11" />
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="Xrandr" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="X11" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="Xrandr" />
       </linker>
 
       <linker id="linker.cfg.android.newt" extends="linker.cfg.android">
-        <syslibset dir="${env.TARGET_PLATFORM_LIBS}" libs="android" />
+        <syslibset dir="${env.TARGET_PLATFORM_ROOT}/usr/lib" libs="android" />
       </linker>
 
       <linker id="linker.cfg.solaris.newt.x11" extends="linker.cfg.solaris">
@@ -311,7 +314,9 @@
       </linker>
 
       <linker id="linker.cfg.macosx.newt" extends="linker.cfg.macosx">
-        <linkerarg value="-framework" />
+        <linkerarg value="-weak_framework" />
+        <linkerarg value="AppKit" />
+        <linkerarg value="-weak_framework" />
         <linkerarg value="Cocoa" />
       </linker>
 
@@ -368,13 +373,73 @@
       <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
     </target>
 
+    <target name="c.configure.linux.hppa" if="isLinuxHppa">
+      <echo message="Linux.hppa" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
+    <target name="c.configure.linux.mips" if="isLinuxMips">
+      <echo message="Linux.mips" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
+    <target name="c.configure.linux.mipsel" if="isLinuxMipsel">
+      <echo message="Linux.mips" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
+    <target name="c.configure.linux.ppc" if="isLinuxPpc">
+      <echo message="Linux.ppc" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
+    <target name="c.configure.linux.s390" if="isLinuxs390">
+      <echo message="Linux.S390" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
+    <target name="c.configure.linux.sparc" if="isLinuxSparc">
+      <echo message="Linux.sparc" />
+      <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
+      <condition property="linker.cfg.id.oswin"             value="linker.cfg.linux.newt.x11"
+                                                            else="linker.cfg.linux">
+          <isset property="isX11" />
+      </condition>
+      <echo message="linker.cfg.id.oswin ${linker.cfg.id.oswin}" />
+    </target>
+
     <target name="c.configure.linux.ia64" if="isLinuxIA64">
       <echo message="Linux.IA64" />
       <property name="compiler.cfg.id"                      value="compiler.cfg.linux" />
       <property name="linker.cfg.id.oswin"                  value="linker.cfg.linux.newt.x11" />
     </target>
 
-    <target name="c.configure.linux" depends="c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.armv7,c.configure.linux.ia64,c.configure.x11" if="isLinux"/>
+    <target name="c.configure.linux" depends="c.configure.linux.x86,c.configure.linux.amd64,c.configure.linux.armv7,c.configure.linux.hppa,c.configure.linux.mips,c.configure.linux.mipsel,c.configure.linux.ppc,c.configure.linux.s390,c.configure.linux.sparc,c.configure.linux.ia64,c.configure.x11" if="isLinux"/>
 
     <target name="c.configure.android" if="isAndroid">
       <echo message="Android" />
@@ -469,9 +534,12 @@
 
         <patternset id="c.src.files.newt">
           <include name="${rootrel.src.c}/NewtCommon.c" />
+          <!-- include name="${rootrel.src.c}/timespec.c"   /--> <!-- currently used for X11 and OSX with special PERF DEBUG MODE-->
           <include name="${rootrel.src.c}/WindowsWindow.c" if="isWindows"/>
           <include name="${rootrel.src.c}/*.m"             if="isOSX"/>
           <include name="${rootrel.src.c}/AndroidWindow.c" if="isAndroid"/>
+          <include name="${rootrel.src.c}/X11Display.c"    if="isX11"/>
+          <include name="${rootrel.src.c}/X11Screen.c"     if="isX11"/>
           <include name="${rootrel.src.c}/X11Window.c"     if="isX11"/>
           <include name="${rootrel.src.c}/KDWindow.c"      if="setup.addNativeKD"/>
           <include name="${rootrel.src.c}/IntelGDL.c"      if="setup.addNativeIntelGDL"/>
@@ -699,7 +767,9 @@
                  sourcepath="${src.java};${src.generated.java}"
                  destdir="${javadoc}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
          bottom="${javadoc.bottom}" >
          <classpath refid="jogl_nativewindow_gluegen.classpath"/>
@@ -713,7 +783,9 @@
                  sourcepath="${src.java};${src.generated.java}"
                  destdir="${javadoc.spec}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
                  bottom="${javadoc.bottom}" >
          <classpath refid="jogl_nativewindow_gluegen.classpath"/>
@@ -727,7 +799,9 @@
                  sourcepath="${src.java};${src.generated.java}"
                  destdir="${javadoc.dev}" windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
+                 maxmemory="${javac.memorymax}"
                  linkoffline="${javadoc.link} 142-packages"
          bottom="${javadoc.bottom}" >
          <classpath refid="jogl_nativewindow_gluegen.classpath"/>
diff --git a/make/build-staticglgen.xml b/make/build-staticglgen.xml
index 325b737..6d15110 100644
--- a/make/build-staticglgen.xml
+++ b/make/build-staticglgen.xml
@@ -30,7 +30,12 @@
 
         <!-- Compile BuildStaticGLInfo -->
         <javac srcdir="${src.java}" destdir="${classes}" includes="**/BuildStaticGLInfo.java" source="${target.sourcelevel}" debug="true" debuglevel="${javacdebuglevel}"
-               includeAntRuntime="false">
+               includeAntRuntime="false"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}">
             <classpath refid="antlr.classpath" />
         </javac>
         
@@ -51,7 +56,10 @@
            - NOTE:  ONLY the StaticGLGen is built at this time.  BuildStaticGLInfo 
            -        itself is built in a separate task.  -->
         <javac destdir="${classes}" includes="**/StaticGLGenTask.java" source="${target.sourcelevel}" debug="true" debuglevel="${javacdebuglevel}"
-               includeAntRuntime="false">
+               includeAntRuntime="true"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${host.sourcelevel}">
             <src path="${src.java}" />
             <classpath refid="classpath" />
         </javac>
diff --git a/make/build-test.xml b/make/build-test.xml
index 533ca30..96b3f08 100644
--- a/make/build-test.xml
+++ b/make/build-test.xml
@@ -4,6 +4,11 @@
 
     <description>JUNIT Tests JOGL</description>
 
+    <property name="gluegen.basename" value="gluegen" /> <!-- if differs, ie jenkins jobname, must be set properly first -->
+    <property name="jogl.basename" value="jogl" /> <!-- if differs, ie jenkins jobname, must be set properly first -->
+    <echo message="gluegen.basename: ${gluegen.basename}"/>
+    <echo message="jogl.basename: ${jogl.basename}"/>
+
     <import file="build-common.xml"/>
 
     <taskdef resource="net/sf/antcontrib/antlib.xml">
@@ -42,6 +47,8 @@
     <target name="clean" description="Remove all build products" depends="declare.common">
         <delete includeEmptyDirs="true" quiet="true">
             <fileset dir="${build.test}" />
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
             <fileset dir="." includes="*.tga" />
             <fileset file="${jogl.test.jar}" />
         </delete>
@@ -51,31 +58,32 @@
     <!--
        - Build/run tests/junit.
       -->
-    <target name="test.compile.check" depends="declare.common">
-      <!-- Create the required output directories. -->
-      <mkdir dir="${obj.test}" />
-      <mkdir dir="${classes}" />
-
-      <property name="jogl.test.jar.path" location="${jogl.test.jar}"/> <!-- absolute path -->
-      <echo message="jogl.test.jar ${jogl.test.jar.path}"/>
-      <uptodate property="test.compile.skip">
-        <srcfiles dir= "."                 includes="*.xml"/>
-        <srcfiles dir= "${src.test}"       includes="**"/>
-        <srcfiles                          file="${gluegen.jar}" />
-        <srcfiles                          dir="${src}/nativewindow" />
-        <srcfiles                          dir="${src}/jogl" />
-        <srcfiles                          dir="${src}/newt" />
-        <mapper type="merge" to="${jogl.test.jar.path}"/>
-      </uptodate>
+    <target name="android.test.package" if="isAndroid">
+        <aapt.signed 
+            assetsdir="resources/assets-test"
+            jarsrcdir="${src}/test"
+            jarbuilddir="${jar}"
+            jarbasename="jogl.test"
+            nativebuilddir="${lib}"
+            nativebasename="non-existing"
+            android.abi="${android.abi}"
+            androidmanifest.path="resources/android/AndroidManifest-test.xml"
+            androidresources.path="resources/android/res-test"
+            jarmanifest.path="${build.jogl}/manifest.mf"
+            version.code="${jogl_int_version}"
+            version.name="${jogl.version.plus}" />
     </target>
 
-    <target name="test.compile" depends="test.compile.check" unless="test.compile.skip">
+    <target name="test.compile.java">
         <!-- Perform the junit pass Java compile -->
         <javac destdir="${classes}"
-               source="${host.sourcelevel}"
                fork="yes"
-               memoryMaximumSize="${javac.memorymax}"
                includeAntRuntime="false"
+               memoryMaximumSize="${javac.memorymax}"
+               encoding="UTF-8"
+               source="${target.sourcelevel}" 
+               target="${target.targetlevel}" 
+               bootclasspath="${target.rt.jar}"
                debug="${javacdebug}" debuglevel="${javacdebuglevel}">
             <classpath refid="junit_jogl_newt_android.compile.classpath"/>
             <src path="${src.test}" />
@@ -90,11 +98,35 @@
             <!-- get all class files, but skip any resource files that external tools
                  might have copied into the class directory (otherwise, it's possible
                  to get the same resource file twice in the jar) -->
-            <fileset dir="${classes}"
-                includes="${java.part.test}"/>
+            <fileset dir="${classes}" includes="${java.part.test}"/>
+            <fileset dir="resources/assets-test" includes="**" />
         </jar>
     </target>
 
+    <target name="test.compile.check" depends="declare.common">
+      <!-- Create the required output directories. -->
+      <mkdir dir="${obj.test}" />
+      <mkdir dir="${classes}" />
+
+      <property name="jogl.test.jar.path" location="${jogl.test.jar}"/> <!-- absolute path -->
+      <echo message="jogl.test.jar ${jogl.test.jar.path}"/>
+      <uptodate property="test.compile.skip">
+        <srcfiles dir= "."                 includes="*.xml"/>
+        <srcfiles dir= "${src.test}"       includes="**"/>
+        <srcfiles dir= "resources/android" includes="**/*.xml"/>
+        <srcfiles                          file="${gluegen-rt.jar}" />
+        <srcfiles                          dir="${src}/nativewindow" />
+        <srcfiles                          dir="${src}/jogl" />
+        <srcfiles                          dir="${src}/newt" />
+        <mapper type="merge" to="${jogl.test.jar.path}"/>
+      </uptodate>
+    </target>
+
+    <target name="test.compile" depends="test.compile.check" unless="test.compile.skip">
+        <antcall target="test.compile.java" inheritRefs="true" inheritAll="true"/>
+        <antcall target="android.test.package" inheritRefs="true" inheritAll="true"/>
+    </target>
+
     <target name="test.manual.run" depends="test.compile">
         <for param="test.class.path.m" keepgoing="true">
             <!-- results in absolute path -->
@@ -124,6 +156,8 @@
                  output="${test.class.result.file}">
                 <env key="${system.env.library.path}" path="${obj.all.paths}"/>
                 <env key="CLASSPATH" value="${junit_jogl_awt.run.jars}"/>
+                <arg line="${junit.run.arg0}"/>
+                <arg line="${junit.run.arg1}"/>
                 <arg line="${jvmDataModel.arg}"/>
                 <arg value="-Djava.library.path=${obj.all.paths}"/>
                 <!--
@@ -144,6 +178,8 @@
         <!-- Test*NOUI* -->
         <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
             <env key="${system.env.library.path}" path="${obj.all.paths}"/>
+            <jvmarg value="${junit.run.arg0}"/>
+            <jvmarg value="${junit.run.arg1}"/>
             <jvmarg value="${jvmDataModel.arg}"/>
             <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
 
@@ -208,6 +244,8 @@
                  failonerror="false">
                 <env key="${system.env.library.path}" path="${obj.all.paths}"/>
                 <env key="CLASSPATH" value="${junit_jogl_noawt.run.jars}"/>
+                <arg line="${junit.run.arg0}"/>
+                <arg line="${junit.run.arg1}"/>
                 <arg line="${jvmDataModel.arg}"/>
                 <arg value="-Djava.library.path=${obj.all.paths}"/>
                 <arg line="${jvmarg.headless}"/>
@@ -243,6 +281,8 @@
         <!-- Test*NEWT* -->
         <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
             <env key="${system.env.library.path}" path="${obj.all.paths}"/>
+            <jvmarg value="${junit.run.arg0}"/>
+            <jvmarg value="${junit.run.arg1}"/>
             <jvmarg value="${jvmDataModel.arg}"/>
             <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
 
@@ -278,6 +318,8 @@
         <!-- Test*AWT* -->
         <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
             <env key="${system.env.library.path}" path="${obj.all.paths}"/>
+            <jvmarg value="${junit.run.arg0}"/>
+            <jvmarg value="${junit.run.arg1}"/>
             <jvmarg value="${jvmDataModel.arg}"/>
             <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
 
@@ -313,6 +355,8 @@
         <!-- Test*AWT* -->
         <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
             <env key="${system.env.library.path}" path="${obj.all.paths}"/>
+            <jvmarg value="${junit.run.arg0}"/>
+            <jvmarg value="${junit.run.arg1}"/>
             <jvmarg value="${jvmDataModel.arg}"/>
             <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
 
@@ -371,6 +415,8 @@
                  failonerror="false">
                 <env key="${system.env.library.path}" path="${obj.all.paths}"/>
                 <env key="CLASSPATH" value="${junit_extra_classpath}${junit_jogl_swt.run.jars}"/>
+                <arg line="${junit.run.arg0}"/>
+                <arg line="${junit.run.arg1}"/>
                 <arg line="${jvmDataModel.arg}"/>
                 <arg value="-Djava.library.path=${obj.all.paths}"/>
                 <arg line="${jvmarg.headless}"/>
@@ -398,10 +444,12 @@
         </for>
     </target>
 
-    <target name="junit.run.swt.awt" depends="test.compile" description="Runs all SWT_AWT tests." if="isSWTRuntimeAvailable">
+    <target name="junit.run.swt.awt" depends="test.compile" description="Runs all SWT AWT tests." if="isSWTRuntimeAvailable">
       <!-- Test*SWT*AWT* -->
       <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
           <env key="${system.env.library.path}" path="${obj.all.paths}"/>
+          <jvmarg value="${junit.run.arg0}"/>
+          <jvmarg value="${junit.run.arg1}"/>
           <jvmarg value="${jvmDataModel.arg}"/>
           <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
 
@@ -435,6 +483,8 @@
     <target name="junit.run.newt.awt" depends="test.compile">
         <!-- Test*AWT* -->
         <junit forkmode="perTest" showoutput="true" fork="true" haltonerror="off" timeout="${batchtest.timeout}">
+            <jvmarg value="${junit.run.arg0}"/>
+            <jvmarg value="${junit.run.arg1}"/>
             <jvmarg value="${jvmDataModel.arg}"/>
             <env key="${system.env.library.path}" path="${obj.all.paths}"/>
             <jvmarg value="-Djava.library.path=${obj.all.paths}"/>
@@ -467,28 +517,33 @@
         </junit>
     </target>
 
-    <target name="test.auto.run" depends="junit.run"/>
-
-        <condition property="jvmarg.mainthrd" value="-XstartOnFirstThread"><isset property="isOSX"/></condition>
-
-    <target name="junit.run.tests" depends="junit.run.noui,junit.run.newt.headless,junit.run.awt,junit.run.newt.awt,junit.run.swt.headless,junit.run.swt.awt"/>
+    <target name="junit.run.local" unless="isCrosscompilation" >
+        <antcall target="junit.run.noui"          inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.newt.headless" inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.awt"           inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.newt.awt"      inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.swt.headless"  inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.swt.awt"       inheritRefs="true" inheritAll="true"/>
+    </target>
 
-    <target name="junit.run.d32" if="isOSX">
+    <target name="junit.run.local.d32" if="isOSX">
         <var name="jvmDataModel.arg" unset="true"/>
         <var name="jvmDataModel.arg" value="-d32"/>
         <var name="junit_extra_classpath" unset="true"/>
         <var name="junit_extra_classpath" value="${swt-cocoa-macosx-x86_32.jar}:"/>
 
-        <antcall target="junit.run.tests" inheritRefs="true" inheritAll="true"/>
+        <antcall target="junit.run.local" inheritRefs="true" inheritAll="true"/>
 
         <mkdir dir="${build}/test/results-x32"/>
         <move todir="${build}/test/results-x32">
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
             <fileset dir="." includes="*.tga" />
         </move>
         <move todir="${build}/test/results-x32">
             <fileset dir="${results.test}" includes="**" />
         </move>
-        <mkdir dir="${build}/test/results"/>
+        <mkdir dir="${results.test}"/>
 
         <var name="jvmDataModel.arg" unset="true"/>
         <var name="jvmDataModel.arg" value="-d64"/>
@@ -496,24 +551,379 @@
         <var name="junit_extra_classpath" value=""/>
     </target>
 
-    <target name="junit.run.settings">
+    <target name="junit.run.remote.ssh.all" if="isCrosscompilation" unless="isAndroid">
+        <echo message="#! /bin/sh${line.separator}" append="false" file="${build.test}/targetcommand.sh" />
+        <echo message="${line.separator}
+rsync -av --delete --delete-after --delete-excluded \${line.separator}
+      --exclude 'build-x86*/' --exclude 'build-linux-x*/' --exclude 'build-android*/' --exclude 'build-win*/' --exclude 'build-mac*/' \${line.separator}
+      --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \${line.separator}
+      ${env.HOST_UID}@${env.HOST_IP}::${env.HOST_RSYNC_ROOT}/${jogl.basename} ${env.TARGET_ROOT} ${line.separator}
+cd ${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make ${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+
+        <for param="test.class.path.m" keepgoing="true">
+            <!-- results in absolute path -->
+            <fileset dir="${classes}">
+                <include name="${java.dir.junit}/**/Test*NEWT*"/>
+                <exclude name="**/*$$*"/>
+            </fileset>
+          <sequential>
+            <var name="test.class.path" unset="true"/>
+            <property name="test.class.path" basedir="${classes}" relative="true" location="@{test.class.path.m}"/>
+            <var name="test.class.fqn" unset="true"/>
+            <pathconvert property="test.class.fqn">
+              <fileset file="${classes}${file.separator}${test.class.path}"/>
+              <chainedmapper>
+                  <globmapper    from="${classes.path}${file.separator}*" to="*"/> <!-- rel. -->
+                  <packagemapper from="*.class"           to="*"/> <!-- FQCN -->
+              </chainedmapper>
+            </pathconvert>
+            <var name="test.class.result.file" value="${results.test}/TEST-${test.class.fqn}.xml"/>
+            <echo message="Testing ${test.class.fqn} -- ${test.class.result.file}"/>
+            <echo message="${line.separator}
+export DISPLAY=:0.0${line.separator}
+java \${line.separator}
+${junit.run.arg0}\${line.separator}
+${junit.run.arg1}\${line.separator}
+${jvmDataModel.arg}\${line.separator}
+-cp ${junit_jogl_noawt.run.remote.jars}\${line.separator}
+${jvmarg.headless}\${line.separator}
+com.jogamp.newt.util.MainThread\${line.separator}
+org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \${line.separator}
+${test.class.fqn} \${line.separator}
+filtertrace=true \${line.separator}
+haltOnError=false \${line.separator}
+haltOnFailure=false \${line.separator}
+showoutput=true \${line.separator}
+outputtoformatters=true \${line.separator}
+logfailedtests=true \${line.separator}
+logtestlistenerevents=true \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.class.result.file} ${line.separator}
+${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+          </sequential>
+        </for>
+
+        <for param="test.class.path.m" keepgoing="true">
+            <!-- results in absolute path -->
+            <fileset dir="${classes}">
+                <include name="${java.dir.junit}/**/Test*AWT*"/>
+                <exclude name="**/*$$*"/>
+                <exclude name="**/*SWT*"/>
+                <exclude name="${java.dir.junit}/**/Test*NEWT*"/>
+            </fileset>
+          <sequential>
+            <var name="test.class.path" unset="true"/>
+            <property name="test.class.path" basedir="${classes}" relative="true" location="@{test.class.path.m}"/>
+            <var name="test.class.fqn" unset="true"/>
+            <pathconvert property="test.class.fqn">
+              <fileset file="${classes}${file.separator}${test.class.path}"/>
+              <chainedmapper>
+                  <globmapper    from="${classes.path}${file.separator}*" to="*"/> <!-- rel. -->
+                  <packagemapper from="*.class"           to="*"/> <!-- FQCN -->
+              </chainedmapper>
+            </pathconvert>
+            <var name="test.class.result.file" value="${results.test}/TEST-${test.class.fqn}.xml"/>
+            <echo message="Testing ${test.class.fqn} -- ${test.class.result.file}"/>
+            <echo message="${line.separator}
+export DISPLAY=:0.0${line.separator}
+java \${line.separator}
+${junit.run.arg0}\${line.separator}
+${junit.run.arg1}\${line.separator}
+${jvmDataModel.arg}\${line.separator}
+-cp ${junit_jogl_awt.run.remote.jars}\${line.separator}
+org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \${line.separator}
+${test.class.fqn} \${line.separator}
+filtertrace=true \${line.separator}
+haltOnError=false \${line.separator}
+haltOnFailure=false \${line.separator}
+showoutput=true \${line.separator}
+outputtoformatters=true \${line.separator}
+logfailedtests=true \${line.separator}
+logtestlistenerevents=true \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.class.result.file} ${line.separator}
+${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+          </sequential>
+        </for>
+        <exec dir="." executable="sh" logError="true" failonerror="true" failifexecutionfails="true">
+            <arg line='-x -c "
+            chmod 0755 ${build.test}/targetcommand.sh ;
+            scp ${build.test}/targetcommand.sh ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            ssh -x ${env.TARGET_UID}@${env.TARGET_IP} ${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            scp -pr ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make/${results.test}/* ${results.test}/ "'/>
+        </exec>
+    </target>
+
+    <target name="junit.run.remote.ssh.newt" if="isCrosscompilation" unless="isAndroid">
+        <echo message="#! /bin/sh${line.separator}" append="false" file="${build.test}/targetcommand.sh" />
+        <echo message="${line.separator}
+rsync -av --delete --delete-after --delete-excluded \${line.separator}
+      --exclude 'build-x86*/' --exclude 'build-linux-x*/' --exclude 'build-android*/' --exclude 'build-win*/' --exclude 'build-mac*/' \${line.separator}
+      --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \${line.separator}
+      ${env.HOST_UID}@${env.HOST_IP}::${env.HOST_RSYNC_ROOT}/${jogl.basename} ${env.TARGET_ROOT} ${line.separator}
+cd ${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make ${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+
+        <for param="test.class.path.m" keepgoing="true">
+            <!-- results in absolute path -->
+            <fileset dir="${classes}">
+                <include name="${java.dir.junit}/**/Test*NEWT*"/>
+                <exclude name="**/*$$*"/>
+            </fileset>
+          <sequential>
+            <var name="test.class.path" unset="true"/>
+            <property name="test.class.path" basedir="${classes}" relative="true" location="@{test.class.path.m}"/>
+            <var name="test.class.fqn" unset="true"/>
+            <pathconvert property="test.class.fqn">
+              <fileset file="${classes}${file.separator}${test.class.path}"/>
+              <chainedmapper>
+                  <globmapper    from="${classes.path}${file.separator}*" to="*"/> <!-- rel. -->
+                  <packagemapper from="*.class"           to="*"/> <!-- FQCN -->
+              </chainedmapper>
+            </pathconvert>
+            <var name="test.class.result.file" value="${results.test}/TEST-${test.class.fqn}.xml"/>
+            <echo message="Testing ${test.class.fqn} -- ${test.class.result.file}"/>
+            <echo message="${line.separator}
+export DISPLAY=:0.0${line.separator}
+java \${line.separator}
+${junit.run.arg0}\${line.separator}
+${junit.run.arg1}\${line.separator}
+${jvmDataModel.arg}\${line.separator}
+-cp ${junit_jogl_noawt.run.remote.jars}\${line.separator}
+${jvmarg.headless}\${line.separator}
+com.jogamp.newt.util.MainThread\${line.separator}
+org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \${line.separator}
+${test.class.fqn} \${line.separator}
+filtertrace=true \${line.separator}
+haltOnError=false \${line.separator}
+haltOnFailure=false \${line.separator}
+showoutput=true \${line.separator}
+outputtoformatters=true \${line.separator}
+logfailedtests=true \${line.separator}
+logtestlistenerevents=true \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.class.result.file} ${line.separator}
+${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+          </sequential>
+        </for>
+
+        <exec dir="." executable="sh" logError="true" failonerror="true" failifexecutionfails="true">
+            <arg line='-x -c "
+            chmod 0755 ${build.test}/targetcommand.sh ;
+            scp ${build.test}/targetcommand.sh ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            ssh -x ${env.TARGET_UID}@${env.TARGET_IP} ${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            scp -pr ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make/${results.test}/* ${results.test}/ "'/>
+        </exec>
+    </target>
+
+    <target name="junit.run.remote.ssh.awt" if="isCrosscompilation" unless="isAndroid">
+        <echo message="#! /bin/sh${line.separator}" append="false" file="${build.test}/targetcommand.sh" />
+        <echo message="${line.separator}
+rsync -av --delete --delete-after --delete-excluded \${line.separator}
+      --exclude 'build-x86*/' --exclude 'build-linux-x*/' --exclude 'build-android*/' --exclude 'build-win*/' --exclude 'build-mac*/' \${line.separator}
+      --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \${line.separator}
+      ${env.HOST_UID}@${env.HOST_IP}::${env.HOST_RSYNC_ROOT}/${jogl.basename} ${env.TARGET_ROOT} ${line.separator}
+cd ${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make ${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+
+        <for param="test.class.path.m" keepgoing="true">
+            <!-- results in absolute path -->
+            <fileset dir="${classes}">
+                <include name="${java.dir.junit}/**/Test*AWT*"/>
+                <exclude name="**/*$$*"/>
+                <exclude name="**/*SWT*"/>
+                <exclude name="${java.dir.junit}/**/Test*NEWT*"/>
+            </fileset>
+          <sequential>
+            <var name="test.class.path" unset="true"/>
+            <property name="test.class.path" basedir="${classes}" relative="true" location="@{test.class.path.m}"/>
+            <var name="test.class.fqn" unset="true"/>
+            <pathconvert property="test.class.fqn">
+              <fileset file="${classes}${file.separator}${test.class.path}"/>
+              <chainedmapper>
+                  <globmapper    from="${classes.path}${file.separator}*" to="*"/> <!-- rel. -->
+                  <packagemapper from="*.class"           to="*"/> <!-- FQCN -->
+              </chainedmapper>
+            </pathconvert>
+            <var name="test.class.result.file" value="${results.test}/TEST-${test.class.fqn}.xml"/>
+            <echo message="Testing ${test.class.fqn} -- ${test.class.result.file}"/>
+            <echo message="${line.separator}
+export DISPLAY=:0.0${line.separator}
+java \${line.separator}
+${junit.run.arg0}\${line.separator}
+${junit.run.arg1}\${line.separator}
+${jvmDataModel.arg}\${line.separator}
+-cp ${junit_jogl_awt.run.remote.jars}\${line.separator}
+org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \${line.separator}
+${test.class.fqn} \${line.separator}
+filtertrace=true \${line.separator}
+haltOnError=false \${line.separator}
+haltOnFailure=false \${line.separator}
+showoutput=true \${line.separator}
+outputtoformatters=true \${line.separator}
+logfailedtests=true \${line.separator}
+logtestlistenerevents=true \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.class.result.file} ${line.separator}
+${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+          </sequential>
+        </for>
+        <exec dir="." executable="sh" logError="true" failonerror="true" failifexecutionfails="true">
+            <arg line='-x -c "
+            chmod 0755 ${build.test}/targetcommand.sh ;
+            scp ${build.test}/targetcommand.sh ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            ssh -x ${env.TARGET_UID}@${env.TARGET_IP} ${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            scp -pr ${env.TARGET_UID}@${env.TARGET_IP}:${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make/${results.test}/* ${results.test}/ "'/>
+        </exec>
+    </target>
+
+<!--
+rsync:
+    -a == -rlptgoD
+    -rt 
+-->
+
+    <target name="junit.run.remote.adb" if="isAndroidARMv7">
+        <echo message="#! /system/bin/sh${line.separator}" append="false" file="${build.test}/targetcommand.sh" />
+        <echo message="${line.separator}
+rsync -rtv --delete --delete-after --delete-excluded \${line.separator}
+      --exclude 'build-x86*/' --exclude 'build-linux*/' --exclude 'build-win*/' --exclude 'build-mac*/' \${line.separator}
+      --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \${line.separator}
+      --exclude 'gensrc/' --exclude 'doc/' --exclude 'jnlp-files' --exclude 'archive/' \${line.separator}
+      --exclude 'android-sdk/' --exclude 'resources/' --exclude 'scripts/' \${line.separator}
+      --exclude 'stub_includes/' --exclude 'nbproject/' --exclude '*.log' --exclude '*.zip' --exclude '*.7z' \${line.separator}
+      ${env.HOST_UID}@${env.HOST_IP}::${env.HOST_RSYNC_ROOT}/${gluegen.basename} \${line.separator}
+      ${env.HOST_UID}@${env.HOST_IP}::${env.HOST_RSYNC_ROOT}/${jogl.basename} \${line.separator}
+      ${env.TARGET_ROOT} ${line.separator}
+mkdir ${env.TARGET_ROOT}/tmp ${line.separator}
+cd ${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make ${line.separator}
+export ${system.env.library.path}=/system/lib:${env.TARGET_ROOT}/${gluegen.basename}/${env.NODE_LABEL}/${rootrel.build}/obj:${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/${rootrel.build}/lib ${line.separator}
+# export BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar ${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+
+        <for param="test.class.path.m" keepgoing="true">
+            <!-- results in absolute path -->
+            <fileset dir="${classes}">
+                <!--include name="${java.dir.junit}/**/Test*NEWT*"/-->
+                <include name="${java.dir.junit}/**/TestMainVersionGLWindowNEWT*"/>
+                <!--include name="${java.dir.junit}/**/TestGLProfile01NEWT*"/-->
+                <exclude name="**/*$$*"/>
+            </fileset>
+          <sequential>
+            <var name="test.class.path" unset="true"/>
+            <property name="test.class.path" basedir="${classes}" relative="true" location="@{test.class.path.m}"/>
+            <var name="test.class.fqn" unset="true"/>
+            <pathconvert property="test.class.fqn">
+              <fileset file="${classes}${file.separator}${test.class.path}"/>
+              <chainedmapper>
+                  <globmapper    from="${classes.path}${file.separator}*" to="*"/> <!-- rel. -->
+                  <packagemapper from="*.class"           to="*"/> <!-- FQCN -->
+              </chainedmapper>
+            </pathconvert>
+            <var name="test.class.result.file" value="${results.test}/TEST-${test.class.fqn}.xml"/>
+            <echo message="Testing ${test.class.fqn} -- ${test.class.result.file}"/>
+            <echo message="${line.separator}
+dalvikvm \${line.separator}
+-Xjnigreflimit:2000 \${line.separator}
+${junit.run.arg0}\${line.separator}
+${junit.run.arg1}\${line.separator}
+-cp ${junit.run.remote.apks} \${line.separator}
+-Dgluegen.root=${gluegen.root} \${line.separator}
+-Drootrel.build=${rootrel.build} \${line.separator}
+com.android.internal.util.WithFramework \${line.separator}
+org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \${line.separator}
+${test.class.fqn} \${line.separator}
+filtertrace=true \${line.separator}
+haltOnError=false \${line.separator}
+haltOnFailure=false \${line.separator}
+showoutput=true \${line.separator}
+outputtoformatters=true \${line.separator}
+logfailedtests=true \${line.separator}
+logtestlistenerevents=true \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \${line.separator}
+formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,${test.class.result.file} ${line.separator}
+${line.separator}
+" append="true" file="${build.test}/targetcommand.sh" />
+          </sequential>
+        </for>
+        <exec dir="." executable="sh" logError="true" failonerror="true" failifexecutionfails="true">
+            <arg line='-x -c "
+            chmod 0755 ${build.test}/targetcommand.sh ;
+            adb connect ${env.TARGET_IP}:${env.TARGET_ADB_PORT} ;
+            adb -s ${env.TARGET_IP}:${env.TARGET_ADB_PORT} push ${build.test}/targetcommand.sh ${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            adb -s ${env.TARGET_IP}:${env.TARGET_ADB_PORT} shell su -c ${env.TARGET_ROOT}/jogl-targetcommand.sh ;
+            adb -s ${env.TARGET_IP}:${env.TARGET_ADB_PORT} pull ${env.TARGET_ROOT}/${jogl.basename}/${env.NODE_LABEL}/make/${results.test}/ ${results.test}/ "'/>
+        </exec>
+    </target>
+
+    <target name="junit.run.tests" depends="junit.run.local.d32, junit.run.local, junit.run.remote.ssh.all, junit.run.remote.adb"/>
+
+    <target name="junit.run.settings" depends="declare.common">
         <delete quiet="true">
             <fileset dir="${results.test}" includes="**"/>
             <fileset dir="${build}/test/results-x32" includes="**"/>
             <fileset file="${build}/${test.archive.name}.7z"/>
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
             <fileset dir="." includes="*.tga" />
         </delete>
         <mkdir dir="${results.test}" />
     </target>
 
-    <target name="junit.run" depends="declare.common, junit.run.settings, junit.run.d32, junit.run.tests">
+    <target name="junit.run.if.enabled" unless="junit.is.disabled">
+        <antcall target="junit.run.tests"      inheritRefs="true" inheritAll="true"/>
+    </target>
+    <target name="junit.run.if.disabled" if="junit.is.disabled">
+        <copy todir="${results.test}" file="${gluegen.root}/make/lib/TEST-com.jogamp.junit.DisabledTest.xml"/>
+    </target>
+
+    <target name="junit.run" depends="junit.run.settings, junit.run.if.enabled, junit.run.if.disabled">
+        <mkdir dir="${results.test}" />
+        <move todir="${results.test}">
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
+            <fileset dir="." includes="*.tga" />
+        </move>
+        <antcall target="test-zip-archive" inheritRefs="true" inheritAll="true"/>
+    </target>
+
+    <target name="junit.manual.run.remote.ssh.newt" depends="junit.run.settings, junit.run.remote.ssh.newt">
         <mkdir dir="${results.test}" />
         <move todir="${results.test}">
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
             <fileset dir="." includes="*.tga" />
         </move>
         <antcall target="test-zip-archive" inheritRefs="true" inheritAll="true"/>
     </target>
 
+    <target name="junit.manual.run.remote.ssh.awt" depends="junit.run.settings, junit.run.remote.ssh.awt">
+        <mkdir dir="${results.test}" />
+        <move todir="${results.test}">
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
+            <fileset dir="." includes="*.tga" />
+        </move>
+        <antcall target="test-zip-archive" inheritRefs="true" inheritAll="true"/>
+    </target>
+
+    <target name="junit.manual.run.remote.ssh.all" depends="junit.run.settings, junit.run.remote.ssh.all">
+        <mkdir dir="${results.test}" />
+        <move todir="${results.test}">
+            <fileset dir="." includes="*.png" />
+            <fileset dir="." includes="*.pam" />
+            <fileset dir="." includes="*.tga" />
+        </move>
+        <antcall target="test-zip-archive" inheritRefs="true" inheritAll="true"/>
+    </target>
+
+    <target name="test.auto.run" depends="junit.run"/>
+
     <!-- updates / create the test results zip file -->
     <target name="test-zip-archive" depends="declare.common">
         <archive.7z destfile="${build}/${test.archive.name}.7z"
diff --git a/make/build.xml b/make/build.xml
index 791e69a..5f85f9a 100644
--- a/make/build.xml
+++ b/make/build.xml
@@ -16,12 +16,10 @@
 
     <target name="all.ide" description="Debug IDE build nativewindow, jogl and newt projects, including all junit tests, but don't tag the build or create archives" depends="init.debug,build.nativewindow,build.jogl,build.newt,one.dir,test.compile" />
 
-    <target name="test.compile.1">
+    <target name="test.compile">
       <ant antfile="build-test.xml" target="test.compile" inheritRefs="true" inheritAll="true"/>
     </target>
 
-    <target name="test.compile" depends="test.compile.1,android.test.package"/>
-
     <target name="test.auto.run" description="Run automated tests (junit and others) in nativewindow, jogl and newt projects">
       <ant antfile="build-test.xml" target="test.auto.run" inheritRefs="true" inheritAll="true"/>
     </target>
@@ -105,7 +103,7 @@
             <archives>
                 <zips>
                     <path refid="nativewindow_core_atoms.classpath"/>
-                    <path refid="jogl_all-mobile_atoms.classpath"/>
+                    <path refid="jogl_all-android_atoms.classpath"/>
                     <path refid="newt_all-android_atoms.classpath"/>
                 </zips>
             </archives>
@@ -149,7 +147,7 @@
     </target>
 
     <target name="android.package.jogl.skip.check" depends="init,gluegen.cpptasks.detect.os">
-      <uptodate property="android.package.jogl.skip" targetfile="${jar}/jogl.all-android.apk">
+      <uptodate property="android.package.jogl.skip" targetfile="${jogl.all-android.apk}">
         <srcfiles dir="${jar}" includes="jogl.all-android.jar" />
         <srcfiles dir="resources/android" includes="**" />
       </uptodate>
@@ -157,11 +155,13 @@
 
     <target name="android.jogl.package" depends="init,gluegen.cpptasks.detect.os,android.package.jogl.skip.check" if="isAndroid" unless="android.package.jogl.skip">
         <aapt.signed 
+            assetsdir="resources/assets"
             jarsrcdir="${src}/jogl/classes"
             jarbuilddir="${jar}"
             jarbasename="jogl.all-android"
             nativebuilddir="${lib}"
             nativebasename=""
+            android.abi="${android.abi}"
             androidmanifest.path="resources/android/AndroidManifest-jogl.xml"
             androidresources.path="resources/android/res-jogl"
             jarmanifest.path="${build.jogl}/manifest.mf"
@@ -169,55 +169,6 @@
             version.name="${jogl.version.plus}" />
     </target>
 
-    <target name="android.package.test.skip.check" depends="init,gluegen.cpptasks.detect.os">
-      <uptodate property="android.package.test.skip" targetfile="${jar}/jogl.test.apk">
-        <srcfiles dir="${jar}" includes="jogl.test.jar" />
-        <srcfiles dir="resources/android" includes="**" />
-      </uptodate>
-    </target>
-
-    <target name="android.test.package" depends="init,gluegen.cpptasks.detect.os,android.package.test.skip.check" if="isAndroid" unless="android.package.test.skip">
-        <aapt.signed 
-            jarsrcdir="${src}/test"
-            jarbuilddir="${jar}"
-            jarbasename="jogl.test"
-            nativebuilddir="${lib}"
-            nativebasename="non-existing"
-            androidmanifest.path="resources/android/AndroidManifest-test.xml"
-            androidresources.path="resources/android/res-jogl"
-            jarmanifest.path="${build.jogl}/manifest.mf"
-            version.code="${jogl_int_version}"
-            version.name="${jogl.version.plus}" />
-    </target>
-
-    <target name="android.launcher.package" depends="init,gluegen.cpptasks.detect.os" if="isAndroid">
-        <mkdir dir="${build}/android/classes" />
-        <mkdir dir="${build}/android/lib" />
-        <javac destdir="${build}/android/classes"
-               includes="com/jogamp/android/launcher/**"
-               source="${target.sourcelevel}"
-               fork="yes"
-               includeAntRuntime="false"
-               memoryMaximumSize="${javac.memorymax}"
-               debug="${javacdebug}" debuglevel="${javacdebuglevel}">
-            <src path="${project.root}/src/android" />
-            <classpath location="${android.jar}"/>
-        </javac>
-        <jar destfile="${jar}/jogl.android-launcher.jar" filesonly="true">
-            <fileset dir="${build}/android/classes"
-                     includes="com/jogamp/android/launcher/**"/>
-        </jar>
-        <aapt.signed 
-            jarbuilddir="${jar}"
-            jarbasename="jogl.android-launcher"
-            nativebuilddir="${build}/android/lib"
-            nativebasename="non-existing"
-            androidmanifest.path="resources/android/AndroidManifest-launcher.xml"
-            androidresources.path="resources/android/res-launcher"
-            version.code="1"
-            version.name="version 1" />
-    </target>
-
     <target name="one.dir.skip.check" depends="init,gluegen.cpptasks.detect.os">
       <uptodate property="one.dir.skip.native" targetfile="${jar}/jogl-all-natives-${os.and.arch}.jar">
         <srcfiles dir="${lib}" includes="*.${native.library.suffix}" />
@@ -241,7 +192,7 @@
       </condition>
     </target>
 
-    <target name="one.dir" depends="one.dir.skip.check, one.jar.dir, android.jogl.package, android.launcher.package"/>
+    <target name="one.dir" depends="one.dir.skip.check, one.jar.dir, android.jogl.package"/>
 
     <target name="repack-jars" depends="one.jar.dir">
         <!-- Re-pack jars we have the intent to compress later, after signing -->
@@ -417,8 +368,9 @@
                  windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
                  access="public"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="1024m"
+                 maxmemory="${javac.memorymax}"
                  bottom="${javadoc.bottom}" >
             <classpath refid="jogl_all.classpath"/>
             <link offline="true" href="${javadoc.link}" packagelistLoc="${gluegen.root}/make/142-packages" />
@@ -438,8 +390,9 @@
                  windowtitle="${javadoc.spec.windowtitle}"
                  overview="${javadoc.overview}"
                  access="public"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="1024m"
+                 maxmemory="${javac.memorymax}"
                  bottom="${javadoc.bottom}" >
             <classpath refid="jogl_all.classpath"/>
             <link offline="true" href="${javadoc.link}" packagelistLoc="${gluegen.root}/make/142-packages" />
@@ -460,8 +413,9 @@
                  windowtitle="${javadoc.windowtitle}"
                  overview="${javadoc.overview}" 
                  access="protected"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="1024m"
+                 maxmemory="${javac.memorymax}"
                  bottom="${javadoc.bottom}" >
             <classpath refid="jogl_all.classpath"/>
             <link offline="true" href="${javadoc.link}" packagelistLoc="${gluegen.root}/make/142-packages" />
@@ -481,8 +435,9 @@
                  windowtitle="${javadoc.nw.spec.windowtitle}"
                  overview="${javadoc.nw.overview}"
                  access="public"
+                 encoding="UTF-8"
                  source="${target.sourcelevel}"
-                 maxmemory="1024m"
+                 maxmemory="${javac.memorymax}"
                  bottom="${javadoc.bottom}" >
             <classpath refid="jogl_all.classpath"/>
             <link offline="true" href="${javadoc.link}" packagelistLoc="${gluegen.root}/make/142-packages" />
diff --git a/make/config/jogl/cg-common.cfg b/make/config/jogl/cg-common.cfg
index f21ece3..35805bf 100644
--- a/make/config/jogl/cg-common.cfg
+++ b/make/config/jogl/cg-common.cfg
@@ -108,6 +108,7 @@ Import com.jogamp.opengl.cg.CgDynamicLibraryBundleInfo
 
 #
 # NIODirectOnly directives for routines requiring them for semantic reasons
+#               essential where the buffer lifecycle extends the function call
 #
 NIODirectOnly cgGLSetParameterPointer
 
diff --git a/make/config/jogl/egl-common.cfg b/make/config/jogl/egl-common.cfg
index da0e332..cf5d0b0 100644
--- a/make/config/jogl/egl-common.cfg
+++ b/make/config/jogl/egl-common.cfg
@@ -10,20 +10,18 @@ Import javax.media.opengl.fixedfunc.*
 Import jogamp.opengl.*
 
 # Treat all of the EGL types as opaque longs
-# Opaque long EGLConfig
+Opaque long EGLConfig
 Opaque long EGLContext
 Opaque long EGLDisplay
 Opaque long EGLSurface
 Opaque long EGLNativeDisplayType
 Opaque long EGLNativeWindowType
 Opaque long EGLNativePixmapType
-Opaque long EGLClientBuffer
 Opaque long EGLImageKHR
 #Opaque long EGLPerfMonitorNV
 #Opaque long EGLPerfCounterNV
 #Opaque long EGLPerfMarkerNV
 Opaque long EGLSyncKHR
-Opaque long NativeSyncKHR
 Opaque boolean EGLBoolean
 
 # Make eglGetProcAddress return an opaque long
@@ -43,3 +41,7 @@ ForceProcAddressGen __ALL__
 # pointer typedefs for these routines to EGLAPIENTRY
 LocalProcAddressCallingConvention __ALL__ EGLAPIENTRY
 
+# Using EGLClientBuffer as argument, 
+# which native pointer exceeds the native function call lifetime
+NIODirectOnly eglCreatePbufferFromClientBuffer
+NIODirectOnly eglCreateImageKHR
diff --git a/make/config/jogl/gl-common-extensions.cfg b/make/config/jogl/gl-common-extensions.cfg
index 1f294ee..51edd9e 100644
--- a/make/config/jogl/gl-common-extensions.cfg
+++ b/make/config/jogl/gl-common-extensions.cfg
@@ -48,7 +48,6 @@ IgnoreExtension GL_NV_vertex_program
 IgnoreExtension GL_NV_present_video
 
 # For the time being, ignore these extensions which are in the ES 2.0 spec
-IgnoreExtension GL_NV_coverage_sample
 IgnoreExtension GL_NV_framebuffer_vertex_attrib_array
 
 # Remove extension suffixes from extensions which are common between OpenGL and OpenGL ES
@@ -74,6 +73,39 @@ RenameExtensionIntoCore GL_OES_texture_cube_map
 RenameExtensionIntoCore GL_OES_texture_half_float
 RenameExtensionIntoCore GL_OES_texture_mirrored_repeat
 RenameExtensionIntoCore GL_OES_vertex_type_10_10_10_2
+RenameExtensionIntoCore GL_EXT_color_buffer_half_float
+RenameExtensionIntoCore GL_EXT_occlusion_query_boolean
+RenameExtensionIntoCore GL_EXT_robustness
+RenameExtensionIntoCore GL_ARB_robustness
+RenameExtensionIntoCore GL_EXT_separate_shader_objects
+RenameExtensionIntoCore GL_EXT_shadow_samplers
+RenameExtensionIntoCore GL_EXT_sRGB
+RenameExtensionIntoCore GL_EXT_texture_array
+RenameExtensionIntoCore GL_EXT_texture_rg
+RenameExtensionIntoCore GL_EXT_texture_type_2_10_10_10_REV
+RenameExtensionIntoCore GL_NV_draw_buffers
+RenameExtensionIntoCore GL_NV_fbo_color_attachments
+RenameExtensionIntoCore GL_EXT_packed_float
+RenameExtensionIntoCore GL_EXT_texture_format_BGRA8888
+
+# A mess w/ the ES2 definition .. sadly
+# RenameExtensionIntoCore GL_EXT_texture_storage
+RenameJavaSymbol glTexStorage1DEXT glTexStorage1D
+RenameJavaSymbol glTexStorage2DEXT glTexStorage2D
+RenameJavaSymbol glTexStorage3DEXT glTexStorage3D
+RenameJavaSymbol GL_TEXTURE_IMMUTABLE_FORMAT_EXT GL_TEXTURE_IMMUTABLE_FORMAT
+RenameJavaSymbol GL_RGBA32F_EXT                  GL_RGBA32F
+RenameJavaSymbol GL_RGB32F_EXT                   GL_RGB32F
+RenameJavaSymbol GL_ALPHA32F_EXT                 GL_ALPHA32F_ARB
+RenameJavaSymbol GL_LUMINANCE32F_EXT             GL_LUMINANCE32F_ARB
+RenameJavaSymbol GL_LUMINANCE_ALPHA32F_EXT       GL_LUMINANCE_ALPHA32F_ARB
+RenameJavaSymbol GL_RGB16F_EXT                   GL_RGB16F
+RenameJavaSymbol GL_ALPHA16F_EXT                 GL_ALPHA16F_ARB
+RenameJavaSymbol GL_LUMINANCE16F_EXT             GL_LUMINANCE16F_ARB
+RenameJavaSymbol GL_LUMINANCE_ALPHA16F_EXT       GL_LUMINANCE_ALPHA16F_ARB
+RenameJavaSymbol GL_RGB10_A2_EXT                 GL_RGB10_A2
+RenameJavaSymbol GL_RGB10_EXT                    GL_RGB10
+
 
 # The following extensions have some differences requiring us to
 # manually rename some symbols and leave others alone for best
diff --git a/make/config/jogl/gl-common.cfg b/make/config/jogl/gl-common.cfg
index 74af5cf..8af080e 100644
--- a/make/config/jogl/gl-common.cfg
+++ b/make/config/jogl/gl-common.cfg
@@ -232,7 +232,9 @@ IgnoreExtension GL_EXT_framebuffer_object
 RenameExtensionIntoCore GL_NV_half_float
 RenameExtensionIntoCore GL_ARB_half_float_pixel
 
-RenameExtensionIntoCore GL_EXT_framebuffer_multisample
+# naming collision w/ GL_EXT_multisampled_render_to_texture, but included anyways
+# RenameExtensionIntoCore GL_EXT_framebuffer_multisample 
+IgnoreExtension GL_EXT_framebuffer_multisample 
 RenameExtensionIntoCore GL_EXT_framebuffer_blit
 
 #Big gap of promoted tokens and functions: GL_EXT_texture_integer
@@ -334,11 +336,15 @@ IgnoreExtension GL_EXT_vertex_attrib_64bit
 RenameExtensionIntoCore GL_ARB_viewport_array
 # <<< OpenGL 4.1
 
+# >>> OpenGL 4.2
+# Rename extension suffices (if exist) subsumed in OpenGL 4.2 (from OpenGL 4.2 spec, Appendix L.1)
+# <<< OpenGL 4.2
+
 # Ignore a few obsolete versions of extensions that have been subsumed into the core or ARB extensions
 IgnoreExtension GL_EXT_multisample
 IgnoreExtension GL_EXT_point_parameters
 IgnoreExtension GL_EXT_separate_shader_objects
-
+IgnoreExtension GL_EXT_shader_image_load_store
 
 #
 # Opaques and other directives for platform-independent routines
@@ -346,6 +352,7 @@ IgnoreExtension GL_EXT_separate_shader_objects
 
 Opaque boolean GLboolean
 Opaque long GLsync
+Opaque long GLeglImageOES
 ReturnsString glGetString
 ReturnsString glGetStringi
 
@@ -354,51 +361,48 @@ ReturnsString glGetStringi
 
 #
 # NIODirectOnly directives for vertex arrays and other core routines
+#               essential where the buffer lifecycle extends the function call.
 #
-
-NIODirectOnly glColorPointer
-NIODirectOnly glEdgeFlagPointer
-NIODirectOnly glFeedbackBuffer
-NIODirectOnly glIndexPointer
-NIODirectOnly glNormalPointer
-NIODirectOnly glSelectBuffer
-NIODirectOnly glTexCoordPointer
-NIODirectOnly glVertexPointer
+# Note: API calls like glColorPointer(..) will not be exploded to 
+#       multiple primitive arrays, since the pointer argument is 'void *'.
 #
-# FIXME: we should probably be ignoring the "EXT" variants of these
-#
-NIODirectOnly glColorPointerEXT
-NIODirectOnly glEdgeFlagPointerEXT
-NIODirectOnly glIndexPointerEXT
-NIODirectOnly glNormalPointerEXT
-NIODirectOnly glTexCoordPointerEXT
-NIODirectOnly glVertexPointerEXT
+
+#NIO Review: No technical reason to constrain array access for these:
+#NIODirectOnly glColorPointer
+#NIODirectOnly glEdgeFlagPointer
+#NIODirectOnly glIndexPointer
+#NIODirectOnly glNormalPointer
+#NIODirectOnly glTexCoordPointer
+#NIODirectOnly glVertexPointer
+#NIODirectOnly glVertexAttribPointer
+#NIODirectOnly glFogCoordPointer
+#NIODirectOnly glSecondaryColorPointer
+
+#Return values
+#NIODirectOnly glGenBuffers
+#NIODirectOnly glGetPointerv
+#NIODirectOnly glFeedbackBuffer
+#NIODirectOnly glSelectBuffer
+#NIODirectOnly glGetBufferSubData
+
 #
 # NIODirectOnly directives for other extensions
 #
-NIODirectOnly glBinormalPointerEXT
-NIODirectOnly glGetBufferSubDataARB
-# FIXME: should add way to restrict argument to be a direct ByteBuffer
+#NIO Review: No technical reason to constrain array access for these:
+#NIODirectOnly glMatrixIndexPointerARB
 NIODirectOnly glGetProgramStringARB
-NIODirectOnly glElementPointerATI
-NIODirectOnly glElementPointerNV
-NIODirectOnly glElementPointerAPPLE
-NIODirectOnly glFogCoordPointer
-NIODirectOnly glFogCoordPointerEXT
-NIODirectOnly glMatrixIndexPointerARB
 NIODirectOnly glPixelDataRangeNV
-NIODirectOnly glSecondaryColorPointer
-NIODirectOnly glSecondaryColorPointerEXT
-NIODirectOnly glTangentPointerEXT
 NIODirectOnly glVertexArrayRangeNV
 NIODirectOnly glVertexArrayRangeApple
-NIODirectOnly glVertexAttribPointerARB
-NIODirectOnly glVertexAttribPointerNV
-NIODirectOnly glVertexWeightPointerEXT
-NIODirectOnly glWeightPointerARB
 NIODirectOnly wglFreeMemoryNV
 NIODirectOnly glXFreeMemoryNV
 
+#
+# NIOOnly for a few API calls ..
+#
+NIOOnly glVertexAttribPointerNV
+NIOOnly glVertexWeightPointerEXT
+
 # Capacity of wglAllocateMemoryNV/glXAllocateMemoryNV return value is
 # same as value of first argument
 ReturnValueCapacity wglAllocateMemoryNV {0}
diff --git a/make/config/jogl/gl-es1.cfg b/make/config/jogl/gl-es1.cfg
index 518dc07..2a7b64d 100644
--- a/make/config/jogl/gl-es1.cfg
+++ b/make/config/jogl/gl-es1.cfg
@@ -14,8 +14,8 @@ Ignore glGetBufferPointervOES
 Package javax.media.opengl
 Style InterfaceAndImpl
 JavaClass GLES1
-Extends GLES1 GLBase
-Extends GLES1 GL
+#Extends GLES1 GLBase
+#Extends GLES1 GL
 Extends GLES1 GL2ES1
 ImplPackage jogamp.opengl.es1
 ImplJavaClass GLES1Impl
@@ -67,7 +67,7 @@ JavaPrologue glPixelStorei glStateTracker.setInt(pname, param);
 JavaPrologue glGetIntegerv if ( glStateTracker.getInt(pname, params, params_offset) ) { return; }
 
 CustomJavaCode GLES1Impl  public void glOrtho(double left, double right, double bottom, double top, double near_val, double far_val) {
-CustomJavaCode GLES1Impl    glOrtho((float) left, (float) right, (float) bottom, (float) top, (float) near_val, (float) far_val); }
+CustomJavaCode GLES1Impl    glOrthof((float) left, (float) right, (float) bottom, (float) top, (float) near_val, (float) far_val); }
                 
 CustomJavaCode GLES1Impl  public void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar) {
 CustomJavaCode GLES1Impl    glFrustumf((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar); }
diff --git a/make/config/jogl/gl-es2.cfg b/make/config/jogl/gl-es2.cfg
index 614904a..8b6152b 100644
--- a/make/config/jogl/gl-es2.cfg
+++ b/make/config/jogl/gl-es2.cfg
@@ -9,8 +9,8 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/GLBase.jav
 Package javax.media.opengl
 Style InterfaceAndImpl
 JavaClass GLES2
-Extends GLES2 GLBase
-Extends GLES2 GL
+#Extends GLES2 GLBase
+#Extends GLES2 GL
 Extends GLES2 GL2ES2
 ImplPackage jogamp.opengl.es2
 ImplJavaClass GLES2Impl
diff --git a/make/config/jogl/gl-gl4bc.cfg b/make/config/jogl/gl-gl4bc.cfg
index 67582af..ae77b2e 100644
--- a/make/config/jogl/gl-gl4bc.cfg
+++ b/make/config/jogl/gl-gl4bc.cfg
@@ -18,13 +18,13 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/fixedfunc/
 Package javax.media.opengl
 Style InterfaceAndImpl
 JavaClass GL4bc
-Extends GL4bc GLBase
-Extends GL4bc GL
-Extends GL4bc GL2ES1
-Extends GL4bc GL2ES2
-Extends GL4bc GL2GL3
-Extends GL4bc GL2
-Extends GL4bc GL3
+#Extends GL4bc GLBase
+#Extends GL4bc GL
+#Extends GL4bc GL2ES1
+#Extends GL4bc GL2ES2
+#Extends GL4bc GL2GL3
+#Extends GL4bc GL2
+#Extends GL4bc GL3
 Extends GL4bc GL3bc
 Extends GL4bc GL4
 ImplPackage jogamp.opengl.gl4
diff --git a/make/config/jogl/gl-if-CustomJavaCode-gl2_es2.java b/make/config/jogl/gl-if-CustomJavaCode-gl2_es2.java
index 1599a89..4522d34 100644
--- a/make/config/jogl/gl-if-CustomJavaCode-gl2_es2.java
+++ b/make/config/jogl/gl-if-CustomJavaCode-gl2_es2.java
@@ -1,3 +1,5 @@
+  /** Part of <code>GL_ARB_separate_shader_objects</code>, <code>GL_EXT_separate_shader_objects</code> */
+  public static final int GL_ALL_SHADER_BITS = 0xFFFFFFFF ;
 
   /** Start: GL_ARB_ES2_compatibility functions, which are part of ES2 core as well */
 
diff --git a/make/config/jogl/gl-if-CustomJavaCode-gl2_gl3.java b/make/config/jogl/gl-if-CustomJavaCode-gl2_gl3.java
index 1777c15..97fd6c4 100644
--- a/make/config/jogl/gl-if-CustomJavaCode-gl2_gl3.java
+++ b/make/config/jogl/gl-if-CustomJavaCode-gl2_gl3.java
@@ -5,4 +5,6 @@ public static final int GL_INVALID_INDEX = 0xFFFFFFFF ;
 /** Part of <code>GL_ARB_sync</code> */
 public static final long GL_TIMEOUT_IGNORED = 0xFFFFFFFFFFFFFFFFL ;
 
+/** Part of <code>GL_ARB_shader_image_load_store</code> */
+public static final int GL_ALL_BARRIER_BITS = 0xFFFFFFFF ;
 
diff --git a/make/config/jogl/gl-if-gl-ignores.cfg b/make/config/jogl/gl-if-gl-ignores.cfg
index 94e26d8..220bd74 100644
--- a/make/config/jogl/gl-if-gl-ignores.cfg
+++ b/make/config/jogl/gl-if-gl-ignores.cfg
@@ -18,13 +18,140 @@ IgnoreExtension GL_EXT_discard_framebuffer
 IgnoreExtension GL_OES_compressed_paletted_texture
 IgnoreExtension GL_OES_get_program_binary
 IgnoreExtension GL_OES_standard_derivatives
-# subsumed, so ignore the aliased ones
 IgnoreExtension GL_OES_vertex_type_10_10_10_2
-Ignore GL_UNSIGNED_INT_10_10_10_2
-Ignore GL_INT_10_10_10_2
+IgnoreExtension GL_EXT_texture_type_2_10_10_10_REV
+IgnoreExtension GL_EXT_color_buffer_half_float
+IgnoreExtension GL_EXT_occlusion_query_boolean
+IgnoreExtension GL_EXT_separate_shader_objects
+IgnoreExtension GL_EXT_shadow_samplers
+IgnoreExtension GL_EXT_sRGB
+IgnoreExtension GL_EXT_texture_array
+IgnoreExtension GL_EXT_texture_rg
+IgnoreExtension GL_OES_compressed_ETC1_RGB8_texture
+IgnoreExtension GL_EXT_debug_marker
+IgnoreExtension GL_EXT_debug_label
+IgnoreExtension GL_EXT_multisampled_render_to_texture
+IgnoreExtension GL_EXT_framebuffer_multisample
 
+# IgnoreExtension GL_EXT_texture_storage
+IgnoreExtension GL_NV_draw_buffers
+IgnoreExtension GL_NV_fbo_color_attachments
 IgnoreExtension GL_OES_vertex_array_object
 IgnoreExtension GL_OES_texture_3D
+# above ext are subsumed, so ignore the aliased ones
+Ignore GL_ACTIVE_PROGRAM
+Ignore GL_ALPHA16F
+Ignore GL_ALPHA32F
+Ignore GL_ALPHA8
+Ignore GL_ANY_SAMPLES_PASSED
+Ignore GL_ANY_SAMPLES_PASSED_CONSERVATIVE
+Ignore GL_BGRA8
+Ignore GL_BGRA8_EXT
+Ignore GL_BUFFER_OBJECT_EXT
+Ignore GL_COLOR_ATTACHMENT1
+Ignore GL_COLOR_ATTACHMENT10
+Ignore GL_COLOR_ATTACHMENT11
+Ignore GL_COLOR_ATTACHMENT12
+Ignore GL_COLOR_ATTACHMENT13
+Ignore GL_COLOR_ATTACHMENT14
+Ignore GL_COLOR_ATTACHMENT15
+Ignore GL_COLOR_ATTACHMENT2
+Ignore GL_COLOR_ATTACHMENT3
+Ignore GL_COLOR_ATTACHMENT4
+Ignore GL_COLOR_ATTACHMENT5
+Ignore GL_COLOR_ATTACHMENT6
+Ignore GL_COLOR_ATTACHMENT7
+Ignore GL_COLOR_ATTACHMENT8
+Ignore GL_COLOR_ATTACHMENT9
+Ignore GL_COMPARE_REF_TO_TEXTURE
+Ignore GL_CONTEXT_ROBUST_ACCESS
+Ignore GL_CURRENT_QUERY
+Ignore GL_DRAW_BUFFER0
+Ignore GL_DRAW_BUFFER1
+Ignore GL_DRAW_BUFFER10
+Ignore GL_DRAW_BUFFER11
+Ignore GL_DRAW_BUFFER12
+Ignore GL_DRAW_BUFFER13
+Ignore GL_DRAW_BUFFER14
+Ignore GL_DRAW_BUFFER15
+Ignore GL_DRAW_BUFFER2
+Ignore GL_DRAW_BUFFER3
+Ignore GL_DRAW_BUFFER4
+Ignore GL_DRAW_BUFFER5
+Ignore GL_DRAW_BUFFER6
+Ignore GL_DRAW_BUFFER7
+Ignore GL_DRAW_BUFFER8
+Ignore GL_DRAW_BUFFER9
+Ignore GL_FRAGMENT_SHADER_BIT
+Ignore GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING
+Ignore GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE
+Ignore GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT
+Ignore GL_INT_10_10_10_2
+Ignore GL_LUMINANCE16F
+Ignore GL_LUMINANCE32F
+Ignore GL_LUMINANCE8
+Ignore GL_LUMINANCE8_ALPHA8
+Ignore GL_LUMINANCE_ALPHA16F
+Ignore GL_LUMINANCE_ALPHA32F
+Ignore GL_MAX_COLOR_ATTACHMENTS
+Ignore GL_MAX_DRAW_BUFFERS
+Ignore GL_PROGRAM_OBJECT_EXT
+Ignore GL_PROGRAM_PIPELINE_BINDING
+Ignore GL_PROGRAM_PIPELINE_OBJECT_EXT
+Ignore GL_PROGRAM_SEPARABLE
+Ignore GL_QUERY_OBJECT_EXT
+Ignore GL_QUERY_RESULT
+Ignore GL_QUERY_RESULT_AVAILABLE
+Ignore GL_R16F
+Ignore GL_R8
+Ignore GL_RED
+Ignore GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES
+Ignore GL_RG
+Ignore GL_RG16F
+Ignore GL_RG8
+Ignore GL_RGB16F
+Ignore GL_RGBA16F
+Ignore GL_SAMPLER_2D_SHADOW
+Ignore GL_SAMPLER_EXTERNAL_OES
+Ignore GL_SHADER_BINARY_DMP
+Ignore GL_SHADER_OBJECT_EXT
+Ignore GL_TEXTURE_BINDING_EXTERNAL_OES
+Ignore GL_TEXTURE_COMPARE_FUNC
+Ignore GL_TEXTURE_COMPARE_MODE
+Ignore GL_TEXTURE_EXTERNAL_OES
+Ignore GL_UNPACK_ROW_LENGTH
+Ignore GL_UNPACK_SKIP_PIXELS
+Ignore GL_UNPACK_SKIP_ROWS
+Ignore GL_UNSIGNED_INT_10_10_10_2
+Ignore GL_UNSIGNED_INT_2_10_10_10_REV
+Ignore GL_UNSIGNED_NORMALIZED
+Ignore GL_VERTEX_ARRAY_OBJECT_EXT
+Ignore GL_VERTEX_SHADER_BIT
+Ignore glFramebufferTexture2DMultisampleEXT
+Ignore glGetObjectLabelEXT
+Ignore glInsertEventMarkerEXT
+Ignore glLabelObjectEXT
+Ignore glPopGroupMarkerEXT
+Ignore glProgramUniform1f
+Ignore glProgramUniform1fv
+Ignore glProgramUniform1i
+Ignore glProgramUniform1iv
+Ignore glProgramUniform2f
+Ignore glProgramUniform2fv
+Ignore glProgramUniform2i
+Ignore glProgramUniform2iv
+Ignore glProgramUniform3f
+Ignore glProgramUniform3fv
+Ignore glProgramUniform3i
+Ignore glProgramUniform3iv
+Ignore glProgramUniform4f
+Ignore glProgramUniform4fv
+Ignore glProgramUniform4i
+Ignore glProgramUniform4iv
+Ignore glProgramUniformMatrix2fv
+Ignore glProgramUniformMatrix3fv
+Ignore glProgramUniformMatrix4fv
+Ignore glPushGroupMarkerEXT
 
 # isn't included in GL2
 Ignore GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET
diff --git a/make/config/jogl/gl-if-gl.cfg b/make/config/jogl/gl-if-gl.cfg
index 2f7932b..8923333 100644
--- a/make/config/jogl/gl-if-gl.cfg
+++ b/make/config/jogl/gl-if-gl.cfg
@@ -21,12 +21,15 @@ Ignore ^gl.*x
 Ignore ^gl.*xOES
 Ignore glEGL.*
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
 
 # Inform the glue code generator of the association between #defines
-# and functions and the extensions in which they are defined
+# and functions and the extensions in which they are defined.
+# This also gives a better API doc since it includes all extension names.
 GLHeader GLES2/gl2.h
 GLHeader GLES2/gl2ext.h
 GLHeader GL/gl.h
diff --git a/make/config/jogl/gl-if-gl2.cfg b/make/config/jogl/gl-if-gl2.cfg
index da6ca16..c58b73d 100644
--- a/make/config/jogl/gl-if-gl2.cfg
+++ b/make/config/jogl/gl-if-gl2.cfg
@@ -14,10 +14,10 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/fixedfunc/
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL2
-Extends GL2 GLBase
-Extends GL2 GL
+#Extends GL2 GLBase
+#Extends GL2 GL
 Extends GL2 GL2ES1
-Extends GL2 GL2ES2
+#Extends GL2 GL2ES2
 Extends GL2 GL2GL3
 Include gl-common.cfg
 Include gl-common-extensions.cfg
@@ -28,6 +28,12 @@ Include gl-if-gl4-ignores.cfg
 # Pick up on-line OpenGL javadoc thanks to user cylab on javagaming.org forums
 TagNativeBinding true
 
+# dummy procaddress config / force procaddress for comments
+EmitProcAddressTable false
+ProcAddressTableClassName DontGenerateProcAddressTableStuff
+GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
+
 # Ignore extensions that are already picked up via the GL2ES1 interface
 IgnoreExtension GL_EXT_point_parameters
 
@@ -36,7 +42,3 @@ CustomJavaCode GL2     public boolean glIsPBOUnpackEnabled();
 
 Include gl-headers.cfg
 
-EmitProcAddressTable false
-ProcAddressTableClassName DontGenerateProcAddressTableStuff
-GetProcAddressTableExpr DontGenerateProcAddressTableStuff
-
diff --git a/make/config/jogl/gl-if-gl2_es1.cfg b/make/config/jogl/gl-if-gl2_es1.cfg
index 2aaee06..ad8bbea 100644
--- a/make/config/jogl/gl-if-gl2_es1.cfg
+++ b/make/config/jogl/gl-if-gl2_es1.cfg
@@ -2,7 +2,7 @@
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL2ES1
-Extends GL2ES1 GLBase
+#Extends GL2ES1 GLBase
 Extends GL2ES1 GL
 Extends GL2ES1 GLMatrixFunc
 Extends GL2ES1 GLPointerFunc
@@ -35,6 +35,7 @@ DropUniqVendorExtensions VIV
 IgnoreExtension GL_EXT_discard_framebuffer
 IgnoreExtension GL_OES_compressed_paletted_texture
 IgnoreExtension GL_OES_vertex_array_object
+IgnoreExtension GL_OES_EGL_image_external
 
 IgnoreExtension GL_OES_compressed_ETC1_RGB8_texture
 IgnoreExtension GL_OES_draw_texture
@@ -44,6 +45,10 @@ IgnoreExtension GL_OES_point_size_array
 IgnoreExtension GL_OES_query_matrix
 IgnoreExtension GL_OES_vertex_half_float
 
+IgnoreExtension GL_EXT_debug_marker
+IgnoreExtension GL_EXT_debug_label
+IgnoreExtension GL_EXT_multisampled_render_to_texture
+
 # isn't included in GL2
 # includes GL_STATE_RESTORE, which hasn't the QCOM suffix
 IgnoreExtension GL_QCOM_extended_get
@@ -101,9 +106,11 @@ Ignore glGetFixedv
 CustomJavaCode GL2ES1 public void glOrtho(double left, double right, double bottom, double top, double near_val, double far_val);
 CustomJavaCode GL2ES1 public void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar);
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
 
 # Inform the glue code generator of the association between #defines
 # and functions and the extensions in which they are defined
diff --git a/make/config/jogl/gl-if-gl2_es2.cfg b/make/config/jogl/gl-if-gl2_es2.cfg
index a466ea5..6a8aef0 100644
--- a/make/config/jogl/gl-if-gl2_es2.cfg
+++ b/make/config/jogl/gl-if-gl2_es2.cfg
@@ -8,7 +8,7 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/GLBase.jav
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL2ES2
-Extends GL2ES2 GLBase
+#Extends GL2ES2 GLBase
 Extends GL2ES2 GL
 
 HierarchicalNativeOutput false
@@ -35,6 +35,10 @@ IgnoreExtension GL_EXT_discard_framebuffer
 IgnoreExtension GL_OES_compressed_paletted_texture
 IgnoreExtension GL_OES_compressed_ETC1_RGB8_texture
 IgnoreExtension GL_OES_vertex_array_object
+IgnoreExtension GL_OES_EGL_image_external
+IgnoreExtension GL_EXT_debug_marker
+IgnoreExtension GL_EXT_debug_label
+IgnoreExtension GL_EXT_multisampled_render_to_texture
 
 # isn't included in GL2
 # includes GL_STATE_RESTORE, which hasn't the QCOM suffix
@@ -61,12 +65,15 @@ CustomJavaCode GL2ES2 public void glDepthRange(double zNear, double zFar);
 
 IncludeAs CustomJavaCode GL2ES2 gl-if-CustomJavaCode-gl2_es2.java
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
 
 # Inform the glue code generator of the association between #defines
 # and functions and the extensions in which they are defined
+# This also gives a better API doc since it includes all extension names.
 GLHeader GLES2/gl2.h
 GLHeader GLES2/gl2ext.h
 GLHeader GL/gl.h
diff --git a/make/config/jogl/gl-if-gl2_gl3.cfg b/make/config/jogl/gl-if-gl2_gl3.cfg
index 99e241f..0c51dfe 100644
--- a/make/config/jogl/gl-if-gl2_gl3.cfg
+++ b/make/config/jogl/gl-if-gl2_gl3.cfg
@@ -2,8 +2,8 @@
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL2GL3
-Extends GL2GL3 GLBase
-Extends GL2GL3 GL
+#Extends GL2GL3 GLBase
+#Extends GL2GL3 GL
 Extends GL2GL3 GL2ES2
 
 ExtendedInterfaceSymbolsIgnore ../build-temp/gensrc/classes/javax/media/opengl/GL.java
@@ -27,20 +27,17 @@ NativeOutputDir gensrc/native/jogl
 # Same name but different signature ..
 # No collisions found .. good!
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
 
 # Inform the glue code generator of the association between #defines
 # and functions and the extensions in which they are defined
 GLHeader GL/gl.h
 GLHeader GL/glext.h
 
-# Force all of the methods to be emitted using dynamic linking so we
-# don't need to link against any emulation library on the desktop or
-# depend on the presence of an import library for a particular device
-ForceProcAddressGen __ALL__
-
 # Also force the calling conventions of the locally generated function
 # pointer typedefs for these routines to APIENTRY
 LocalProcAddressCallingConvention __ALL__ APIENTRY
diff --git a/make/config/jogl/gl-if-gl3-ignores.cfg b/make/config/jogl/gl-if-gl3-ignores.cfg
index 672c622..a84f7fb 100644
--- a/make/config/jogl/gl-if-gl3-ignores.cfg
+++ b/make/config/jogl/gl-if-gl3-ignores.cfg
@@ -7,7 +7,7 @@
 # OpenGL 3.x dependencies
 #
 # We allow GL_VERSION_3_0 within GL2
-IgnoreExtension GL_VERSION_3_1
+# IgnoreExtension GL_VERSION_3_1 - contains common tokens
 IgnoreExtension GL_VERSION_3_2
 IgnoreExtension GL_VERSION_3_3
 IgnoreExtension GL_VERSION_3_4
diff --git a/make/config/jogl/gl-if-gl3-subset.cfg b/make/config/jogl/gl-if-gl3-subset.cfg
index 8579789..dae38ec 100644
--- a/make/config/jogl/gl-if-gl3-subset.cfg
+++ b/make/config/jogl/gl-if-gl3-subset.cfg
@@ -10,6 +10,8 @@ Include gl3-desktop.cfg
 Include gl-if-gl3-ignores.cfg
 Include gl-if-gl4-ignores.cfg
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
+ForceProcAddressGen __ALL__
diff --git a/make/config/jogl/gl-if-gl3.cfg b/make/config/jogl/gl-if-gl3.cfg
index fc08ecc..649b351 100644
--- a/make/config/jogl/gl-if-gl3.cfg
+++ b/make/config/jogl/gl-if-gl3.cfg
@@ -10,9 +10,9 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/GLBase.jav
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL3
-Extends GL3 GLBase
-Extends GL3 GL
-Extends GL3 GL2ES2
+#Extends GL3 GLBase
+#Extends GL3 GL
+#Extends GL3 GL2ES2
 Extends GL3 GL2GL3
 ImplPackage jogamp.opengl.gl3
 ImplJavaClass GL3Impl
@@ -25,14 +25,13 @@ Include gl-common-extensions.cfg
 Include gl3-desktop.cfg
 Include gl-if-gl4-ignores.cfg
 
-EmitProcAddressTable false
-
 # Pick up on-line OpenGL javadoc thanks to user cylab on javagaming.org forums
 TagNativeBinding true
 
 Include gl3-headers.cfg
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
-
+ForceProcAddressGen __ALL__
diff --git a/make/config/jogl/gl-if-gl3bc.cfg b/make/config/jogl/gl-if-gl3bc.cfg
index 6765e09..f07a9a4 100644
--- a/make/config/jogl/gl-if-gl3bc.cfg
+++ b/make/config/jogl/gl-if-gl3bc.cfg
@@ -16,11 +16,11 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/fixedfunc/
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL3bc
-Extends GL3bc GLBase
-Extends GL3bc GL
-Extends GL3bc GL2ES1
-Extends GL3bc GL2ES2
-Extends GL3bc GL2GL3
+#Extends GL3bc GLBase
+#Extends GL3bc GL
+#Extends GL3bc GL2ES1
+#Extends GL3bc GL2ES2
+#Extends GL3bc GL2GL3
 Extends GL3bc GL2
 Extends GL3bc GL3
 
@@ -39,7 +39,8 @@ IgnoreExtension GL_EXT_point_parameters
 Include gl-headers.cfg
 Include gl3ext-headers.cfg
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
-
+ForceProcAddressGen __ALL__
diff --git a/make/config/jogl/gl-if-gl4.cfg b/make/config/jogl/gl-if-gl4.cfg
index dbcf633..1e920ac 100644
--- a/make/config/jogl/gl-if-gl4.cfg
+++ b/make/config/jogl/gl-if-gl4.cfg
@@ -11,19 +11,20 @@ ExtendedInterfaceSymbolsIgnore ../src/jogl/classes/javax/media/opengl/GLBase.jav
 Package javax.media.opengl
 Style InterfaceOnly
 JavaClass GL4
-Extends GL4 GLBase
-Extends GL4 GL
-Extends GL4 GL2ES2
-Extends GL4 GL2GL3
+#Extends GL4 GLBase
+#Extends GL4 GL
+#Extends GL4 GL2ES2
+#Extends GL4 GL2GL3
 Extends GL4 GL3
 Include gl-common.cfg
 Include gl-common-extensions.cfg
 Include gl3-desktop.cfg
 
+# dummy procaddress config / force procaddress for comments
 EmitProcAddressTable false
 ProcAddressTableClassName DontGenerateProcAddressTableStuff
 GetProcAddressTableExpr DontGenerateProcAddressTableStuff
-
+ForceProcAddressGen __ALL__
 
 # Pick up on-line OpenGL javadoc thanks to user cylab on javagaming.org forums
 TagNativeBinding true
diff --git a/make/config/jogl/gl-impl-CustomJavaCode-common.java b/make/config/jogl/gl-impl-CustomJavaCode-common.java
index 0878bd2..2c3227e 100644
--- a/make/config/jogl/gl-impl-CustomJavaCode-common.java
+++ b/make/config/jogl/gl-impl-CustomJavaCode-common.java
@@ -35,11 +35,6 @@
       return _context.isExtensionAvailable(glExtensionName);
     }
 
-    public boolean isNPOTTextureAvailable() {
-      return isGL3() || isGLES2() || isExtensionAvailable(GL_ARB_texture_non_power_of_two);
-    }
-    private static final String GL_ARB_texture_non_power_of_two = "GL_ARB_texture_non_power_of_two";
-
     public Object getExtension(String extensionName) {
       // At this point we don't expose any extensions using this mechanism
       return null;
@@ -53,10 +48,16 @@
 
     private GLContextImpl _context;
 
+    /**
+     * @see javax.media.opengl.GLContext#setSwapInterval(int)
+     */
     public void setSwapInterval(int interval) {
       _context.setSwapInterval(interval);
     }
 
+    /**
+     * @see javax.media.opengl.GLContext#getSwapInterval()
+     */
     public int getSwapInterval() {
       return _context.getSwapInterval();
     }
diff --git a/make/config/jogl/gl-impl-CustomJavaCode-desktop.java b/make/config/jogl/gl-impl-CustomJavaCode-desktop.java
index 08b981a..33b0f13 100644
--- a/make/config/jogl/gl-impl-CustomJavaCode-desktop.java
+++ b/make/config/jogl/gl-impl-CustomJavaCode-desktop.java
@@ -120,3 +120,6 @@
         throw new GLException("Not a GLES2 implementation");
     }
 
+    public boolean isNPOTTextureAvailable() {
+      return _context.isNPOTTextureAvailable();
+    }
diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java b/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java
index d83ccd8..dc4f898 100644
--- a/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java
+++ b/make/config/jogl/gl-impl-CustomJavaCode-gl4bc.java
@@ -182,7 +182,7 @@ public boolean glIsPBOUnpackEnabled() {
     return checkUnpackPBOEnabled(false);
 }
 
-private HashMap/*<MemoryObject>*/ arbMemCache = new HashMap();
+private HashMap<MemoryObject, MemoryObject> arbMemCache = new HashMap<MemoryObject, MemoryObject>();
 
 /** Entry point to C language function: <br> <code> LPVOID glMapBuffer(GLenum target, GLenum access); </code>    */
 public java.nio.ByteBuffer glMapBuffer(int target, int access) {
diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gles1.java b/make/config/jogl/gl-impl-CustomJavaCode-gles1.java
index 54bb37c..9b0d98f 100644
--- a/make/config/jogl/gl-impl-CustomJavaCode-gles1.java
+++ b/make/config/jogl/gl-impl-CustomJavaCode-gles1.java
@@ -58,6 +58,10 @@ public final boolean hasGLSL() {
     return false;
 }
 
+public boolean isNPOTTextureAvailable() {
+  return false;
+}
+
 public final GL4bc getGL4bc() throws GLException {
     throw new GLException("Not a GL4bc implementation");
 }
@@ -199,7 +203,7 @@ private boolean checkPackPBOEnabled(boolean throwException) {
     return false;
 }
 
-private HashMap/*<MemoryObject>*/ arbMemCache = new HashMap();
+private HashMap<MemoryObject, MemoryObject> arbMemCache = new HashMap<MemoryObject, MemoryObject>();
 
 /** Entry point to C language function: <br> <code> LPVOID glMapBuffer(GLenum target, GLenum access); </code>    */
 public java.nio.ByteBuffer glMapBuffer(int target, int access) {
diff --git a/make/config/jogl/gl-impl-CustomJavaCode-gles2.java b/make/config/jogl/gl-impl-CustomJavaCode-gles2.java
index b009d93..ea6544d 100644
--- a/make/config/jogl/gl-impl-CustomJavaCode-gles2.java
+++ b/make/config/jogl/gl-impl-CustomJavaCode-gles2.java
@@ -62,6 +62,10 @@ public final boolean hasGLSL() {
     return true;
 }
 
+public boolean isNPOTTextureAvailable() {
+  return true;
+}
+
 public final GL4bc getGL4bc() throws GLException {
     throw new GLException("Not a GL4bc implementation");
 }
@@ -203,7 +207,7 @@ private boolean checkPackPBOEnabled(boolean throwException) {
     return false;
 }
 
-private HashMap/*<MemoryObject>*/ arbMemCache = new HashMap();
+private HashMap<MemoryObject, MemoryObject> arbMemCache = new HashMap<MemoryObject, MemoryObject>();
 
 /** Entry point to C language function: <br> <code> LPVOID glMapBuffer(GLenum target, GLenum access); </code>    */
 public java.nio.ByteBuffer glMapBuffer(int target, int access) {
diff --git a/make/config/jogl/glu-common.cfg b/make/config/jogl/glu-common.cfg
index d2a4802..9271ec3 100644
--- a/make/config/jogl/glu-common.cfg
+++ b/make/config/jogl/glu-common.cfg
@@ -14,6 +14,7 @@ Import javax.media.opengl.glu.*
 Import jogamp.opengl.*
 Import jogamp.opengl.glu.*
 Import jogamp.opengl.glu.tessellator.GLUtessellatorImpl
+Import jogamp.opengl.ProjectFloat
 Import com.jogamp.common.util.ReflectionUtil
 
 # Raise GLException instead of RuntimeException in glue code
diff --git a/make/config/jogl/wgl-win32.cfg b/make/config/jogl/wgl-win32.cfg
index c7adffa..4d2fea5 100644
--- a/make/config/jogl/wgl-win32.cfg
+++ b/make/config/jogl/wgl-win32.cfg
@@ -3,6 +3,8 @@
 JavaOutputDir gensrc/classes
 NativeOutputDir gensrc/native/jogl/Windows
 
+ExtendedInterfaceSymbolsIgnore ../build-temp/gensrc/classes/jogamp/nativewindow/windows/GDI.java
+
 Package jogamp.opengl.windows.wgl
 JavaClass WGL
 Style AllStatic
@@ -21,6 +23,9 @@ EmitProcAddressTable true
 ProcAddressTableClassName WGLProcAddressTable
 GetProcAddressTableExpr wglProcAddressTable
 
+Ignore PIXELFORMATDESCRIPTOR
+
+Import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR
 Import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver
 
 CustomJavaCode WGL private static WGLProcAddressTable wglProcAddressTable = new WGLProcAddressTable(new GLProcAddressResolver());
diff --git a/make/config/nativewindow/jawt-CustomJavaCode.java b/make/config/nativewindow/jawt-CustomJavaCode.java
index d3dc384..6ea57dc 100644
--- a/make/config/nativewindow/jawt-CustomJavaCode.java
+++ b/make/config/nativewindow/jawt-CustomJavaCode.java
@@ -1,38 +1,23 @@
-/** Available and recommended on Mac OS X >= 10.6 Update 4 */
-public static final int JAWT_MACOSX_USE_CALAYER = 0x80000000;
-public static final VersionNumber JAWT_MacOSXCALayerMinVersion = new VersionNumber(10,6,4);
-
 private int jawt_version_cached = 0;
 
 public final int getCachedVersion() {
     return jawt_version_cached;
 }
 
-/** Helper routine for all users to call to access the JAWT. */
-public static JAWT getJAWT(final int jawt_version_flags) {
+protected static boolean getJAWT(final JAWT jawt, final int jawt_version_flags) {
     JAWTUtil.initSingleton();
     // Workaround for 4845371.
     // Make sure the first reference to the JNI GetDirectBufferAddress is done
     // from a privileged context so the VM's internal class lookups will succeed.
-    return AccessController.doPrivileged(new PrivilegedAction<JAWT>() {
-        public JAWT run() {
-          int jawt_version_flags_mod = jawt_version_flags;
-          JAWT jawt = JAWT.create();
-          if( 0 != ( jawt_version_flags_mod & JAWT_MACOSX_USE_CALAYER ) ) {
-              jawt.setVersion(jawt_version_flags_mod);
-              if (JAWTFactory.JAWT_GetAWT(jawt)) {
-                  jawt.jawt_version_cached = jawt.getVersion();
-                  return jawt;
-              }
-              jawt_version_flags_mod &= ~JAWT_MACOSX_USE_CALAYER;
-              System.err.println("MacOSX "+Platform.OS_VERSION_NUMBER+" >= "+JAWT_MacOSXCALayerMinVersion+": Failed to use JAWT_MACOSX_USE_CALAYER");
-          }
-          jawt.setVersion(jawt_version_flags_mod);
-          if (!JAWTFactory.JAWT_GetAWT(jawt)) {
-            throw new RuntimeException("Unable to initialize JAWT: 0x"+Integer.toHexString(jawt_version_flags_mod));
+    return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+        public Boolean run() {
+          jawt.setVersion(jawt_version_flags);
+          if (JAWTFactory.JAWT_GetAWT(jawt)) {
+            jawt.jawt_version_cached = jawt.getVersion();
+            return new Boolean(true);
           }
-          jawt.jawt_version_cached = jawt.getVersion();
-          return jawt;
+          jawt.jawt_version_cached = 0;
+          return new Boolean(false);
         }
-      });
+      }).booleanValue();
 }
diff --git a/make/config/nativewindow/jawt-DrawingSurfaceInfo-CustomJavaCode.java b/make/config/nativewindow/jawt-DrawingSurfaceInfo-CustomJavaCode.java
index 4ff3a45..092aa59 100644
--- a/make/config/nativewindow/jawt-DrawingSurfaceInfo-CustomJavaCode.java
+++ b/make/config/nativewindow/jawt-DrawingSurfaceInfo-CustomJavaCode.java
@@ -13,7 +13,7 @@ private static JAWT_PlatformInfo newPlatformInfo(JAWT jawt, ByteBuffer buf) {
         if (Platform.OS_TYPE == Platform.OSType.WINDOWS) {
           factoryClass = Class.forName("jogamp.nativewindow.jawt.windows.JAWT_Win32DrawingSurfaceInfo");
         } else if (Platform.OS_TYPE == Platform.OSType.MACOS) {
-          if( 0 != ( jawt.getCachedVersion() & JAWT.JAWT_MACOSX_USE_CALAYER ) ) {
+          if( 0 != ( jawt.getCachedVersion() & JAWTUtil.JAWT_MACOSX_USE_CALAYER ) ) {
               factoryClass = Class.forName("jogamp.nativewindow.jawt.macosx.JAWT_SurfaceLayers");
           } else {
               factoryClass = Class.forName("jogamp.nativewindow.jawt.macosx.JAWT_MacOSXDrawingSurfaceInfo");
diff --git a/make/config/nativewindow/x11-CustomJavaCode.java b/make/config/nativewindow/x11-CustomJavaCode.java
index 8ac5575..73439fc 100644
--- a/make/config/nativewindow/x11-CustomJavaCode.java
+++ b/make/config/nativewindow/x11-CustomJavaCode.java
@@ -26,7 +26,7 @@
 
   public static native long DefaultVisualID(long display, int screen);
 
-  public static native long CreateDummyWindow(long display, int screen_index, long visualID, int width, int height);
+  public static native long CreateDummyWindow(long display, int screen_index, int visualID, int width, int height);
   public static native void DestroyDummyWindow(long display, long window);
 
   public static Point GetRelativeLocation(long display, int screen_index, long src_win, long dest_win, int src_x, int src_y) {
diff --git a/make/config/nativewindow/x11-lib.cfg b/make/config/nativewindow/x11-lib.cfg
index 2fe45cf..ed8c13b 100644
--- a/make/config/nativewindow/x11-lib.cfg
+++ b/make/config/nativewindow/x11-lib.cfg
@@ -21,6 +21,7 @@ Opaque long Display *
 Opaque boolean Bool
 Opaque long GLXFBConfig
 Opaque long Visual *
+Opaque long void *
 
 IncludeAs CustomJavaCode X11Lib x11-CustomJavaCode.java
 
@@ -46,4 +47,5 @@ CustomCCode #include <gluegen_stddef.h>
 CustomCCode #include <X11/Xlib.h>
 CustomCCode #include <X11/Xutil.h>
 CustomCCode #include <X11/extensions/Xrender.h>
+CustomCCode #include <XineramaHelper.h>
 
diff --git a/make/resources/android/AndroidManifest-launcher.xml b/make/resources/android/AndroidManifest-launcher.xml
deleted file mode 100644
index dda42b4..0000000
--- a/make/resources/android/AndroidManifest-launcher.xml
+++ /dev/null
@@ -1,130 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-      sharedUserId="com.jogamp.Community" 
-      package="com.jogamp.android.launcher">
-
-    <uses-permission android:name="android.permission.INTERNET" /> <!-- required for NV's perfhud -->
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- required for Android trace -->
-
-    <uses-sdk android:minSdkVersion="9" />
-    <uses-library android:name="com.jogamp.common" android:required="true" />
-    <uses-library android:name="javax.media.opengl" android:required="true" />
-    <uses-library android:name="com.jogamp.opengl.test" android:required="true" />
-
-    <application android:icon="@drawable/icon" 
-                 android:label="@string/app_name"
-                 android:description="@string/app_descr"
-                 android:persistent="false"
-                 >
-
-        <!-- We use activities with ES1 and ES2,
-             also setting the feature tag didn't fix the tegra issue.
-             Leave it here for documentation, maybe later use.
-		<uses-feature android:glEsVersion="0x00020000" />
-           -->
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherRedSquareES1Activity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_redsquarees1_name"
-                  android:description="@string/activity_redsquarees1_descr"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherRedSquareES2Activity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_redsquarees2_name"
-                  android:description="@string/activity_redsquarees2_descr"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherGearsES1Activity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_gearses1_name"
-                  android:description="@string/activity_gearses1_descr"
-                  android:exported="true"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherGearsES2Activity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_gearses2_name"
-                  android:description="@string/activity_gearses2_descr"
-                  android:exported="true"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherGearsES2TransActivity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_gearses2t_name"
-                  android:description="@string/activity_gearses2t_descr"
-                  android:exported="true"
-                  android:theme="@style/Theme.Transparent"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherGraphUI1pActivity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_graphui1p_name"
-                  android:description="@string/activity_graphui1p_descr"
-                  android:exported="true"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherGraphUI2pActivity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_graphui2p_name"
-                  android:description="@string/activity_graphui2p_descr"
-                  android:exported="true"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity android:name="com.jogamp.android.launcher.NEWTLauncherElektronActivity"
-                  android:finishOnTaskLaunch="true"
-                  android:launchMode="standard"
-                  android:configChanges="keyboardHidden|orientation"
-                  android:label="@string/activity_elektro_name"
-                  android:description="@string/activity_elektro_descr"
-                  android:exported="true"
-                  >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-
-</manifest>
diff --git a/make/resources/android/AndroidManifest-test.xml b/make/resources/android/AndroidManifest-test.xml
index 80539cf..4e6a5a2 100644
--- a/make/resources/android/AndroidManifest-test.xml
+++ b/make/resources/android/AndroidManifest-test.xml
@@ -12,6 +12,149 @@
                  android:description="@string/app_descr"
                  android:persistent="false"
                  >
+
+        <activity android:name="com.jogamp.opengl.test.android.NEWTRedSquareES1ActivityLauncher"
+                  android:label="@string/activity_redsquarees1_name"
+                  android:description="@string/activity_redsquarees1_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.NEWTRedSquareES2ActivityLauncher"
+                  android:label="@string/activity_redsquarees2_name"
+                  android:description="@string/activity_redsquarees2_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <activity android:name="com.jogamp.opengl.test.android.NEWTGearsES1ActivityLauncher"
+                  android:label="@string/activity_gearses1_name"
+                  android:description="@string/activity_gearses1_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.NEWTGearsES2ActivityLauncher"
+                  android:label="@string/activity_gearses2_name"
+                  android:description="@string/activity_gearses2_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <activity android:name="com.jogamp.opengl.test.android.NEWTGearsES2TransActivityLauncher"
+                  android:label="@string/activity_gearses2t_name"
+                  android:description="@string/activity_gearses2t_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.NEWTGraphUI1pActivityLauncher"
+                  android:label="@string/activity_graphui1p_name"
+                  android:description="@string/activity_graphui1p_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.NEWTGraphUI2pActivityLauncher"
+                  android:label="@string/activity_graphui2p_name"
+                  android:description="@string/activity_graphui2p_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.NEWTElektronActivityLauncher"
+                  android:label="@string/activity_elektro_name"
+                  android:description="@string/activity_elektro_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieSimpleActivityLauncher00a"
+                  android:label="@string/activity_moviesimple0a_name"
+                  android:description="@string/activity_moviesimple_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieSimpleActivityLauncher00b"
+                  android:label="@string/activity_moviesimple0b_name"
+                  android:description="@string/activity_moviesimple_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieSimpleActivityLauncher01a"
+                  android:label="@string/activity_moviesimple1a_name"
+                  android:description="@string/activity_moviesimple_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieSimpleActivityLauncher01b"
+                  android:label="@string/activity_moviesimple1b_name"
+                  android:description="@string/activity_moviesimple_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieSimpleActivityLauncher02"
+                  android:label="@string/activity_moviesimple2_name"
+                  android:description="@string/activity_moviesimple_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name="com.jogamp.opengl.test.android.MovieCubeActivityLauncher0"
+                  android:label="@string/activity_moviecube0_name"
+                  android:description="@string/activity_moviecube_descr"
+                  android:theme="@android:style/Theme.NoDisplay"
+                  >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
     </application>
 
 </manifest>
diff --git a/make/resources/android/res-launcher/values/colors.xml b/make/resources/android/res-jogl/values/colors.xml
similarity index 100%
rename from make/resources/android/res-launcher/values/colors.xml
rename to make/resources/android/res-jogl/values/colors.xml
diff --git a/make/resources/android/res-launcher/values/styles.xml b/make/resources/android/res-jogl/values/styles.xml
similarity index 100%
rename from make/resources/android/res-launcher/values/styles.xml
rename to make/resources/android/res-jogl/values/styles.xml
diff --git a/make/resources/android/res-launcher/drawable-hdpi/icon.png b/make/resources/android/res-test/drawable-hdpi/icon.png
similarity index 100%
rename from make/resources/android/res-launcher/drawable-hdpi/icon.png
rename to make/resources/android/res-test/drawable-hdpi/icon.png
diff --git a/make/resources/android/res-launcher/drawable-ldpi/icon.png b/make/resources/android/res-test/drawable-ldpi/icon.png
similarity index 100%
rename from make/resources/android/res-launcher/drawable-ldpi/icon.png
rename to make/resources/android/res-test/drawable-ldpi/icon.png
diff --git a/make/resources/android/res-launcher/drawable-mdpi/icon.png b/make/resources/android/res-test/drawable-mdpi/icon.png
similarity index 100%
rename from make/resources/android/res-launcher/drawable-mdpi/icon.png
rename to make/resources/android/res-test/drawable-mdpi/icon.png
diff --git a/make/resources/android/res-launcher/layout/main.xml b/make/resources/android/res-test/layout/main.xml
similarity index 100%
rename from make/resources/android/res-launcher/layout/main.xml
rename to make/resources/android/res-test/layout/main.xml
diff --git a/make/resources/android/res-launcher/values/strings.xml b/make/resources/android/res-test/values/strings.xml
similarity index 60%
rename from make/resources/android/res-launcher/values/strings.xml
rename to make/resources/android/res-test/values/strings.xml
index 8b6928d..fcaf102 100644
--- a/make/resources/android/res-launcher/values/strings.xml
+++ b/make/resources/android/res-test/values/strings.xml
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
-    <string name="hello">Jogl Launcher</string>
-    <string name="app_name">JogAmp\'s Jogl Launcher</string>
-    <string name="app_descr">Launches Jogl Applications.</string>
+    <string name="hello">Jogl Tests</string>
+    <string name="app_name">Jogl Tests</string>
+    <string name="app_descr">Launches Jogl Tests.</string>
     <string name="activity_redsquarees1_name">RedSqrES1</string>
     <string name="activity_redsquarees1_descr">RedSquareES1</string>
     <string name="activity_redsquarees2_name">RedSqrES2</string>
@@ -19,4 +19,12 @@
     <string name="activity_graphui2p_descr">GraphUI 2-pass</string>
     <string name="activity_elektro_name">Elektro</string>
     <string name="activity_elektro_descr">Elektro</string>
+    <string name="activity_moviesimple0a_name">MovieSimple0a</string>
+    <string name="activity_moviesimple0b_name">MovieSimple0b</string>
+    <string name="activity_moviesimple1a_name">MovieSimple1a</string>
+    <string name="activity_moviesimple1b_name">MovieSimple1b</string>
+    <string name="activity_moviesimple2_name">MovieSimple2</string>
+    <string name="activity_moviesimple_descr">MovieSimple</string>
+    <string name="activity_moviecube0_name">MovieCube0</string>
+    <string name="activity_moviecube_descr">MovieCube</string>
 </resources>
diff --git a/make/resources/assets-test/placeholder.txt b/make/resources/assets-test/placeholder.txt
new file mode 100644
index 0000000..efb91aa
--- /dev/null
+++ b/make/resources/assets-test/placeholder.txt
@@ -0,0 +1 @@
+placeholder for git - can be removed when containing real assets for tests
diff --git a/make/resources/assets/jogl/util/data/av/test-ntsc01-160x90.png b/make/resources/assets/jogl/util/data/av/test-ntsc01-160x90.png
new file mode 100644
index 0000000..3df4743
Binary files /dev/null and b/make/resources/assets/jogl/util/data/av/test-ntsc01-160x90.png differ
diff --git a/make/scripts/adb-install-all.sh b/make/scripts/adb-install-all-armv7.sh
similarity index 70%
rename from make/scripts/adb-install-all.sh
rename to make/scripts/adb-install-all-armv7.sh
index d48d0ab..503c6f2 100755
--- a/make/scripts/adb-install-all.sh
+++ b/make/scripts/adb-install-all-armv7.sh
@@ -1,4 +1,4 @@
+adb $* install ../../gluegen/build-android-armv7/jogamp.android-launcher.apk
 adb $* install ../../gluegen/build-android-armv7/gluegen-rt.apk
 adb $* install ../build-android-armv7/jar/jogl.all-android.apk
-adb $* install ../build-android-armv7/jar/jogl.android-launcher.apk
 adb $* install ../build-android-armv7/jar/jogl.test.apk
diff --git a/make/scripts/adb-launch-activity.sh b/make/scripts/adb-launch-activity.sh
new file mode 100644
index 0000000..8439952
--- /dev/null
+++ b/make/scripts/adb-launch-activity.sh
@@ -0,0 +1,11 @@
+#! /bin/sh
+
+#ANAME="com.jogamp.opengl.test/com.jogamp.opengl.test.android.NEWTGenericActivity"
+#ANAME="com.jogamp.android.launcher/com.jogamp.android.launcher.NEWTLauncherActivity2"
+ANAME="com.jogamp.opengl.test/com.jogamp.opengl.test.android.NEWTGearsES2ActivityLauncher"
+
+adb $* shell "setprop log.redirect-stdio true ; setprop log.redirect-stderr true ; \
+              am start -a android.intent.action.MAIN -n $ANAME"
+
+
+
diff --git a/make/scripts/adb-launch-main.sh b/make/scripts/adb-launch-main.sh
new file mode 100644
index 0000000..7e32165
--- /dev/null
+++ b/make/scripts/adb-launch-main.sh
@@ -0,0 +1,69 @@
+#! /bin/bash
+
+export HOST_UID=jogamp
+# jogamp02 - 10.1.0.122
+export HOST_IP=10.1.0.122
+export HOST_RSYNC_ROOT=PROJECTS/JOGL
+
+export TARGET_UID=jogamp
+export TARGET_IP=panda02
+export TARGET_ADB_PORT=5555
+export TARGET_ROOT=/data/projects
+
+export BUILD_DIR=../build-android-armv7
+
+if [ -e /opt-linux-x86/android-sdk-linux_x86 ] ; then
+    export ANDROID_SDK_HOME=/opt-linux-x86/android-sdk-linux_x86
+    export PATH=$ANDROID_SDK_HOME/platform-tools:$PATH
+fi 
+
+TSTCLASS=jogamp.android.launcher.LauncherUtil
+#TSTCLASS=com.jogamp.opengl.test.android.LauncherUtil
+#TSTCLASS=com.jogamp.android.launcher.NEWTLauncherMain
+#TSTCLASS=com.jogamp.nativewindow.NativeWindowVersion
+#TSTCLASS=com.jogamp.opengl.JoglVersion
+#TSTCLASS=com.jogamp.newt.NewtVersion
+#TSTCLASS=com.jogamp.newt.opengl.GLWindow
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01
+#TSTCLASS=com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo01
+#TSTCLASS=com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo02
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.gl2es1.gears.newt.TestGearsGL2ES1NEWT
+
+LOGFILE=`basename $0 .sh`.log
+
+RSYNC_EXCLUDES="--delete-excluded \
+                --exclude 'build-x86*/' --exclude 'build-linux*/' --exclude 'build-win*/' --exclude 'build-mac*/' \
+                --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \
+                --exclude 'gensrc/' --exclude 'doc/' --exclude 'jnlp-files' --exclude 'archive/' \
+                --exclude 'android-sdk/' --exclude 'resources/' --exclude 'scripts/' \
+                --exclude 'stub_includes/' --exclude 'nbproject/' --exclude '*.log' --exclude '*.zip' --exclude '*.7z'"
+
+echo "#! /system/bin/sh" > $BUILD_DIR/jogl-targetcommand.sh
+
+echo "\
+rsync -av --delete --delete-after $RSYNC_EXCLUDES \
+   $HOST_UID@$HOST_IP::$HOST_RSYNC_ROOT/gluegen \
+   $HOST_UID@$HOST_IP::$HOST_RSYNC_ROOT/jogl \
+   $TARGET_ROOT ; \
+cd $TARGET_ROOT/jogl/make ;
+export LD_LIBRARY_PATH=/system/lib:$TARGET_ROOT/gluegen/make/$BUILD_DIR/obj:$TARGET_ROOT/jogl/make/$BUILD_DIR/lib ; \
+# export BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar 
+dalvikvm \
+  -Xjnigreflimit:2000 \
+  -cp ../../gluegen/make/$BUILD_DIR/jogamp.android-launcher.apk:../../gluegen/make/lib/ant-junit-all.apk:../../gluegen/make/$BUILD_DIR/gluegen-rt.apk:$BUILD_DIR/jar/jogl.all-android.apk:$BUILD_DIR/jar/jogl.test.apk:$BUILD_DIR/jar/jogl.android-launcher.apk \
+  -Dgluegen.root=../../gluegen \
+  -Drootrel.build=build-android-armv7 \
+  com.android.internal.util.WithFramework \
+  $TSTCLASS \
+" >> $BUILD_DIR/jogl-targetcommand.sh
+
+chmod ugo+x $BUILD_DIR/jogl-targetcommand.sh
+adb connect $TARGET_IP:$TARGET_ADB_PORT
+adb -s $TARGET_IP:$TARGET_ADB_PORT push $BUILD_DIR/jogl-targetcommand.sh $TARGET_ROOT/jogl-targetcommand.sh
+adb -s $TARGET_IP:$TARGET_ADB_PORT shell su -c $TARGET_ROOT/jogl-targetcommand.sh 2>&1 | tee $LOGFILE
+
+
diff --git a/make/scripts/adb-power-alwayson.sh b/make/scripts/adb-power-alwayson.sh
new file mode 100755
index 0000000..ec04064
--- /dev/null
+++ b/make/scripts/adb-power-alwayson.sh
@@ -0,0 +1,3 @@
+sdir=`dirname $0`
+
+adb $* shell svc power stayon true
diff --git a/make/scripts/adb-reinstall-all.sh b/make/scripts/adb-reinstall-all-armv7.sh
similarity index 59%
rename from make/scripts/adb-reinstall-all.sh
rename to make/scripts/adb-reinstall-all-armv7.sh
index f450a29..2cb7713 100755
--- a/make/scripts/adb-reinstall-all.sh
+++ b/make/scripts/adb-reinstall-all-armv7.sh
@@ -1,5 +1,5 @@
 sdir=`dirname $0`
 
 $sdir/adb-uninstall-all.sh $*
-$sdir/adb-install-all.sh $*
+$sdir/adb-install-all-armv7.sh $*
 
diff --git a/make/scripts/adb-uninstall-all.sh b/make/scripts/adb-uninstall-all.sh
index 3e65e12..1605a0e 100755
--- a/make/scripts/adb-uninstall-all.sh
+++ b/make/scripts/adb-uninstall-all.sh
@@ -1,4 +1,4 @@
+adb $* uninstall jogamp.android.launcher
 adb $* uninstall com.jogamp.common
 adb $* uninstall javax.media.opengl
-adb $* uninstall com.jogamp.android.launcher
 adb $* uninstall com.jogamp.opengl.test
diff --git a/make/scripts/check-java-major-version.sh b/make/scripts/check-java-major-version.sh
new file mode 100755
index 0000000..08e3bc7
--- /dev/null
+++ b/make/scripts/check-java-major-version.sh
@@ -0,0 +1,27 @@
+#! /bin/bash
+
+TDIR=`pwd`
+
+function dump_version() {
+    echo -n "$1: "
+    javap -v $1 | grep 'major version'
+}
+
+function dump_versions() {
+    cd $1
+    #dump_version jogamp.common.Debug
+    for i in `find . -name '*.class'` ; do 
+      dump_version `echo $i | sed -e 's/\//./g' -e 's/\.class//g'`
+    done
+    cd $TDIR
+}
+
+function do_it() {
+    dump_versions $1/nativewindow/classes
+    dump_versions $1/jogl/classes
+    dump_versions $1/newt/classes
+    dump_versions $1/test/build/classes
+}
+
+do_it $1 2>&1 | tee check-java-major-version.log
+
diff --git a/make/scripts/crosstest-java-android-armv7-rel.sh b/make/scripts/crosstest-java-android-armv7-rel.sh
deleted file mode 100644
index 8d9ae27..0000000
--- a/make/scripts/crosstest-java-android-armv7-rel.sh
+++ /dev/null
@@ -1,69 +0,0 @@
-#! /bin/bash
-
-export HOST_UID=sven
-export HOST_IP=192.168.0.52
-export HOST_RSYNC_ROOT=PROJECTS/JOGL
-
-export TARGET_UID=jogamp
-export TARGET_IP=beagle02
-export TARGET_ROOT=/projects
-
-export BUILD_DIR=../build-android-armv7
-
-if [ -e /opt-linux-x86/android-sdk-linux_x86 ] ; then
-    export ANDROID_SDK_HOME=/opt-linux-x86/android-sdk-linux_x86
-    export PATH=$ANDROID_SDK_HOME/platform-tools:$PATH
-fi 
-
-#
-# orig android:
-#   export LD_LIBRARY_PATH /system/lib
-#   export BOOTCLASSPATH /system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar
-#
-
-#TSTCLASS=com.jogamp.nativewindow.NativeWindowVersion
-#TSTCLASS=com.jogamp.opengl.JoglVersion
-#TSTCLASS=com.jogamp.newt.NewtVersion
-TSTCLASS=com.jogamp.newt.opengl.GLWindow
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState01NEWT
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01
-#TSTCLASS=com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo01
-#TSTCLASS=com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo02
-#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.gl2es1.gears.newt.TestGearsGL2ES1NEWT
-
-
-LOGFILE=`basename $0 .sh`.log
-
-#  -Djava.class.path=lib/junit.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-junit.jar:$BUILD_DIR/gluegen.jar:$BUILD_DIR/test/build/gluegen-test.jar \
-#  -Djava.class.path=lib/ant-junit-all.apk:$BUILD_DIR/gluegen-rt.apk \
-#  -Djava.library.path=/system/lib:$TARGET_ROOT/gluegen/make/$BUILD_DIR/obj:$BUILD_DIR/test/build/natives \
-
-RSYNC_EXCLUDES="--exclude 'build-x86*/' --exclude 'build-linux*/' --exclude 'build-win*/' --exclude 'build-mac*/' \
-                --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude 'jogl-java-src.zip' \
-                --delete-excluded"
-
-echo "#! /system/bin/sh" > $BUILD_DIR/targetcommand.sh
-
-echo "\
-rsync -av --delete --delete-after $RSYNC_EXCLUDES $HOST_UID@$HOST_IP::$HOST_RSYNC_ROOT/gluegen $HOST_UID@$HOST_IP::$HOST_RSYNC_ROOT/jogl $TARGET_ROOT ; \
-cd $TARGET_ROOT/jogl/make ;
-export LD_LIBRARY_PATH=/system/lib:$TARGET_ROOT/gluegen/make/$BUILD_DIR/obj:$TARGET_ROOT/jogl/make/$BUILD_DIR/lib ; \
-export BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar ; \
-dalvikvm \
-  -Xjnigreflimit:2000 \
-  -cp ../../gluegen/make/lib/ant-junit-all.apk:../../gluegen/make/$BUILD_DIR/gluegen-rt.apk:$BUILD_DIR/jar/jogl.all-android.apk:$BUILD_DIR/jar/jogl.test.jar \
-  -Djogamp.debug.JNILibLoader=true \
-  -Djogamp.debug.NativeLibrary=true \
-  -Djogamp.debug.NativeLibrary.Lookup=true \
-  -Djogl.debug=all \
-  com.android.internal.util.WithFramework \
-  $TSTCLASS \
-" >> $BUILD_DIR/targetcommand.sh
-
-chmod ugo+x $BUILD_DIR/targetcommand.sh
-adb push $BUILD_DIR/targetcommand.sh $TARGET_ROOT/targetcommand.sh
-adb shell $TARGET_ROOT/targetcommand.sh 2>&1 | tee $LOGFILE
-
diff --git a/make/scripts/crosstest-launch-android-activity.sh b/make/scripts/crosstest-launch-android-activity.sh
deleted file mode 100644
index c67cbfa..0000000
--- a/make/scripts/crosstest-launch-android-activity.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#! /bin/sh
-
-#adb uninstall com.jogamp.common
-#adb install ../../gluegen/build-android-armv7/gluegen-rt.apk
-
-adb uninstall javax.media.opengl
-adb install ../build-android-armv7/jar/jogl.all-android.apk 
-
-adb shell "setprop log.redirect-stdio true ; setprop log.redirect-stderr true ; \
-           am start -a android.intent.action.MAIN -n javax.media.opengl/jogamp.newt.driver.android.NewtVersionActivity"
-
-#adb uninstall com.jogamp.android.launcher
-#adb install ../build-android-armv7/android/jar/jogllauncher.apk 
-
-#adb shell "setprop log.redirect-stdio true ; setprop log.redirect-stderr true ; \
-#           am start -a android.intent.action.MAIN -n com.jogamp.android.launcher/com.jogamp.android.launcher.NEWTLauncherVersionActivity"
-
diff --git a/make/scripts/gluegen-gl.sh b/make/scripts/gluegen-gl.sh
new file mode 100644
index 0000000..111b707
--- /dev/null
+++ b/make/scripts/gluegen-gl.sh
@@ -0,0 +1,93 @@
+#! /bin/bash
+
+rootrel=build-x86_64
+
+builddir=../$rootrel
+buildtmp=../build-temp
+
+function copy_temp() {
+    mkdir -p $buildtmp/gensrc/classes
+    cp -a $builddir/jogl/gensrc/classes/* $buildtmp/gensrc/classes/
+}
+
+function gluegen_if_gl() {
+java \
+-classpath \
+../../gluegen/$rootrel/gluegen.jar:../$rootrel/jogl/gluegen-gl.jar \
+com.jogamp.gluegen.GlueGen \
+--debug \
+--dumpCPP \
+-O../$rootrel/jogl \
+-Ecom.jogamp.gluegen.opengl.GLEmitter \
+-C./config/jogl/gl-if-gl.cfg \
+-Istub_includes/jni \
+-Istub_includes/jni/macosx \
+-Istub_includes/jni/win32 \
+-Istub_includes/jni/x11 \
+-Istub_includes/khr \
+-Istub_includes/khr/KD \
+-Istub_includes/khr/KHR \
+-Istub_includes/macosx \
+-Istub_includes/macosx/AppKit \
+-Istub_includes/macosx/OpenGL \
+-Istub_includes/macosx/QuartzCore \
+-Istub_includes/opengl \
+-Istub_includes/opengl/GL \
+-Istub_includes/opengl/GL3 \
+-Istub_includes/opengl/GLES \
+-Istub_includes/opengl/GLES2 \
+-Istub_includes/win32 \
+-Istub_includes/x11 \
+-Istub_includes/x11/X11 \
+-Istub_includes/x11/X11/extensions \
+-I../../gluegen/make/stub_includes/gluegen \
+stub_includes/opengl/gles2.c \
+
+copy_temp
+
+}
+
+function gluegen_es2() {
+java \
+-classpath \
+../../gluegen/$rootrel/gluegen.jar:../$rootrel/jogl/gluegen-gl.jar \
+com.jogamp.gluegen.GlueGen \
+--debug \
+--dumpCPP \
+-O../$rootrel/jogl \
+-Ecom.jogamp.gluegen.opengl.GLEmitter \
+-C./config/jogl/gl-es2.cfg \
+-Istub_includes/jni \
+-Istub_includes/jni/macosx \
+-Istub_includes/jni/win32 \
+-Istub_includes/jni/x11 \
+-Istub_includes/khr \
+-Istub_includes/khr/KD \
+-Istub_includes/khr/KHR \
+-Istub_includes/macosx \
+-Istub_includes/macosx/AppKit \
+-Istub_includes/macosx/OpenGL \
+-Istub_includes/macosx/QuartzCore \
+-Istub_includes/opengl \
+-Istub_includes/opengl/GL \
+-Istub_includes/opengl/GL3 \
+-Istub_includes/opengl/GLES \
+-Istub_includes/opengl/GLES2 \
+-Istub_includes/win32 \
+-Istub_includes/x11 \
+-Istub_includes/x11/X11 \
+-Istub_includes/x11/X11/extensions \
+-I../../gluegen/make/stub_includes/gluegen \
+stub_includes/opengl/gles2.c \
+
+copy_temp
+
+}
+
+function gluegen_all() {
+    gluegen_if_gl
+#   gluegen_es2
+}
+
+gluegen_all 2>&1 | tee $(basename $0 .sh).log
+
diff --git a/make/scripts/java-win32-dbg.bat b/make/scripts/java-win32-dbg.bat
index 909a51c..9ad090a 100755
--- a/make/scripts/java-win32-dbg.bat
+++ b/make/scripts/java-win32-dbg.bat
@@ -1,24 +1,34 @@
 
 set BLD_SUB=build-win32
-set J2RE_HOME=c:\jre1.6.0_29_x32
-set JAVA_HOME=c:\jdk1.6.0_29_x32
+set J2RE_HOME=c:\jre1.6.0_30_x32
+set JAVA_HOME=c:\jdk1.6.0_30_x32
 set ANT_PATH=C:\apache-ant-1.8.2
 
-set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
-
+set PROJECT_ROOT=D:\projects\jogamp\jogl
 set BLD_DIR=..\%BLD_SUB%
-set LIB_DIR=..\..\gluegen\%BLD_SUB%\obj;%BLD_DIR%\lib
+
+set FFMPEG_LIB=%PROJECT_ROOT%\make\lib\ffmpeg\x32
+
+set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%FFMPEG_LIB%;%PATH%
+REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\angle\win32;%PATH%
+REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH%
+
+REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj
+set LIB_DIR=%FFMPEG_LIB%
 
 set CP_ALL=.;%BLD_DIR%\jar\jogl.all.jar;%BLD_DIR%\jar\jogl.test.jar;..\..\gluegen\%BLD_SUB%\gluegen-rt.jar;..\..\gluegen\make\lib\junit.jar;%ANT_PATH%\lib\ant.jar;%ANT_PATH%\lib\ant-junit.jar;%BLD_DIR%\..\make\lib\swt\win32-win32-x86\swt-debug.jar
 
 echo CP_ALL %CP_ALL%
 
+set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer"
+REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true"
+REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true"
 REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true"
 REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all"
 REM set D_ARGS="-Dnewt.debug.Window" "-Dnativewindow.debug.TraceLock"
 REM set D_ARGS="-Dnativewindow.debug.TraceLock"
 REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display"
-set D_ARGS="-Djogl.debug=all"
+REM set D_ARGS="-Djogl.debug=all"
 REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL"
 REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL" "-Djogl.debug=all"
 REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.test.Window.reparent.incompatible=true"
@@ -26,5 +36,5 @@ REM set D_ARGS="-Xcheck:jni" "-Xint" "-verbose:jni"
 
 set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true"
 
-%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %D_ARGS% %X_ARGS% %1 %2 %3 %4 %5 %6 %7 %8 %9 > java-win32-dbg.log 2>&1
+%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %D_ARGS% %X_ARGS% %* > java-win32-dbg.log 2>&1
 
diff --git a/make/scripts/java-win32.bat b/make/scripts/java-win32.bat
index 536c3f2..6dc0f3c 100755
--- a/make/scripts/java-win32.bat
+++ b/make/scripts/java-win32.bat
@@ -1,16 +1,22 @@
 
 set BLD_SUB=build-win32
-set J2RE_HOME=c:\jre1.6.0_29_x32
-set JAVA_HOME=c:\jdk1.6.0_29_x32
+set J2RE_HOME=c:\jre1.6.0_30_x32
+set JAVA_HOME=c:\jdk1.6.0_30_x32
 set ANT_PATH=C:\apache-ant-1.8.2
 
-set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
+set PROJECT_ROOT=D:\projects\jogamp\jogl
+set BLD_DIR=..\%BLD_SUB%
+
+REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
+set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\angle\win32;%PATH%
+REM set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%PROJECT_ROOT%\make\lib\PVRVFrame\OGLES-2.0\Windows_x86_32;%PATH%
 
 set BLD_DIR=..\%BLD_SUB%
-set LIB_DIR=..\..\gluegen\%BLD_SUB%\obj;%BLD_DIR%\lib
+REM set LIB_DIR=..\..\gluegen\%BLD_SUB%\obj;%BLD_DIR%\lib
+set LIB_DIR=
 
 set CP_ALL=.;%BLD_DIR%\jar\jogl.all.jar;%BLD_DIR%\jar\jogl.test.jar;..\..\gluegen\%BLD_SUB%\gluegen-rt.jar;..\..\gluegen\make\lib\junit.jar;%ANT_PATH%\lib\ant.jar;%ANT_PATH%\lib\ant-junit.jar;%BLD_DIR%\..\make\lib\swt\win32-win32-x86\swt-debug.jar
 
 echo CP_ALL %CP_ALL%
 
-%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" "-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true" %1 %2 %3 %4 %5 %6 %7 %8 %9 > java-win32.log 2>&1
+%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" "-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true" %* > java-win32.log 2>&1
diff --git a/make/scripts/java-win64-dbg.bat b/make/scripts/java-win64-dbg.bat
index a195d72..4b88116 100755
--- a/make/scripts/java-win64-dbg.bat
+++ b/make/scripts/java-win64-dbg.bat
@@ -1,26 +1,36 @@
 
 set BLD_SUB=build-win64
-set J2RE_HOME=c:\jre1.6.0_29_x64
-set JAVA_HOME=c:\jdk1.6.0_29_x64
+set J2RE_HOME=c:\jre1.6.0_30_x64
+set JAVA_HOME=c:\jdk1.6.0_30_x64
 set ANT_PATH=C:\apache-ant-1.8.2
 
-set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
-
+set PROJECT_ROOT=D:\projects\jogamp\jogl
 set BLD_DIR=..\%BLD_SUB%
-set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj
+
+set FFMPEG_LIB=%PROJECT_ROOT%\make\lib\ffmpeg\x64
+
+set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;%FFMPEG_LIB%;%PATH%
+REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj
+set LIB_DIR=%FFMPEG_LIB%
 
 set CP_ALL=.;%BLD_DIR%\jar\jogl.all.jar;%BLD_DIR%\jar\jogl.test.jar;..\..\gluegen\%BLD_SUB%\gluegen-rt.jar;..\..\gluegen\make\lib\junit.jar;%ANT_PATH%\lib\ant.jar;%ANT_PATH%\lib\ant-junit.jar;%BLD_DIR%\..\make\lib\swt\win32-win32-x86_64\swt-debug.jar
 
 echo CP_ALL %CP_ALL%
 
+set D_ARGS="-Djogamp.debug.IOUtil" "-Djogl.debug.GLSLCode" "-Djogl.debug.GLMediaPlayer"
+REM set D_ARGS="-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLSLCode"
 REM set D_ARGS="-Djogl.debug.ExtensionAvailabilityCache" "-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.ProcAddressHelper=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true"
+REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.NativeLibrary=true"
 REM set D_ARGS="-Djogl.debug.GLContext" "-Djogl.debug.ExtensionAvailabilityCache" "-Djogamp.debug.ProcAddressHelper=true"
 REM set D_ARGS="-Djogl.debug.GraphicsConfiguration"
 REM set D_ARGS="-Djogamp.debug.JNILibLoader=true" "-Djogamp.debug.NativeLibrary=true" "-Djogamp.debug.NativeLibrary.Lookup=true" "-Djogl.debug.GLProfile=true"
 REM set D_ARGS="-Djogl.debug=all" "-Dnewt.debug=all" "-Dnativewindow.debug=all" "-Djogamp.debug.Lock" "-Djogamp.debug.Lock.TraceLock"
 REM set D_ARGS="-Djogl.debug=all" "-Dnativewindow.debug=all"
 REM set D_ARGS="-Djogl.debug=all"
-set D_ARGS="-Dnewt.debug.Window"
+REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL"
+REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch" "-Djogl.windows.useWGLVersionOf5WGLGDIFuncSet"
+REM set D_ARGS="-Djogl.debug.GLCanvas" "-Djogl.debug.Animator" "-Djogl.debug.GLContext" "-Djogl.debug.GLContext.TraceSwitch"
+REM set D_ARGS="-Dnewt.debug.Window"
 REM set D_ARGS="-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.DebugGL" "-Djogl.debug.TraceGL"
 REM set D_ARGS="-Djogl.debug.DebugGL" "-Djogl.debug.GLDebugMessageHandler" "-Djogl.debug.GLSLCode"
 REM set D_ARGS="-Djogl.debug.GraphicsConfiguration" "-Djogl.debug.CapabilitiesChooser"
@@ -31,6 +41,8 @@ REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.debug.EDT" "
 REM set D_ARGS="-Dnewt.debug.Screen" "-Dnewt.debug.EDT" "-Dnativewindow.debug=all"
 REM set D_ARGS="-Dnewt.debug.Window" "-Dnewt.debug.Display" "-Dnewt.test.Window.reparent.incompatible=true"
 
-set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true"
+REM set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.java2d.opengl=true" "-Dsun.awt.noerasebackground=true"
+REM set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.java2d.d3d=false" "-Dsun.java2d.ddoffscreen=false" "-Dsun.java2d.gdiblit=false" "-Dsun.java2d.opengl=false" "-Dsun.awt.noerasebackground=true" "-Xms512m" "-Xmx1024m"
+REM set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.java2d.d3d=false" "-Dsun.java2d.ddoffscreen=false" "-Dsun.java2d.gdiblit=false" "-Dsun.java2d.opengl=true" "-Dsun.awt.noerasebackground=true" "-Xms512m" "-Xmx1024m"
 
-%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %D_ARGS% %X_ARGS% %1 %2 %3 %4 %5 %6 %7 %8 %9 > java-win64-dbg.log 2>&1
+%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %D_ARGS% %X_ARGS% %* > java-win64-dbg.log 2>&1
diff --git a/make/scripts/java-win64.bat b/make/scripts/java-win64.bat
index d7d3b6a..ba4fdb1 100755
--- a/make/scripts/java-win64.bat
+++ b/make/scripts/java-win64.bat
@@ -1,17 +1,18 @@
 
 set BLD_SUB=build-win64
-set J2RE_HOME=c:\jre1.6.0_29_x64
-set JAVA_HOME=c:\jdk1.6.0_29_x64
+set J2RE_HOME=c:\jre1.6.0_30_x64
+set JAVA_HOME=c:\jdk1.6.0_30_x64
 set ANT_PATH=C:\apache-ant-1.8.2
 
 set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
 
 set BLD_DIR=..\%BLD_SUB%
-set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj
+REM set LIB_DIR=%BLD_DIR%\lib;..\..\gluegen\%BLD_SUB%\obj
+set LIB_DIR=
 
 set CP_ALL=.;%BLD_DIR%\jar\jogl.all.jar;%BLD_DIR%\jar\jogl.test.jar;..\..\gluegen\%BLD_SUB%\gluegen-rt.jar;..\..\gluegen\make\lib\junit.jar;%ANT_PATH%\lib\ant.jar;%ANT_PATH%\lib\ant-junit.jar;%BLD_DIR%\..\make\lib\swt\win32-win32-x86_64\swt-debug.jar
 echo CP_ALL %CP_ALL%
 
 set X_ARGS="-Dsun.java2d.noddraw=true" "-Dsun.awt.noerasebackground=true"
 
-%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %X_ARGS% %1 %2 %3 %4 %5 %6 %7 %8 %9 > java-win64.log 2>&1
+%J2RE_HOME%\bin\java -classpath %CP_ALL% "-Djava.library.path=%LIB_DIR%" %X_ARGS% %* > java-win64.log 2>&1
diff --git a/make/scripts/make.jogl.all.android-armv7-cross.sh b/make/scripts/make.jogl.all.android-armv7-cross.sh
index 37a5c4c..4c4ea4c 100755
--- a/make/scripts/make.jogl.all.android-armv7-cross.sh
+++ b/make/scripts/make.jogl.all.android-armv7-cross.sh
@@ -1,26 +1,43 @@
 #! /bin/sh
 
-export HOST_UID=sven
-export HOST_IP=192.168.0.52
+export NODE_LABEL=.
+
+export HOST_UID=jogamp
+# jogamp02 - 10.1.0.122
+export HOST_IP=10.1.0.122
 export HOST_RSYNC_ROOT=PROJECTS/JOGL
 
 export TARGET_UID=jogamp
-export TARGET_IP=beagle01
-export TARGET_ROOT=/projects
+export TARGET_IP=panda02
+#export TARGET_IP=jautab03
+#export TARGET_IP=jauphone04
+export TARGET_ADB_PORT=5555
+# needs executable bit (probably su)
+export TARGET_ROOT=/data/projects
 export TARGET_ANT_HOME=/usr/share/ant
 
-export ANDROID_VERSION=9
-
 echo ANDROID_SDK_HOME $ANDROID_SDK_HOME
 echo NDK_ROOT $NDK_ROOT
 
 if [ -z "$NDK_ROOT" ] ; then
-    if [ -e /usr/local/android-ndk-r6 ] ; then
-        NDK_ROOT=/usr/local/android-ndk-r6
-    elif [ -e /opt-linux-x86/android-ndk-r6 ] ; then
-        NDK_ROOT=/opt-linux-x86/android-ndk-r6
-    elif [ -e /opt/android-ndk-r6 ] ; then
-        NDK_ROOT=/opt/android-ndk-r6
+    #
+    # Generic android-ndk
+    #
+    if [ -e /usr/local/android-ndk ] ; then
+        NDK_ROOT=/usr/local/android-ndk
+    elif [ -e /opt-linux-x86/android-ndk ] ; then
+        NDK_ROOT=/opt-linux-x86/android-ndk
+    elif [ -e /opt/android-ndk ] ; then
+        NDK_ROOT=/opt/android-ndk
+    #
+    # Specific android-ndk-r7b
+    #
+    elif [ -e /usr/local/android-ndk-r7b ] ; then
+        NDK_ROOT=/usr/local/android-ndk-r7b
+    elif [ -e /opt-linux-x86/android-ndk-r7b ] ; then
+        NDK_ROOT=/opt-linux-x86/android-ndk-r7b
+    elif [ -e /opt/android-ndk-r7b ] ; then
+        NDK_ROOT=/opt/android-ndk-r7b
     else 
         echo NDK_ROOT is not specified and does not exist in default locations
         exit 1
@@ -30,7 +47,6 @@ elif [ ! -e $NDK_ROOT ] ; then
     exit 1
 fi
 export NDK_ROOT
-NDK_TOOLCHAIN=$NDK_ROOT/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/arm-linux-androideabi
 
 if [ -z "$ANDROID_SDK_HOME" ] ; then
     if [ -e /usr/local/android-sdk-linux_x86 ] ; then
@@ -49,64 +65,28 @@ elif [ ! -e $ANDROID_SDK_HOME ] ; then
 fi
 export ANDROID_SDK_HOME
 
-export PATH="$NDK_TOOLCHAIN/bin:$ANDROID_SDK_HOME/platform-tools:$PATH"
+export ANDROID_VERSION=9
+export SOURCE_LEVEL=1.6
+export TARGET_LEVEL=1.6
+export TARGET_RT_JAR=/opt-share/jre1.6.0_30/lib/rt.jar
 
 export GCC_VERSION=4.4.3
 HOST_ARCH=linux-x86
-export TARGET_ARCH=arm-linux-androideabi
-# mcpu: cortex-a8', `cortex-a9', `cortex-r4', `cortex-r4f', `cortex-m3', `cortex-m1', `xscale', `iwmmxt', `iwmmxt2', `ep9312'. 
-export TARGET_CPU_NAME=armv7-a
-TARGET_CPU_TUNE=armv7-a
-# mfpu: `vfp', `vfpv3', `vfpv3-d16' and `neon'
-TARGET_FPU_NAME=vfpv3
-TARGET_FPU_ABI=softfp
-
-export TARGET_TOOL_PATH=${NDK_ROOT}/toolchains/${TARGET_ARCH}-${GCC_VERSION}/prebuilt/${HOST_ARCH}
+export TARGET_TRIPLE=arm-linux-androideabi
 
-export TARGET_OS_PATH=${NDK_ROOT}/platforms/android-${ANDROID_VERSION}/arch-arm/usr
-export TARGET_PLATFORM_LIBS=${TARGET_OS_PATH}/lib
-export HOST_OS_PATH=${NDK_ROOT}/platforms/android-${ANDROID_VERSION}/arch-x86/usr
+export NDK_TOOLCHAIN_ROOT=$NDK_ROOT/toolchains/${TARGET_TRIPLE}-${GCC_VERSION}/prebuilt/${HOST_ARCH}
+export TARGET_PLATFORM_ROOT=${NDK_ROOT}/platforms/android-${ANDROID_VERSION}/arch-arm
 
-export NDK_XBIN_PATH=${TARGET_TOOL_PATH}/bin
-export NDK_BIN_PATH=${TARGET_TOOL_PATH}/${TARGET_ARCH}/bin
+# Need to add toolchain bins to the PATH. 
+export PATH="$NDK_TOOLCHAIN_ROOT/$TARGET_TRIPLE/bin:$ANDROID_SDK_HOME/platform-tools:$PATH"
 
-export NDK_GCC=${NDK_XBIN_PATH}/${TARGET_ARCH}-gcc
-export NDK_AR=${NDK_XBIN_PATH}/${TARGET_ARCH}-ar
-export NDK_STRIP=${NDK_XBIN_PATH}/${TARGET_ARCH}-strip
-export NDK_READELF=${NDK_XBIN_PATH}/${TARGET_ARCH}-readelf
+export GLUEGEN_CPPTASKS_FILE=`pwd`/../../gluegen/make/lib/gluegen-cpptasks-android-armv7.xml
 
-export PATH=${NDK_XBIN_PATH}:$PATH
-
-export NDK_CFLAGS="\
--march=${TARGET_CPU_NAME} \
--fpic \
--DANDROID \
-"
-
-export NDK_LDFLAGS="\
--Wl,--demangle \
--nostdlib -Bdynamic -Wl,-dynamic-linker,/system/bin/linker -Wl,--gc-sections -Wl,-z,nocopyreloc \
-${TARGET_OS_PATH}/lib/libc.so \
-${TARGET_OS_PATH}/lib/libstdc++.so \
-${TARGET_OS_PATH}/lib/libm.so \
-${TARGET_OS_PATH}/lib/crtbegin_dynamic.o \
--Wl,--no-undefined -Wl,-rpath-link=${TARGET_OS_PATH}/lib \
-${TARGET_TOOL_PATH}/lib/gcc/${TARGET_ARCH}/${GCC_VERSION}/${TARGET_CPU_NAME}/libgcc.a \
-${TARGET_OS_PATH}/lib/crtend_android.o \
-"
-
-
-which gcc 2>&1 | tee make.jogl.all.android-armv7-cross.log
+#export JUNIT_DISABLED="true"
+#export JUNIT_RUN_ARG0="-Dnewt.test.Screen.disableScreenMode"
 
+# BUILD_ARCHIVE=true \
 ant \
-    -Dgluegen-cpptasks.file=`pwd`/../../gluegen/make/lib/gluegen-cpptasks-android-armv7.xml \
     -Drootrel.build=build-android-armv7 \
-    -Dgluegen.cpptasks.detected.os=true \
-    -DisUnix=true \
-    -DisAndroid=true \
-    -DisAndroidARMv7=true \
-    -DisCrosscompilation=true \
-    \
     $* 2>&1 | tee -a make.jogl.all.android-armv7-cross.log
 
-
diff --git a/make/scripts/make.jogl.all.linux-armv7-cross.sh b/make/scripts/make.jogl.all.linux-armv7-cross.sh
index 9a6b00a..5bb5728 100755
--- a/make/scripts/make.jogl.all.linux-armv7-cross.sh
+++ b/make/scripts/make.jogl.all.linux-armv7-cross.sh
@@ -1,5 +1,12 @@
 #! /bin/sh
 
+SDIR=`dirname $0` 
+
+if [ -e $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh ] ; then
+    . $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh
+fi
+
+# arm-linux-gnueabi == armel triplet
 PATH=`pwd`/../../gluegen/make/lib/linux/arm-linux-gnueabi/bin:$PATH
 export PATH
 
@@ -10,26 +17,29 @@ export PATH
 #    -DisLinuxARMv7=true \
 #    -DisX11=false \
 
-export HOST_UID=sven
-export HOST_IP=192.168.0.52
+export NODE_LABEL=.
+
+export HOST_UID=jogamp
+export HOST_IP=jogamp02
 export HOST_RSYNC_ROOT=PROJECTS/JOGL
 
 export TARGET_UID=jogamp
-export TARGET_IP=beagle01
+export TARGET_IP=panda01
+#export TARGET_IP=jautab02
 export TARGET_ROOT=/home/jogamp/projects-cross
 export TARGET_ANT_HOME=/usr/share/ant
 
-export TARGET_PLATFORM_LIBS=/opt-linux-armv7-eabi/lib
-export TARGET_JAVA_LIBS=/opt-linux-armv7-eabi/jre/lib/arm
+export TARGET_PLATFORM_ROOT=/opt-linux-armv7-armel
+export TARGET_PLATFORM_LIBS=$TARGET_PLATFORM_ROOT/usr/lib
+export TARGET_JAVA_LIBS=$TARGET_PLATFORM_ROOT/jre/lib/arm
+
+export GLUEGEN_CPPTASKS_FILE="../../gluegen/make/lib/gluegen-cpptasks-linux-armv4.xml"
+
+#export JUNIT_DISABLED="true"
+export JUNIT_RUN_ARG0="-Dnewt.test.Screen.disableScreenMode"
 
 ant \
     -Drootrel.build=build-linux-armv7 \
-    -Dgluegen.cpptasks.detected.os=true \
-    -DisUnix=true \
-    -DisLinux=true \
-    -DisLinuxARMv7=true \
-    -DisX11=true \
-    -DisCrosscompilation=true \
     \
     -Dsetup.addNativeKD=true \
     -Dsetup.addNativeOpenMAX=true \
diff --git a/make/scripts/make.jogl.all.linux-armv7.sh b/make/scripts/make.jogl.all.linux-armv7.sh
new file mode 100755
index 0000000..0fd0b6e
--- /dev/null
+++ b/make/scripts/make.jogl.all.linux-armv7.sh
@@ -0,0 +1,27 @@
+#! /bin/sh
+
+# arm-linux-gnueabi == armel triplet
+PATH=`pwd`/../../gluegen/make/lib/linux/arm-linux-gnueabi/bin:$PATH
+export PATH
+
+#    -Dc.compiler.debug=true 
+#    -Dgluegen.cpptasks.detected.os=true \
+#    -DisUnix=true \
+#    -DisLinux=true \
+#    -DisLinuxARMv7=true \
+#    -DisX11=false \
+
+export TARGET_PLATFORM_ROOT=/
+export TARGET_PLATFORM_LIBS=/usr/lib/arm-linux-gnueabi
+export TARGET_JAVA_LIBS=/usr/lib/jvm/default-java/jre/lib/arm
+
+export GLUEGEN_CPPTASKS_FILE="../../gluegen/make/lib/gluegen-cpptasks-linux-armv4.xml"
+
+ant \
+    -Drootrel.build=build-linux-armv7 \
+    -Dsetup.addNativeKD=true \
+    -Dsetup.addNativeOpenMAX=true \
+    -Dsetup.addNativeBroadcomEGL=true \
+    -Djunit.run.arg0="-Dnewt.test.Screen.disableScreenMode" \
+    $* 2>&1 | tee make.jogl.all.linux-armv7.log
+
diff --git a/make/scripts/make.jogl.all.linux-armv7hf-cross.sh b/make/scripts/make.jogl.all.linux-armv7hf-cross.sh
new file mode 100755
index 0000000..cd82d82
--- /dev/null
+++ b/make/scripts/make.jogl.all.linux-armv7hf-cross.sh
@@ -0,0 +1,51 @@
+#! /bin/sh
+
+SDIR=`dirname $0` 
+
+if [ -e $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh ] ; then
+    . $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh
+fi
+
+# arm-linux-gnueabihf == armel triplet
+PATH=`pwd`/../../gluegen/make/lib/linux/arm-linux-gnueabihf/bin:$PATH
+export PATH
+
+#    -Dc.compiler.debug=true 
+#    -Dgluegen.cpptasks.detected.os=true \
+#    -DisUnix=true \
+#    -DisLinux=true \
+#    -DisLinuxARMv7=true \
+#    -DisX11=false \
+
+export NODE_LABEL=.
+
+export HOST_UID=jogamp
+export HOST_IP=jogamp02
+export HOST_RSYNC_ROOT=PROJECTS/JOGL
+
+export TARGET_UID=jogamp
+export TARGET_IP=panda01
+#export TARGET_IP=jautab02
+export TARGET_ROOT=/home/jogamp/projects-cross
+export TARGET_ANT_HOME=/usr/share/ant
+
+export TARGET_PLATFORM_ROOT=/opt-linux-armv7-armhf
+export TARGET_PLATFORM_LIBS=$TARGET_PLATFORM_ROOT/usr/lib
+export TARGET_JAVA_LIBS=$TARGET_PLATFORM_ROOT/jre/lib/arm
+
+export GLUEGEN_CPPTASKS_FILE="../../gluegen/make/lib/gluegen-cpptasks-linux-armv7hf.xml"
+
+#export JUNIT_DISABLED="true"
+export JUNIT_RUN_ARG0="-Dnewt.test.Screen.disableScreenMode"
+
+ant \
+    -Drootrel.build=build-linux-armv7hf \
+    \
+    -Dsetup.addNativeKD=true \
+    -Dsetup.addNativeOpenMAX=true \
+    -Dsetup.addNativeBroadcomEGL=true \
+    $* 2>&1 | tee make.jogl.all.linux-armv7hf-cross.log
+
+
+
+
diff --git a/make/scripts/make.jogl.all.linux-x86_64.sh b/make/scripts/make.jogl.all.linux-x86_64.sh
index 6fe8031..4642326 100755
--- a/make/scripts/make.jogl.all.linux-x86_64.sh
+++ b/make/scripts/make.jogl.all.linux-x86_64.sh
@@ -24,6 +24,11 @@ fi
 #    -DisLinux=true \
 #    -DisLinuxAMD64=true \
 #    -DisX11=true \
+#
+#    -Dtarget.sourcelevel=1.6 \
+#    -Dtarget.targetlevel=1.6 \
+#    -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \
+
 
 #LD_LIBRARY_PATH=/opt-linux-x86_64/mesa-7.8.1/lib64
 #export LD_LIBRARY_PATH
@@ -44,6 +49,9 @@ echo LIBGL_DEBUG: $LIBGL_DEBUG 2>&1 | tee -a $LOGF
 # BUILD_ARCHIVE=true \
 ant  \
     $CUSTOMLIBDIR \
+    -Dtarget.sourcelevel=1.6 \
+    -Dtarget.targetlevel=1.6 \
+    -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \
     -Djavacdebuglevel="source,lines,vars" \
     -Drootrel.build=build-x86_64 \
     -Dsetup.addNativeOpenMAX=true \
diff --git a/make/scripts/make.jogl.all.macosx.sh b/make/scripts/make.jogl.all.macosx.sh
index 0eaaa1c..23a276c 100755
--- a/make/scripts/make.jogl.all.macosx.sh
+++ b/make/scripts/make.jogl.all.macosx.sh
@@ -5,8 +5,18 @@ if [ -e /opt-share/etc/profile.ant ] ; then
 fi
 
 
-#    -Dc.compiler.debug=true 
+#    -Dc.compiler.debug=true \
+#    -Djavacdebug="true" \
+#    -Djavacdebuglevel="source,lines,vars" \
+#
+#    -Dtarget.sourcelevel=1.6 \
+#    -Dtarget.targetlevel=1.6 \
+#    -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \
+
 
 ant \
+    -Dtarget.sourcelevel=1.6 \
+    -Dtarget.targetlevel=1.6 \
+    -Dtarget.rt.jar=/opt-share/jre1.6.0_30/lib/rt.jar \
     -Drootrel.build=build-macosx \
     $* 2>&1 | tee make.jogl.all.macosx.log
diff --git a/make/scripts/make.jogl.all.win32.bat b/make/scripts/make.jogl.all.win32.bat
index 5094f1a..52ea33a 100755
--- a/make/scripts/make.jogl.all.win32.bat
+++ b/make/scripts/make.jogl.all.win32.bat
@@ -1,7 +1,7 @@
 set THISDIR="C:\JOGL"
 
-set J2RE_HOME=c:\jre1.6.0_29_x32
-set JAVA_HOME=c:\jdk1.6.0_29_x32
+set J2RE_HOME=c:\jre1.6.0_30_x32
+set JAVA_HOME=c:\jdk1.6.0_30_x32
 set ANT_PATH=C:\apache-ant-1.8.2
 
 set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw\bin;%PATH%
diff --git a/make/scripts/make.jogl.all.win64.bat b/make/scripts/make.jogl.all.win64.bat
index de98972..e1d258c 100755
--- a/make/scripts/make.jogl.all.win64.bat
+++ b/make/scripts/make.jogl.all.win64.bat
@@ -1,7 +1,7 @@
 set THISDIR="C:\JOGL"
 
-set J2RE_HOME=c:\jre1.6.0_29_x64
-set JAVA_HOME=c:\jdk1.6.0_29_x64
+set J2RE_HOME=c:\jre1.6.0_30_x64
+set JAVA_HOME=c:\jdk1.6.0_30_x64
 set ANT_PATH=C:\apache-ant-1.8.2
 
 set PATH=%JAVA_HOME%\bin;%ANT_PATH%\bin;c:\mingw64\bin;c:\mingw\bin;%PATH%
diff --git a/make/scripts/targetcommand-awt.sh b/make/scripts/targetcommand-awt.sh
new file mode 100755
index 0000000..af3b5f7
--- /dev/null
+++ b/make/scripts/targetcommand-awt.sh
@@ -0,0 +1,59 @@
+#! /bin/sh
+
+THISDIR=`pwd`
+
+#XTRA_FLAGS="-Dnewt.test.Screen.disableScreenMode"
+XTRA_FLAGS="-Dnewt.test.Screen.disableScreenMode -Djogl.debug.EGL -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Dnewt.debug.Screen"
+#XTRA_FLAGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow"
+#XTRA_FLAGS="-Dnewt.debug.Window -Djogl.debug.EGL -Djogl.debug.GLContext -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.EGL"
+#XTRA_FLAGS="-Djogl.debug.GraphicsConfiguration"
+#XTRA_FLAGS="-Djogl.debug.GLContext -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.TraceGL"
+#XTRA_FLAGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL"
+
+TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT
+ 
+ mkdir -p $THISDIR/projects-cross 
+
+ rsync -av --delete --delete-after --delete-excluded \
+       --exclude 'build-x86*/' --exclude 'build-linux-x*/' --exclude 'build-android*/' --exclude 'build-win*/' --exclude 'build-mac*/' \
+       --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \
+       jogamp at jogamp02::PROJECTS/JOGL/gluegen jogamp at jogamp02::PROJECTS/JOGL/jogl $THISDIR/projects-cross 
+
+ cd $THISDIR/projects-cross/jogl/make 
+ 
+function junit_run() {
+     java \
+     -cp ../../gluegen/make/lib/junit.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-junit.jar:../../gluegen/build-linux-armv7/gluegen-rt.jar:../build-linux-armv7/jar/jogl.all.jar:../build-linux-armv7/jar/jogl.test.jar\
+     $XTRA_FLAGS \
+     com.jogamp.newt.util.MainThread\
+     org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \
+     $TSTCLASS \
+     filtertrace=true \
+     haltOnError=false \
+     haltOnFailure=false \
+     showoutput=true \
+     outputtoformatters=true \
+     logfailedtests=true \
+     logtestlistenerevents=true \
+     formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \
+     formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,$THISDIR/targetcommand.xml
+}
+ 
+function main_run() {
+     java \
+     -cp ../../gluegen/make/lib/junit.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-junit.jar:../../gluegen/build-linux-armv7/gluegen-rt.jar:../build-linux-armv7/jar/jogl.all.jar:../build-linux-armv7/jar/jogl.test.jar\
+     $XTRA_FLAGS \
+     com.jogamp.newt.util.MainThread\
+     $TSTCLASS \
+     $*
+}
+ 
+# junit_run 2>&1 | tee $THISDIR/targetcommand.log
+
+main_run $* 2>&1 | tee $THISDIR/targetcommand.log
+ 
diff --git a/make/scripts/targetcommand-newt.sh b/make/scripts/targetcommand-newt.sh
new file mode 100755
index 0000000..47b7a0b
--- /dev/null
+++ b/make/scripts/targetcommand-newt.sh
@@ -0,0 +1,124 @@
+#! /bin/sh
+
+THISDIR=`pwd`
+
+export LD_LIBRARY_PATH=$THISDIR/PVRTrace/:$LD_LIBRARY_PATH
+
+XTRA_FLAGS="-Dnewt.test.Screen.disableScreenMode -Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext.TraceSwitch "
+#XTRA_FLAGS="-Dnewt.test.Screen.disableScreenMode -Djogl.debug.DebugGL -Djogl.debug.TraceGL"
+#XTRA_FLAGS="-Dnewt.test.Screen.disableScreenMode -Djogl.debug.EGL -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Dnewt.debug.Screen"
+#XTRA_FLAGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow"
+#XTRA_FLAGS="-Dnewt.debug.Window -Djogl.debug.EGL -Djogl.debug.GLContext -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.EGL"
+#XTRA_FLAGS="-Djogl.debug.GraphicsConfiguration"
+#XTRA_FLAGS="-Djogl.debug.GLContext -Djogl.debug.GLDrawable"
+#XTRA_FLAGS="-Djogl.debug.TraceGL"
+#XTRA_FLAGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL"
+
+# OK (Panda, Omap4)
+#
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.util.TestGLReadBufferUtilTextureIOWrite01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.util.TestGLReadBufferUtilTextureIOWrite02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.graph.TestRegionRendererNEWT01 # (Tegra regressions)
+#TSTCLASS=com.jogamp.opengl.test.junit.graph.TestTextRendererNEWT01  # (Tegra regressions)
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT
+TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT
+
+# Some Regressions (Panda, Omap4)
+#
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT
+
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestNVSwapGroupNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES1NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT2
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestRedSquareES1NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.drawable.TestDrawable01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.glsl.TestTransformFeedbackVaryingsBug407NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestGLWindows00NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestRemoteGLWindows01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestRemoteWindow01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.TestWindows01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
+#TSTCLASS=com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT
+ 
+ mkdir -p $THISDIR/projects-cross 
+
+ rsync -av --delete --delete-after --delete-excluded \
+       --exclude 'build-x86*/' --exclude 'build-linux-x*/' --exclude 'build-android*/' --exclude 'build-win*/' --exclude 'build-mac*/' \
+       --exclude 'classes/' --exclude 'src/' --exclude '.git/' --exclude '*-java-src.zip' \
+       jogamp at jogamp02::PROJECTS/JOGL/gluegen jogamp at jogamp02::PROJECTS/JOGL/jogl $THISDIR/projects-cross 
+
+ cd $THISDIR/projects-cross/jogl/make 
+
+ cp -a $THISDIR/pvrtrace.cfg .
+ 
+function junit_run() {
+     java \
+     -cp ../../gluegen/make/lib/junit.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-junit.jar:../../gluegen/build-linux-armv7/gluegen-rt.jar:../build-linux-armv7/jar/jogl.all-noawt.jar:../build-linux-armv7/jar/jogl.test.jar\
+     -Djava.awt.headless=true\
+     $XTRA_FLAGS \
+     com.jogamp.newt.util.MainThread\
+     org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner \
+     $TSTCLASS \
+     filtertrace=true \
+     haltOnError=false \
+     haltOnFailure=false \
+     showoutput=true \
+     outputtoformatters=true \
+     logfailedtests=true \
+     logtestlistenerevents=true \
+     formatter=org.apache.tools.ant.taskdefs.optional.junit.PlainJUnitResultFormatter \
+     formatter=org.apache.tools.ant.taskdefs.optional.junit.XMLJUnitResultFormatter,$THISDIR/targetcommand.xml
+}
+ 
+function main_run() {
+     java \
+     -cp ../../gluegen/make/lib/junit.jar:/usr/share/ant/lib/ant.jar:/usr/share/ant/lib/ant-junit.jar:../../gluegen/build-linux-armv7/gluegen-rt.jar:../build-linux-armv7/jar/jogl.all-noawt.jar:../build-linux-armv7/jar/jogl.test.jar\
+     -Djava.awt.headless=true\
+     $XTRA_FLAGS \
+     com.jogamp.newt.util.MainThread\
+     $TSTCLASS \
+     $*
+}
+ 
+# junit_run 2>&1 | tee $THISDIR/targetcommand.log
+
+main_run $* 2>&1 | tee $THISDIR/targetcommand.log
+
+cp -a trace-*.pvrt $THISDIR/
+ 
diff --git a/make/scripts/tests-javaws-x64.bat b/make/scripts/tests-javaws-x64.bat
index 1a67326..40f1182 100755
--- a/make/scripts/tests-javaws-x64.bat
+++ b/make/scripts/tests-javaws-x64.bat
@@ -1,4 +1,4 @@
-set JRE_PATH=C:\jre1.6.0_29_x64\bin
+set JRE_PATH=C:\jre1.6.0_30_x64\bin
 set LOG_PATH=%USERPROFILE%\AppData\LocalLow\Sun\Java\Deployment\log
 
 %JRE_PATH%\javaws -uninstall
diff --git a/make/scripts/tests-linux-armv7.sh b/make/scripts/tests-linux-armv7.sh
new file mode 100755
index 0000000..6ec93db
--- /dev/null
+++ b/make/scripts/tests-linux-armv7.sh
@@ -0,0 +1,7 @@
+#! /bin/bash
+
+spath=`dirname $0`
+
+. $spath/tests.sh  `which java` -DummyArg ../build-linux-armv7 $*
+
+
diff --git a/make/scripts/tests-linux-armv7hf.sh b/make/scripts/tests-linux-armv7hf.sh
new file mode 100755
index 0000000..5526e81
--- /dev/null
+++ b/make/scripts/tests-linux-armv7hf.sh
@@ -0,0 +1,7 @@
+#! /bin/bash
+
+spath=`dirname $0`
+
+. $spath/tests.sh  `which java` -DummyArg ../build-linux-armv7hf $*
+
+
diff --git a/make/scripts/tests-osx-x32.sh b/make/scripts/tests-osx-x32.sh
new file mode 100755
index 0000000..e7f4f01
--- /dev/null
+++ b/make/scripts/tests-osx-x32.sh
@@ -0,0 +1,7 @@
+#! /bin/bash
+
+spath=`dirname $0`
+
+. $spath/tests.sh /usr/bin/java -d32 ../build-macosx $*
+
+
diff --git a/make/scripts/tests-osx-x64.sh b/make/scripts/tests-osx-x64.sh
index e502668..748cf39 100755
--- a/make/scripts/tests-osx-x64.sh
+++ b/make/scripts/tests-osx-x64.sh
@@ -1,5 +1,7 @@
 #! /bin/bash
 
+export DYLD_LIBRARY_PATH=/usr/local/lib:$DYLD_LIBRARY_PATH
+
 spath=`dirname $0`
 
 . $spath/tests.sh  /usr/bin/java -d64 ../build-macosx $*
diff --git a/make/scripts/tests-x32.bat b/make/scripts/tests-x32.bat
index 0caa0ef..c29dcef 100755
--- a/make/scripts/tests-x32.bat
+++ b/make/scripts/tests-x32.bat
@@ -1,46 +1,100 @@
+REM scripts\java-win32-dbg.bat jogamp.newt.awt.opengl.VersionApplet
 REM scripts\java-win32-dbg.bat com.jogamp.newt.opengl.GLWindow
-REM scripts\java-win32-dbg.bat com.jogamp.newt.opengl.GLWindow
-REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000
-REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT -time 5000
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT
+REM scripts\java-win32-dbg.bat javax.media.opengl.awt.GLCanvas
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.awt.TestSwingAWT01GLn
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListAWT -time 5000
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT -time 5000
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 %*
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT %*
+
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %*
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %*
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestRedSquareES2NEWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT -time 5000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT03GLCanvasRecreate01
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.newt.TestSwingAWTRobotUsageBeforeJOGLInitBug411
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestTransformFeedbackVaryingsBug407NEWT
-REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT -time 2000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT -time 2000
 
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestParenting01AWT
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %*
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT -time 50000
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT %*
 
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot
-scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot %*
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.nativewindow.TestRecursiveToolkitLockCORE
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT -time 100000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000
 
 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT
+
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %*
+scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 %*
 
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %*
 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT
+
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleAWT -time 10000
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleNEWT -time 10000
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug461OffscreenSupersamplingSwingAWT
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT
+
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol01AWT $*
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $*
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol03NewtAWT $*
 
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %1 %2 %3 %4
-REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %1 %2 %3 %4
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %*
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAWT01GLn $*
 
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT -time 5000
+
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT
+
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.TestRegionRendererNEWT01
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.TestTextRendererNEWT01
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.demos.ui.UINewtDemo01
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo01
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.demos.GPUTextNewtDemo02
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.demos.GPURegionNewtDemo01
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.graph.demos.GPURegionNewtDemo02
+
 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $*
 REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $*
 
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $*
+REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT
+
 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01
 REM scripts\java-win32.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01
 
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %*
+
diff --git a/make/scripts/tests-x64.bat b/make/scripts/tests-x64.bat
index 308da58..f0144f1 100755
--- a/make/scripts/tests-x64.bat
+++ b/make/scripts/tests-x64.bat
@@ -1,19 +1,25 @@
 REM scripts\java-win64-dbg.bat jogamp.newt.awt.opengl.VersionApplet
 REM scripts\java-win64-dbg.bat com.jogamp.newt.opengl.GLWindow
 REM scripts\java-win64-dbg.bat javax.media.opengl.awt.GLCanvas
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT -time 5000
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT %*
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.awt.TestSwingAWT01GLn
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListAWT -time 5000
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT -time 5000
-REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 %1 %2 %3 %4 %5
-REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT %1 %2 %3 %4 %5 %6
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT2 %*
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextVBOES2NEWT %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT %*
+REM scripts\java-win32-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile02NEWT %*
 
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %1 %2 %3 %4 %5 %6
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNewtAWTWrapper %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.newt.TestGearsNEWT -time 30000
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %1 %2 %3
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %1 %2 %3 %4 %5 %6
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es1.newt.TestGearsES1NEWT %*
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT %*
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 4000 -x 10 -y 10 -width 100 -height 100 -screen 0
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestGearsES2NEWT -vsync -time 40000 -width 100 -height 100 -screen 0 %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT -time 5000
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT -time 5000
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.awt.TestAWT03GLCanvasRecreate01
@@ -22,21 +28,21 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestTransf
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLSimple01NEWT -time 2000
 
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestParenting01AWT
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %1 %2 %3 %4 %5 %6
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01bAWT %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cAWT -time 50000
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestListenerCom01AWT
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT %1 %2 %3 %4 %5 %6
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT %*
 
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestWindows01NEWT
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestGLWindows02NEWTAnimated
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
-REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot %1 %2 %3 %4 %5 %6
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot %1 %2 %3 %4 %5 %6
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.nativewindow.TestRecursiveToolkitLockCORE
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT -time 100000
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %1 %2 %3
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %1 %2 %3
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03AWT %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01AWT %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting03bAWT -time 100000
 
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot
@@ -45,9 +51,13 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode0
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestScreenMode02NEWT
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT
 
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple %*
+scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 %*
+
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle01NEWT
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT
-REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %1 %2 %3 %4
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT %*
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT
 
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleAWT -time 10000
@@ -59,8 +69,8 @@ REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingPr
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $*
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol03NewtAWT $*
 
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %1 %2 %3 %4
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %1 %2 %3 %4
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn %*
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn %*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.swt.TestSWTAWT01GLn $*
 
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT -time 5000
@@ -82,10 +92,10 @@ REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGLDeb
 
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $*
 REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $*
-scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT
+REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT
 
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestRulerNEWT01
 REM scripts\java-win64.bat com.jogamp.opengl.test.junit.jogl.glsl.TestFBOMRTNEWT01
 
-REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %1 %2 %3 %4
+REM scripts\java-win64-dbg.bat com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT %*
 
diff --git a/make/scripts/tests-x64.sh b/make/scripts/tests-x64.sh
index ba70489..c3c6762 100755
--- a/make/scripts/tests-x64.sh
+++ b/make/scripts/tests-x64.sh
@@ -2,6 +2,8 @@
 
 SDIR=`dirname $0` 
 
+#export LD_LIBRARY_PATH=/home/sven/libav/lib:$LD_LIBRARY_PATH
+
 if [ -e $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh ] ; then
     . $SDIR/../../../gluegen/make/scripts/setenv-build-jogl-x86_64.sh
 fi
diff --git a/make/scripts/tests.sh b/make/scripts/tests.sh
index f8205b6..81cb060 100755
--- a/make/scripts/tests.sh
+++ b/make/scripts/tests.sh
@@ -32,6 +32,7 @@ MOSX=0
 MOSX_MT=0
 uname -a | grep -i Darwin && MOSX=1
 if [ $MOSX -eq 1 ] ; then
+    #export NSZombieEnabled=YES
     MOSX_MT=1
 fi
 
@@ -40,6 +41,8 @@ $javaexe -version 2>&1 | tee -a java-run.log
 echo LIBXCB_ALLOW_SLOPPY_LOCK: $LIBXCB_ALLOW_SLOPPY_LOCK 2>&1 | tee -a java-run.log
 echo LIBGL_DRIVERS_PATH: $LIBGL_DRIVERS_PATH 2>&1 | tee -a java-run.log
 echo LIBGL_DEBUG: $LIBGL_DEBUG 2>&1 | tee -a java-run.log
+echo LIBGL_ALWAYS_INDIRECT: $LIBGL_ALWAYS_INDIRECT 2>&1 | tee -a java-run.log
+echo LIBGL_ALWAYS_SOFTWARE: $LIBGL_ALWAYS_SOFTWARE 2>&1 | tee -a java-run.log
 echo SWT_CLASSPATH: $SWT_CLASSPATH 2>&1 | tee -a java-run.log
 echo $javaexe $javaxargs $X_ARGS $D_ARGS $* 2>&1 | tee -a java-run.log
 echo MacOsX $MOSX
@@ -50,15 +53,33 @@ function jrun() {
     swton=$1
     shift
 
+    #D_ARGS="-Djogamp.debug.NativeLibrary -Djogamp.debug.NativeLibrary.UseCurrentThreadLibLoader"
+    #D_ARGS="-Djogl.1thread=false -Djogl.debug.Threading"
+    #D_ARGS="-Djogl.1thread=true -Djogl.debug.Threading"
+    #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch"
+    #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL -Djogl.debug.GLContext.TraceSwitch -Djogl.debug=all"
+    #D_ARGS="-Djogl.debug.GLDebugMessageHandler"
+    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL"
+    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Djogl.debug.GLSLState"
+    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL -Djogl.debug.TraceGL"
+    #D_ARGS="-Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode"
+    #D_ARGS="-Djogamp.debug.IOUtil -Djogl.debug.GLSLCode -Djogl.debug.GLMediaPlayer"
+    #D_ARGS="-Djogl.debug.GLArrayData"
+    #D_ARGS="-Djogl.debug.EGL -Dnativewindow.debug.GraphicsConfiguration -Djogl.debug.GLDrawable"
+    #D_ARGS="-Dnewt.test.Screen.disableScreenMode -Dnewt.debug.Screen"
     #D_ARGS="-Djogl.debug.ExtensionAvailabilityCache -Djogl.debug=all -Dnativewindow.debug=all -Djogamp.debug.ProcAddressHelper=true -Djogamp.debug.NativeLibrary=true -Djogamp.debug.NativeLibrary.Lookup=true"
-    #D_ARGS="-Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all"
     #D_ARGS="-Djogamp.debug=all -Dnativewindow.debug=all -Djogl.debug=all -Dnewt.debug=all"
     #D_ARGS="-Dnewt.debug.MainThread"
+    #D_ARGS="-Dnewt.debug.Window"
     #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all"
+    #D_ARGS="-Dnativewindow.debug.GraphicsConfiguration -Dnativewindow.debug.NativeWindow"
+    #D_ARGS="-Djogl.debug=all"
+    #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.Animator -Djogl.debug.GLDrawable -Djogl.debug.GLContext -Djogl.debug.GLContext.TraceSwitch"
     #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.ExtensionAvailabilityCache"
     #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile -Djogl.debug.GLDrawable"
+    #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GLProfile"
     #D_ARGS="-Djogl.debug.GLProfile"
-    # D_ARGS="-Dnewt.debug.EDT -Dnativewindow.debug.ToolkitLock.TraceLock -Dnativewindow.debug.NativeWindow"
+    #D_ARGS="-Dnewt.debug.EDT -Dnativewindow.debug.ToolkitLock.TraceLock -Dnativewindow.debug.NativeWindow"
     #D_ARGS="-Dnativewindow.debug.NativeWindow"
     #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT"
     #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Window -Djogl.debug.GLContext"
@@ -66,10 +87,11 @@ function jrun() {
     #D_ARGS="-Dnativewindow.debug.X11Util -Djogl.debug.GLContext -Djogl.debug.GLDrawable -Dnewt.debug=all"
     #D_ARGS="-Djogl.debug.GLDrawable -Djogl.debug.GLContext"
     #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=600000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock"
-    #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=1000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock"
+    #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=3000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock"
     #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=600000 -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock -Dnativewindow.debug.ToolkitLock.TraceLock"
     #D_ARGS="-Djogamp.common.utils.locks.Lock.timeout=600000 -Djogamp.debug.Lock -Dnativewindow.debug.X11Util"
     #D_ARGS="-Dnewt.debug.EDT -Djogamp.common.utils.locks.Lock.timeout=600000 -Djogl.debug.Animator -Dnewt.debug.Display -Dnewt.debug.Screen"
+    #D_ARGS="-Dnewt.debug.Screen"
     #D_ARGS="-Dnewt.debug.Window -Djogamp.common.utils.locks.Lock.timeout=600000 -Djogl.debug.Animator"
     #D_ARGS="-Djogl.debug.Animator -Dnewt.debug=all"
     #D_ARGS="-Dnewt.debug.EDT -Dnewt.debug.Display -Dnativewindow.debug.X11Util -Djogl.debug.GLDrawable -Djogl.debug.GLCanvas"
@@ -78,26 +100,23 @@ function jrun() {
     #D_ARGS="-Dnewt.debug.Screen -Dnewt.debug.EDT -Djogamp.debug.Lock"
     #D_ARGS="-Djogl.debug.GLContext -Djogl.debug.GraphicsConfiguration"
     #D_ARGS="-Dnewt.debug.EDT"
+    #D_ARGS="-Djogamp.debug=all -Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all"
     #D_ARGS="-Djogl.debug=all -Dnativewindow.debug=all -Dnewt.debug=all"
     #D_ARGS="-Djogl.debug=all -Dnewt.debug=all"
     #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT -Djogl.debug.GLContext"
     #D_ARGS="-Dnewt.debug.Window -Djogl.debug.Animator -Dnewt.debug.Screen"
-    #D_ARGS="-Dnewt.debug.Window -Dnewt.debug.Window.KeyEvent"
+    #D_ARGS="-Dnewt.debug.Window"
+    #D_ARGS="-Dnewt.debug.Window.KeyEvent"
+    #D_ARGS="-Dnewt.debug.Window.MouseEvent"
     #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug=all"
+    #D_ARGS="-Dnewt.debug.Window -Dnativewindow.debug.JAWT -Djogl.debug.Animator"
+    #D_ARGS="-Dnewt.debug.Window"
     #D_ARGS="-Xprof"
     #D_ARGS="-Djogl.debug.Animator"
     #D_ARGS="-Dnativewindow.debug=all"
     #D_ARGS="-Djogl.debug.GraphicsConfiguration"
     #D_ARGS="-Djogl.debug.GLCanvas -Djogl.debug.GraphicsConfiguration"
     #D_ARGS="-Djogl.debug.GLCanvas"
-    #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.GLDebugMessageHandler -Djogl.debug.GLSLCode"
-    #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL"
-    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Dnewt.debug.Window -Dnewt.debug.Display -Dnewt.debug.EDT"
-    #D_ARGS="-Djogl.debug.GLDebugMessageHandler"
-    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL"
-    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.TraceGL -Djogl.debug.DebugGL -Djogl.debug.GLSLCode -Djogl.debug.GLSLState"
-    #D_ARGS="-Djogl.debug.GLDebugMessageHandler -Djogl.debug.DebugGL -Djogl.debug.TraceGL"
-    #D_ARGS="-Djogl.debug.DebugGL -Djogl.debug.TraceGL"
     #D_ARGS="-Dnativewindow.debug.ToolkitLock.TraceLock"
     #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLCode -Djogl.debug.TraceGL"
     #D_ARGS="-Djogl.debug.graph.curve -Djogl.debug.GLSLState"
@@ -113,18 +132,26 @@ function jrun() {
     #D_ARGS="-Dnewt.debug=all -Djogamp.debug.Lock -Djogamp.debug.Lock.TraceLock"
     #D_ARGS="-Djogl.debug.GLContext -Dnewt.debug=all -Djogamp.debug.Lock -Djogamp.common.utils.locks.Lock.timeout=10000"
     #D_ARGS="-Dnewt.debug=all"
-    #X_ARGS="-Dsun.java2d.noddraw=true -Dsun.java2d.opengl=true"
+    #X_ARGS="-Dsun.java2d.noddraw=True -Dsun.java2d.opengl=True -Dsun.java2d.xrender=false"
+    #X_ARGS="-Dsun.java2d.noddraw=True -Dsun.java2d.opengl=false -Dsun.java2d.xrender=false"
     #X_ARGS="-verbose:jni"
+    #X_ARGS="-Xrs"
 
     if [ $awton -eq 1 ] ; then
         export CLASSPATH=$JOGAMP_ALL_AWT_CLASSPATH
         echo CLASSPATH $CLASSPATH
-        X_ARGS="-Djava.awt.headless=false"
+        X_ARGS="-Djava.awt.headless=false $X_ARGS"
     else
         export CLASSPATH=$JOGAMP_ALL_NOAWT_CLASSPATH
-        echo CLASSPATH $CLASSPATH
-        X_ARGS="-Djava.awt.headless=true"
+        X_ARGS="-Djava.awt.headless=true $X_ARGS"
+    fi
+    if [ $swton -eq 1 ] ; then
+        export CLASSPATH=$CLASSPATH:$JOGL_SWT_CLASSPATH
     fi
+    if [ ! -z "$CUSTOM_CLASSPATH" ] ; then
+        export CLASSPATH=$CUSTOM_CLASSPATH:$CLASSPATH
+    fi
+    echo CLASSPATH $CLASSPATH
     if [ $MOSX_MT -eq 1 ] ; then
         X_ARGS="-XstartOnFirstThread $X_ARGS"
         if [ $swton -eq 0 ] ; then
@@ -142,6 +169,10 @@ function jrun() {
     #LD_LIBRARY_PATH=/opt-linux-x86_64/mesa-7.8.1/lib64:$LD_LIBRARY_PATH \
     #LIBGL_DRIVERS_PATH=/usr/lib/mesa:/usr/lib32/mesa \
     #LD_LIBRARY_PATH=/usr/lib/mesa:/usr/lib32/mesa:$LD_LIBRARY_PATH \
+    #LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/mesa:/usr/lib/i386-linux-gnu/mesa:$LD_LIBRARY_PATH \
+    #LD_LIBRARY_PATH=$spath/../lib/PVRVFrame/OGLES-2.0/Linux_x86_64:$LD_LIBRARY_PATH \
+    #LD_LIBRARY_PATH=$spath/../lib/PVRVFrame/OGLES-2.0/Linux_x86_32:$LD_LIBRARY_PATH \
+    #gdb --args $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $*
     $javaexe $javaxargs $X_ARGS $D_ARGS $C_ARG $*
     echo
     echo "Test End: $*"
@@ -161,6 +192,10 @@ function testswt() {
     jrun 0 1 $* 2>&1 | tee -a java-run.log
 }
 
+function testawtswt() {
+    jrun 1 1 $* 2>&1 | tee -a java-run.log
+}
+
 #
 # newt (testnoawt and testawt)
 #
@@ -170,11 +205,12 @@ function testswt() {
 #testnoawt com.jogamp.newt.opengl.GLWindow $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen01GLPBufferNEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.offscreen.TestOffscreen02BitmapNEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestNEWTCloseX11DisplayBug565 $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLWindowNEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteNEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedNEWT $*
 testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
-#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLProfile01NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug00NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGLDebug01NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListNEWT $*
@@ -198,7 +234,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #testnoawt com.jogamp.opengl.test.junit.newt.TestDisplayLifecycle02NEWT
 #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting02NEWT $*
-#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT
+#testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode00bNEWT
 #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01NEWT
 #testnoawt com.jogamp.opengl.test.junit.newt.TestScreenMode01bNEWT
@@ -206,6 +242,12 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #testnoawt com.jogamp.opengl.test.junit.newt.ManualScreenMode03NEWT
 #testnoawt com.jogamp.opengl.test.junit.newt.TestWindowClosingProtocol02NEWT $*
 #testnoawt -Djava.awt.headless=true com.jogamp.opengl.test.junit.newt.TestGLWindows01NEWT
+#testnoawt com.jogamp.opengl.test.junit.jogl.util.TestGLReadBufferUtilTextureIOWrite01NEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.util.TestGLReadBufferUtilTextureIOWrite02NEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.util.TestPNGImage01NEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2 $*
 
 #
 # awt (testawt)
@@ -213,30 +255,43 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #testawt jogamp.newt.awt.opengl.VersionApplet $*
 #testawt javax.media.opengl.awt.GLCanvas $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestMainVersionGLCanvasAWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug551AWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT01GLn $*
+#testawt com.jogamp.opengl.test.junit.jogl.acore.TestAWTCloseX11DisplayBug565 $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextListAWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestSharedContextNewtAWTBug523 $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestPBufferDeadlockAWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownCompleteAWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.acore.TestShutdownSharedAWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.acore.x11.TestGLXCallsOnAWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.awt.TestSwingAWT01GLn
 #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT03GLCanvasRecreate01 $*
 #testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWT02WindowClosing
 #testawt com.jogamp.opengl.test.junit.jogl.awt.text.TestAWTTextRendererUseVertexArrayBug464
 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.demos.es2.awt.TestGearsES2AWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsAWTAnalyzeBug455 $*
 #testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.demos.gl2.awt.TestGearsGLJPanelAWTBug450 $*
 #testawt com.jogamp.opengl.test.junit.jogl.texture.TestTexture01AWT
 #testawt com.jogamp.opengl.test.junit.jogl.awt.TestBug461OffscreenSupersamplingSwingAWT
 #testawt com.jogamp.opengl.test.junit.jogl.texture.TestGrayTextureFromFileAWTBug417
-#testawt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAWT01GLn $*
 #testawt com.jogamp.opengl.test.junit.jogl.glu.TestBug463ScaleImageMemoryAWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.awt.TestAWTCardLayoutAnimatorStartStopBug532 $*
 
 #
 # swt (testswt)
 #
 #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWT01GLn $*
 #testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWT02GLn $*
+#testswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTGLCanvas01GLn $*
+#testawt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAccessor02GLn $*
+
+#
+# awtswt (testawtswt)
+#
+#testawt com.jogamp.opengl.test.junit.jogl.swt.TestSWTAWT01GLn $*
+#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLnAWT $*
 
 #
 # newt.awt (testawt)
@@ -258,8 +313,8 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $*
 #testawt com.jogamp.opengl.test.junit.newt.parenting.TestTranslucentParentingAWT $*
 #testawt com.jogamp.opengl.test.junit.newt.TestCloseNewtAWT
-#testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleAWT $*
-#testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleNEWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1AWT $*
+#testawt com.jogamp.opengl.test.junit.jogl.caps.TestMultisampleES1NEWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyAWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.caps.TestTranslucencyNEWT $*
 #testawt com.jogamp.opengl.test.junit.jogl.glsl.TestShaderCompilationBug459AWT
@@ -288,7 +343,7 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #testnoawt com.jogamp.opengl.test.junit.graph.demos.GPUUISceneNewtDemo02 $*
 
 #testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestGPUMemSec01NEWT $*
-#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBuffer01NEWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestMapBufferRead01NEWT $*
 #testnoawt com.jogamp.opengl.test.junit.jogl.demos.es2.newt.TestElektronenMultipliziererNEWT $*
 
 #
@@ -299,6 +354,19 @@ testnoawt com.jogamp.opengl.test.junit.jogl.acore.TestInitConcurrentNEWT $*
 #
 # regressions
 #
+#Windows
+#testawt com.jogamp.opengl.test.junit.newt.TestFocus01SwingAWTRobot $*
+#testawt com.jogamp.opengl.test.junit.newt.TestFocus02SwingAWTRobot $*
+
+#linux:
+#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParenting01cSwingAWT $*
+#testnoawt com.jogamp.opengl.test.junit.jogl.glsl.TestGLSLShaderState02NEWT $*
+
+# osx:
+#testawtswt com.jogamp.opengl.test.junit.jogl.swt.TestSWTJOGLGLCanvas01GLnAWT $*
+#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingFocusTraversal01AWT $*
+#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer01GLCanvasAWT $*
+#testawt com.jogamp.opengl.test.junit.newt.parenting.TestParentingOffscreenLayer02NewtCanvasAWT $*
 
 $spath/count-edt-start.sh java-run.log
 
diff --git a/make/stub_includes/egl/EGL/egl.h b/make/stub_includes/egl/EGL/egl.h
index 1eabe3a..4c005e8 100644
--- a/make/stub_includes/egl/EGL/egl.h
+++ b/make/stub_includes/egl/EGL/egl.h
@@ -43,10 +43,10 @@ extern "C" {
 /* EGLint is defined in eglplatform.h */
 typedef unsigned int EGLBoolean;
 typedef unsigned int EGLenum;
-typedef void *EGLConfig;
-typedef void *EGLContext;
-typedef void *EGLDisplay;
-typedef void *EGLSurface;
+typedef struct __EGLConfig *EGLConfig;
+typedef struct __EGLContext *EGLContext;
+typedef struct __EGLDisplay *EGLDisplay;
+typedef struct __EGLSurface *EGLSurface;
 typedef void *EGLClientBuffer;
 
 /* EGL Versioning */
diff --git a/make/stub_includes/egl/EGL/eglext.h b/make/stub_includes/egl/EGL/eglext.h
index 972becf..7634036 100644
--- a/make/stub_includes/egl/EGL/eglext.h
+++ b/make/stub_includes/egl/EGL/eglext.h
@@ -6,7 +6,7 @@ extern "C" {
 #endif
 
 /*
-** Copyright (c) 2007-2010 The Khronos Group Inc.
+** Copyright (c) 2007-2012 The Khronos Group Inc.
 **
 ** Permission is hereby granted, free of charge, to any person obtaining a
 ** copy of this software and/or associated documentation files (the
@@ -34,8 +34,8 @@ extern "C" {
 
 /* Header file version number */
 /* Current version at http://www.khronos.org/registry/egl/ */
-/* $Revision: 12814 $ on $Date: 2010-11-03 17:47:28 -0700 (Wed, 03 Nov 2010) $ */
-#define EGL_EGLEXT_VERSION 8
+/* $Revision: 16473 $ on $Date: 2012-01-04 02:20:48 -0800 (Wed, 04 Jan 2012) $ */
+#define EGL_EGLEXT_VERSION 11
 
 #ifndef EGL_KHR_config_attribs
 #define EGL_KHR_config_attribs 1
@@ -78,7 +78,7 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay display
 #ifndef EGL_KHR_image
 #define EGL_KHR_image 1
 #define EGL_NATIVE_PIXMAP_KHR			0x30B0	/* eglCreateImageKHR target */
-typedef void *EGLImageKHR;
+typedef struct __EGLImageKHR *EGLImageKHR;
 /* Manual: #define EGL_NO_IMAGE_KHR ((EGLImageKHR)0) */
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
@@ -124,7 +124,7 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGL
 #ifndef EGL_KHR_reusable_sync
 #define EGL_KHR_reusable_sync 1
 
-typedef void* EGLSyncKHR;
+typedef struct __EGLSyncKHR* EGLSyncKHR;
 typedef khronos_utime_nanoseconds_t EGLTimeKHR;
 
 #define EGL_SYNC_STATUS_KHR			0x30F1
@@ -178,15 +178,15 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EG
 
 #ifndef EGL_NV_coverage_sample
 #define EGL_NV_coverage_sample 1
-#define EGL_COVERAGE_BUFFERS_NV 0x30E0
-#define EGL_COVERAGE_SAMPLES_NV 0x30E1
+#define EGL_COVERAGE_BUFFERS_NV			0x30E0
+#define EGL_COVERAGE_SAMPLES_NV			0x30E1
 #endif
 
 #ifndef EGL_NV_depth_nonlinear
 #define EGL_NV_depth_nonlinear 1
-#define EGL_DEPTH_ENCODING_NV 0x30E2
+#define EGL_DEPTH_ENCODING_NV			0x30E2
 #define EGL_DEPTH_ENCODING_NONE_NV 0
-#define EGL_DEPTH_ENCODING_NONLINEAR_NV 0x30E3
+#define EGL_DEPTH_ENCODING_NONLINEAR_NV		0x30E3
 #endif
 
 #if KHRONOS_SUPPORT_INT64   /* EGLTimeNV requires 64-bit uint support */
@@ -284,20 +284,37 @@ typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy,
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
 #endif
 
-/**
- * Added a few NVidia extensions here.
- * FIXME: Double check if they are still 'active'
- */
+#ifndef EGL_NV_post_sub_buffer
+#define EGL_NV_post_sub_buffer 1
+#define EGL_POST_SUB_BUFFER_SUPPORTED_NV	0x30BE
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLPOSTSUBBUFFERNVPROC) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
+#endif
 
-/* EGL_NV_texture_rectangle (reuse analagous WGL enum) */
-#ifndef EGL_NV_texture_rectangle
-#define EGL_NV_texture_rectangle 1
-#define EGL_GL_TEXTURE_RECTANGLE_NV_KHR           0x30BB
-#define EGL_TEXTURE_RECTANGLE_NV       0x20A2
+#ifndef EGL_ANGLE_query_surface_pointer
+#define EGL_ANGLE_query_surface_pointer 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean eglQuerySurfacePointerANGLE(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
+#endif
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPOINTERANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
 #endif
 
-#include "egl-64bit-types.h"
+#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle
+#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1
+#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE	0x3200
+#endif
+
+#ifndef EGL_NV_coverage_sample_resolve
+#define EGL_NV_coverage_sample_resolve 1
+#define EGL_COVERAGE_SAMPLE_RESOLVE_NV		0x3131
+#define EGL_COVERAGE_SAMPLE_RESOLVE_DEFAULT_NV	0x3132
+#define EGL_COVERAGE_SAMPLE_RESOLVE_NONE_NV	0x3133
+#endif
 
+
+#include "egl-64bit-types.h"
 #ifndef EGL_NV_system_time
 #define EGL_NV_system_time 1
 #ifdef EGL_EGLEXT_PROTOTYPES
@@ -308,6 +325,14 @@ typedef EGLuint64 (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC)(void);
 typedef EGLuint64 (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC)(void);
 #endif
 
+#ifndef EGL_EXT_create_context_robustness
+#define EGL_EXT_create_context_robustness 1
+#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT	0x30BF
+#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT 0x3138
+#define EGL_NO_RESET_NOTIFICATION_EXT		0x31BE
+#define EGL_LOSE_CONTEXT_ON_RESET_EXT		0x31BF
+#endif
+
 /* EGL_NV_omx_il_sink
  */
 #ifndef EGL_NV_omx_il_sink
@@ -321,6 +346,19 @@ typedef EGLuint64 (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC)(void);
 
 #define EGL_RMSURFACE_NV 0x30EF /* eglCreateImageKHR target */
 
+/**
+ * Added a few NVidia extensions here.
+ * FIXME: Double check if they are still 'active'
+ */
+
+/* EGL_NV_texture_rectangle (reuse analagous WGL enum) */
+#ifndef EGL_NV_texture_rectangle
+#define EGL_NV_texture_rectangle 1
+#define EGL_GL_TEXTURE_RECTANGLE_NV_KHR           0x30BB
+#define EGL_TEXTURE_RECTANGLE_NV       0x20A2
+#endif
+
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/make/stub_includes/egl/EGL/eglplatform.h b/make/stub_includes/egl/EGL/eglplatform.h
index a661736..b594e39 100644
--- a/make/stub_includes/egl/EGL/eglplatform.h
+++ b/make/stub_includes/egl/EGL/eglplatform.h
@@ -97,9 +97,9 @@ typedef Window   EGLNativeWindowType;
 
 #warning "Info: Using generic void pointer for EGLNativeDisplayType, EGLNativeWindowType and EGLNativePixmapType"
 
-typedef void* EGLNativeDisplayType;
-typedef void* EGLNativeWindowType;
-typedef void* EGLNativePixmapType;
+typedef struct __EGLNativeDisplayType* EGLNativeDisplayType;
+typedef struct __EGLNativeWindowType* EGLNativeWindowType;
+typedef struct __EGLNativePixmapType* EGLNativePixmapType;
 
 #endif
 
diff --git a/make/stub_includes/libav/libavcodec/avcodec.h b/make/stub_includes/libav/libavcodec/avcodec.h
new file mode 100644
index 0000000..2451294
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/avcodec.h
@@ -0,0 +1,4761 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVCODEC_H
+#define AVCODEC_AVCODEC_H
+
+/**
+ * @file
+ * external API header
+ */
+
+#include <errno.h>
+#include "libavutil/samplefmt.h"
+#include "libavutil/avutil.h"
+#include "libavutil/cpu.h"
+#include "libavutil/dict.h"
+#include "libavutil/log.h"
+#include "libavutil/pixfmt.h"
+#include "libavutil/rational.h"
+
+#include "libavcodec/version.h"
+/**
+ * @defgroup libavc Encoding/Decoding Library
+ * @{
+ *
+ * @defgroup lavc_decoding Decoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_encoding Encoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_codec Codecs
+ * @{
+ * @defgroup lavc_codec_native Native Codecs
+ * @{
+ * @}
+ * @defgroup lavc_codec_wrappers External library wrappers
+ * @{
+ * @}
+ * @defgroup lavc_codec_hwaccel Hardware Accelerators bridge
+ * @{
+ * @}
+ * @}
+ * @defgroup lavc_internal Internal
+ * @{
+ * @}
+ * @}
+ *
+ */
+
+
+/**
+ * Identify the syntax and semantics of the bitstream.
+ * The principle is roughly:
+ * Two decoders with the same ID can decode the same streams.
+ * Two encoders with the same ID can encode compatible streams.
+ * There may be slight deviations from the principle due to implementation
+ * details.
+ *
+ * If you add a codec ID to this list, add it so that
+ * 1. no value of a existing codec ID changes (that would break ABI),
+ * 2. it is as close as possible to similar codecs.
+ */
+enum CodecID {
+    CODEC_ID_NONE,
+
+    /* video codecs */
+    CODEC_ID_MPEG1VIDEO,
+    CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding
+    CODEC_ID_MPEG2VIDEO_XVMC,
+    CODEC_ID_H261,
+    CODEC_ID_H263,
+    CODEC_ID_RV10,
+    CODEC_ID_RV20,
+    CODEC_ID_MJPEG,
+    CODEC_ID_MJPEGB,
+    CODEC_ID_LJPEG,
+    CODEC_ID_SP5X,
+    CODEC_ID_JPEGLS,
+    CODEC_ID_MPEG4,
+    CODEC_ID_RAWVIDEO,
+    CODEC_ID_MSMPEG4V1,
+    CODEC_ID_MSMPEG4V2,
+    CODEC_ID_MSMPEG4V3,
+    CODEC_ID_WMV1,
+    CODEC_ID_WMV2,
+    CODEC_ID_H263P,
+    CODEC_ID_H263I,
+    CODEC_ID_FLV1,
+    CODEC_ID_SVQ1,
+    CODEC_ID_SVQ3,
+    CODEC_ID_DVVIDEO,
+    CODEC_ID_HUFFYUV,
+    CODEC_ID_CYUV,
+    CODEC_ID_H264,
+    CODEC_ID_INDEO3,
+    CODEC_ID_VP3,
+    CODEC_ID_THEORA,
+    CODEC_ID_ASV1,
+    CODEC_ID_ASV2,
+    CODEC_ID_FFV1,
+    CODEC_ID_4XM,
+    CODEC_ID_VCR1,
+    CODEC_ID_CLJR,
+    CODEC_ID_MDEC,
+    CODEC_ID_ROQ,
+    CODEC_ID_INTERPLAY_VIDEO,
+    CODEC_ID_XAN_WC3,
+    CODEC_ID_XAN_WC4,
+    CODEC_ID_RPZA,
+    CODEC_ID_CINEPAK,
+    CODEC_ID_WS_VQA,
+    CODEC_ID_MSRLE,
+    CODEC_ID_MSVIDEO1,
+    CODEC_ID_IDCIN,
+    CODEC_ID_8BPS,
+    CODEC_ID_SMC,
+    CODEC_ID_FLIC,
+    CODEC_ID_TRUEMOTION1,
+    CODEC_ID_VMDVIDEO,
+    CODEC_ID_MSZH,
+    CODEC_ID_ZLIB,
+    CODEC_ID_QTRLE,
+    CODEC_ID_SNOW,
+    CODEC_ID_TSCC,
+    CODEC_ID_ULTI,
+    CODEC_ID_QDRAW,
+    CODEC_ID_VIXL,
+    CODEC_ID_QPEG,
+    CODEC_ID_PNG,
+    CODEC_ID_PPM,
+    CODEC_ID_PBM,
+    CODEC_ID_PGM,
+    CODEC_ID_PGMYUV,
+    CODEC_ID_PAM,
+    CODEC_ID_FFVHUFF,
+    CODEC_ID_RV30,
+    CODEC_ID_RV40,
+    CODEC_ID_VC1,
+    CODEC_ID_WMV3,
+    CODEC_ID_LOCO,
+    CODEC_ID_WNV1,
+    CODEC_ID_AASC,
+    CODEC_ID_INDEO2,
+    CODEC_ID_FRAPS,
+    CODEC_ID_TRUEMOTION2,
+    CODEC_ID_BMP,
+    CODEC_ID_CSCD,
+    CODEC_ID_MMVIDEO,
+    CODEC_ID_ZMBV,
+    CODEC_ID_AVS,
+    CODEC_ID_SMACKVIDEO,
+    CODEC_ID_NUV,
+    CODEC_ID_KMVC,
+    CODEC_ID_FLASHSV,
+    CODEC_ID_CAVS,
+    CODEC_ID_JPEG2000,
+    CODEC_ID_VMNC,
+    CODEC_ID_VP5,
+    CODEC_ID_VP6,
+    CODEC_ID_VP6F,
+    CODEC_ID_TARGA,
+    CODEC_ID_DSICINVIDEO,
+    CODEC_ID_TIERTEXSEQVIDEO,
+    CODEC_ID_TIFF,
+    CODEC_ID_GIF,
+#if LIBAVCODEC_VERSION_MAJOR == 53
+    CODEC_ID_FFH264,
+#endif
+    CODEC_ID_DXA,
+    CODEC_ID_DNXHD,
+    CODEC_ID_THP,
+    CODEC_ID_SGI,
+    CODEC_ID_C93,
+    CODEC_ID_BETHSOFTVID,
+    CODEC_ID_PTX,
+    CODEC_ID_TXD,
+    CODEC_ID_VP6A,
+    CODEC_ID_AMV,
+    CODEC_ID_VB,
+    CODEC_ID_PCX,
+    CODEC_ID_SUNRAST,
+    CODEC_ID_INDEO4,
+    CODEC_ID_INDEO5,
+    CODEC_ID_MIMIC,
+    CODEC_ID_RL2,
+#if LIBAVCODEC_VERSION_MAJOR == 53
+    CODEC_ID_8SVX_EXP,
+    CODEC_ID_8SVX_FIB,
+#endif
+    CODEC_ID_ESCAPE124,
+    CODEC_ID_DIRAC,
+    CODEC_ID_BFI,
+    CODEC_ID_CMV,
+    CODEC_ID_MOTIONPIXELS,
+    CODEC_ID_TGV,
+    CODEC_ID_TGQ,
+    CODEC_ID_TQI,
+    CODEC_ID_AURA,
+    CODEC_ID_AURA2,
+    CODEC_ID_V210X,
+    CODEC_ID_TMV,
+    CODEC_ID_V210,
+    CODEC_ID_DPX,
+    CODEC_ID_MAD,
+    CODEC_ID_FRWU,
+    CODEC_ID_FLASHSV2,
+    CODEC_ID_CDGRAPHICS,
+    CODEC_ID_R210,
+    CODEC_ID_ANM,
+    CODEC_ID_BINKVIDEO,
+    CODEC_ID_IFF_ILBM,
+    CODEC_ID_IFF_BYTERUN1,
+    CODEC_ID_KGV1,
+    CODEC_ID_YOP,
+    CODEC_ID_VP8,
+    CODEC_ID_PICTOR,
+    CODEC_ID_ANSI,
+    CODEC_ID_A64_MULTI,
+    CODEC_ID_A64_MULTI5,
+    CODEC_ID_R10K,
+    CODEC_ID_MXPEG,
+    CODEC_ID_LAGARITH,
+    CODEC_ID_PRORES,
+    CODEC_ID_JV,
+    CODEC_ID_DFA,
+    CODEC_ID_WMV3IMAGE,
+    CODEC_ID_VC1IMAGE,
+#if LIBAVCODEC_VERSION_MAJOR == 53
+    CODEC_ID_G723_1,
+    CODEC_ID_G729,
+#endif
+    CODEC_ID_UTVIDEO,
+    CODEC_ID_BMV_VIDEO,
+    CODEC_ID_VBLE,
+    CODEC_ID_DXTORY,
+    CODEC_ID_V410,
+
+    /* various PCM "codecs" */
+    CODEC_ID_FIRST_AUDIO = 0x10000,     ///< A dummy id pointing at the start of audio codecs
+    CODEC_ID_PCM_S16LE = 0x10000,
+    CODEC_ID_PCM_S16BE,
+    CODEC_ID_PCM_U16LE,
+    CODEC_ID_PCM_U16BE,
+    CODEC_ID_PCM_S8,
+    CODEC_ID_PCM_U8,
+    CODEC_ID_PCM_MULAW,
+    CODEC_ID_PCM_ALAW,
+    CODEC_ID_PCM_S32LE,
+    CODEC_ID_PCM_S32BE,
+    CODEC_ID_PCM_U32LE,
+    CODEC_ID_PCM_U32BE,
+    CODEC_ID_PCM_S24LE,
+    CODEC_ID_PCM_S24BE,
+    CODEC_ID_PCM_U24LE,
+    CODEC_ID_PCM_U24BE,
+    CODEC_ID_PCM_S24DAUD,
+    CODEC_ID_PCM_ZORK,
+    CODEC_ID_PCM_S16LE_PLANAR,
+    CODEC_ID_PCM_DVD,
+    CODEC_ID_PCM_F32BE,
+    CODEC_ID_PCM_F32LE,
+    CODEC_ID_PCM_F64BE,
+    CODEC_ID_PCM_F64LE,
+    CODEC_ID_PCM_BLURAY,
+    CODEC_ID_PCM_LXF,
+    CODEC_ID_S302M,
+    CODEC_ID_PCM_S8_PLANAR,
+
+    /* various ADPCM codecs */
+    CODEC_ID_ADPCM_IMA_QT = 0x11000,
+    CODEC_ID_ADPCM_IMA_WAV,
+    CODEC_ID_ADPCM_IMA_DK3,
+    CODEC_ID_ADPCM_IMA_DK4,
+    CODEC_ID_ADPCM_IMA_WS,
+    CODEC_ID_ADPCM_IMA_SMJPEG,
+    CODEC_ID_ADPCM_MS,
+    CODEC_ID_ADPCM_4XM,
+    CODEC_ID_ADPCM_XA,
+    CODEC_ID_ADPCM_ADX,
+    CODEC_ID_ADPCM_EA,
+    CODEC_ID_ADPCM_G726,
+    CODEC_ID_ADPCM_CT,
+    CODEC_ID_ADPCM_SWF,
+    CODEC_ID_ADPCM_YAMAHA,
+    CODEC_ID_ADPCM_SBPRO_4,
+    CODEC_ID_ADPCM_SBPRO_3,
+    CODEC_ID_ADPCM_SBPRO_2,
+    CODEC_ID_ADPCM_THP,
+    CODEC_ID_ADPCM_IMA_AMV,
+    CODEC_ID_ADPCM_EA_R1,
+    CODEC_ID_ADPCM_EA_R3,
+    CODEC_ID_ADPCM_EA_R2,
+    CODEC_ID_ADPCM_IMA_EA_SEAD,
+    CODEC_ID_ADPCM_IMA_EA_EACS,
+    CODEC_ID_ADPCM_EA_XAS,
+    CODEC_ID_ADPCM_EA_MAXIS_XA,
+    CODEC_ID_ADPCM_IMA_ISS,
+    CODEC_ID_ADPCM_G722,
+
+    /* AMR */
+    CODEC_ID_AMR_NB = 0x12000,
+    CODEC_ID_AMR_WB,
+
+    /* RealAudio codecs*/
+    CODEC_ID_RA_144 = 0x13000,
+    CODEC_ID_RA_288,
+
+    /* various DPCM codecs */
+    CODEC_ID_ROQ_DPCM = 0x14000,
+    CODEC_ID_INTERPLAY_DPCM,
+    CODEC_ID_XAN_DPCM,
+    CODEC_ID_SOL_DPCM,
+
+    /* audio codecs */
+    CODEC_ID_MP2 = 0x15000,
+    CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3
+    CODEC_ID_AAC,
+    CODEC_ID_AC3,
+    CODEC_ID_DTS,
+    CODEC_ID_VORBIS,
+    CODEC_ID_DVAUDIO,
+    CODEC_ID_WMAV1,
+    CODEC_ID_WMAV2,
+    CODEC_ID_MACE3,
+    CODEC_ID_MACE6,
+    CODEC_ID_VMDAUDIO,
+#if LIBAVCODEC_VERSION_MAJOR == 53
+    CODEC_ID_SONIC,
+    CODEC_ID_SONIC_LS,
+#endif
+    CODEC_ID_FLAC,
+    CODEC_ID_MP3ADU,
+    CODEC_ID_MP3ON4,
+    CODEC_ID_SHORTEN,
+    CODEC_ID_ALAC,
+    CODEC_ID_WESTWOOD_SND1,
+    CODEC_ID_GSM, ///< as in Berlin toast format
+    CODEC_ID_QDM2,
+    CODEC_ID_COOK,
+    CODEC_ID_TRUESPEECH,
+    CODEC_ID_TTA,
+    CODEC_ID_SMACKAUDIO,
+    CODEC_ID_QCELP,
+    CODEC_ID_WAVPACK,
+    CODEC_ID_DSICINAUDIO,
+    CODEC_ID_IMC,
+    CODEC_ID_MUSEPACK7,
+    CODEC_ID_MLP,
+    CODEC_ID_GSM_MS, /* as found in WAV */
+    CODEC_ID_ATRAC3,
+    CODEC_ID_VOXWARE,
+    CODEC_ID_APE,
+    CODEC_ID_NELLYMOSER,
+    CODEC_ID_MUSEPACK8,
+    CODEC_ID_SPEEX,
+    CODEC_ID_WMAVOICE,
+    CODEC_ID_WMAPRO,
+    CODEC_ID_WMALOSSLESS,
+    CODEC_ID_ATRAC3P,
+    CODEC_ID_EAC3,
+    CODEC_ID_SIPR,
+    CODEC_ID_MP1,
+    CODEC_ID_TWINVQ,
+    CODEC_ID_TRUEHD,
+    CODEC_ID_MP4ALS,
+    CODEC_ID_ATRAC1,
+    CODEC_ID_BINKAUDIO_RDFT,
+    CODEC_ID_BINKAUDIO_DCT,
+    CODEC_ID_AAC_LATM,
+    CODEC_ID_QDMC,
+    CODEC_ID_CELT,
+#if LIBAVCODEC_VERSION_MAJOR > 53
+    CODEC_ID_G723_1,
+    CODEC_ID_G729,
+    CODEC_ID_8SVX_EXP,
+    CODEC_ID_8SVX_FIB,
+#endif
+    CODEC_ID_BMV_AUDIO,
+
+    /* subtitle codecs */
+    CODEC_ID_FIRST_SUBTITLE = 0x17000,          ///< A dummy ID pointing at the start of subtitle codecs.
+    CODEC_ID_DVD_SUBTITLE = 0x17000,
+    CODEC_ID_DVB_SUBTITLE,
+    CODEC_ID_TEXT,  ///< raw UTF-8 text
+    CODEC_ID_XSUB,
+    CODEC_ID_SSA,
+    CODEC_ID_MOV_TEXT,
+    CODEC_ID_HDMV_PGS_SUBTITLE,
+    CODEC_ID_DVB_TELETEXT,
+    CODEC_ID_SRT,
+
+    /* other specific kind of codecs (generally used for attachments) */
+    CODEC_ID_FIRST_UNKNOWN = 0x18000,           ///< A dummy ID pointing at the start of various fake codecs.
+    CODEC_ID_TTF = 0x18000,
+
+    CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like CODEC_ID_NONE) but lavf should attempt to identify it
+
+    CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS
+                                * stream (only used by libavformat) */
+    CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems
+                                * stream (only used by libavformat) */
+    CODEC_ID_FFMETADATA = 0x21000,   ///< Dummy codec for streams containing only metadata information.
+};
+
+#if FF_API_OLD_SAMPLE_FMT
+#define SampleFormat AVSampleFormat
+
+#define SAMPLE_FMT_NONE AV_SAMPLE_FMT_NONE
+#define SAMPLE_FMT_U8   AV_SAMPLE_FMT_U8
+#define SAMPLE_FMT_S16  AV_SAMPLE_FMT_S16
+#define SAMPLE_FMT_S32  AV_SAMPLE_FMT_S32
+#define SAMPLE_FMT_FLT  AV_SAMPLE_FMT_FLT
+#define SAMPLE_FMT_DBL  AV_SAMPLE_FMT_DBL
+#define SAMPLE_FMT_NB   AV_SAMPLE_FMT_NB
+#endif
+
+#if FF_API_OLD_AUDIOCONVERT
+#include "libavutil/audioconvert.h"
+
+/* Audio channel masks */
+#define CH_FRONT_LEFT            AV_CH_FRONT_LEFT
+#define CH_FRONT_RIGHT           AV_CH_FRONT_RIGHT
+#define CH_FRONT_CENTER          AV_CH_FRONT_CENTER
+#define CH_LOW_FREQUENCY         AV_CH_LOW_FREQUENCY
+#define CH_BACK_LEFT             AV_CH_BACK_LEFT
+#define CH_BACK_RIGHT            AV_CH_BACK_RIGHT
+#define CH_FRONT_LEFT_OF_CENTER  AV_CH_FRONT_LEFT_OF_CENTER
+#define CH_FRONT_RIGHT_OF_CENTER AV_CH_FRONT_RIGHT_OF_CENTER
+#define CH_BACK_CENTER           AV_CH_BACK_CENTER
+#define CH_SIDE_LEFT             AV_CH_SIDE_LEFT
+#define CH_SIDE_RIGHT            AV_CH_SIDE_RIGHT
+#define CH_TOP_CENTER            AV_CH_TOP_CENTER
+#define CH_TOP_FRONT_LEFT        AV_CH_TOP_FRONT_LEFT
+#define CH_TOP_FRONT_CENTER      AV_CH_TOP_FRONT_CENTER
+#define CH_TOP_FRONT_RIGHT       AV_CH_TOP_FRONT_RIGHT
+#define CH_TOP_BACK_LEFT         AV_CH_TOP_BACK_LEFT
+#define CH_TOP_BACK_CENTER       AV_CH_TOP_BACK_CENTER
+#define CH_TOP_BACK_RIGHT        AV_CH_TOP_BACK_RIGHT
+#define CH_STEREO_LEFT           AV_CH_STEREO_LEFT
+#define CH_STEREO_RIGHT          AV_CH_STEREO_RIGHT
+
+/** Channel mask value used for AVCodecContext.request_channel_layout
+    to indicate that the user requests the channel order of the decoder output
+    to be the native codec channel order. */
+#define CH_LAYOUT_NATIVE         AV_CH_LAYOUT_NATIVE
+
+/* Audio channel convenience macros */
+#define CH_LAYOUT_MONO           AV_CH_LAYOUT_MONO
+#define CH_LAYOUT_STEREO         AV_CH_LAYOUT_STEREO
+#define CH_LAYOUT_2_1            AV_CH_LAYOUT_2_1
+#define CH_LAYOUT_SURROUND       AV_CH_LAYOUT_SURROUND
+#define CH_LAYOUT_4POINT0        AV_CH_LAYOUT_4POINT0
+#define CH_LAYOUT_2_2            AV_CH_LAYOUT_2_2
+#define CH_LAYOUT_QUAD           AV_CH_LAYOUT_QUAD
+#define CH_LAYOUT_5POINT0        AV_CH_LAYOUT_5POINT0
+#define CH_LAYOUT_5POINT1        AV_CH_LAYOUT_5POINT1
+#define CH_LAYOUT_5POINT0_BACK   AV_CH_LAYOUT_5POINT0_BACK
+#define CH_LAYOUT_5POINT1_BACK   AV_CH_LAYOUT_5POINT1_BACK
+#define CH_LAYOUT_7POINT0        AV_CH_LAYOUT_7POINT0
+#define CH_LAYOUT_7POINT1        AV_CH_LAYOUT_7POINT1
+#define CH_LAYOUT_7POINT1_WIDE   AV_CH_LAYOUT_7POINT1_WIDE
+#define CH_LAYOUT_STEREO_DOWNMIX AV_CH_LAYOUT_STEREO_DOWNMIX
+#endif
+
+#if FF_API_OLD_DECODE_AUDIO
+/* in bytes */
+#define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
+#endif
+
+/**
+ * Required number of additionally allocated bytes at the end of the input bitstream for decoding.
+ * This is mainly needed because some optimized bitstream readers read
+ * 32 or 64 bit at once and could read over the end.<br>
+ * Note: If the first 23 bits of the additional bytes are not 0, then damaged
+ * MPEG bitstreams could cause overread and segfault.
+ */
+#define FF_INPUT_BUFFER_PADDING_SIZE 8
+
+/**
+ * minimum encoding buffer size
+ * Used to avoid some checks during header writing.
+ */
+#define FF_MIN_BUFFER_SIZE 16384
+
+
+/**
+ * motion estimation type.
+ */
+enum Motion_Est_ID {
+    ME_ZERO = 1,    ///< no search, that is use 0,0 vector whenever one is needed
+    ME_FULL,
+    ME_LOG,
+    ME_PHODS,
+    ME_EPZS,        ///< enhanced predictive zonal search
+    ME_X1,          ///< reserved for experiments
+    ME_HEX,         ///< hexagon based search
+    ME_UMH,         ///< uneven multi-hexagon search
+    ME_ITER,        ///< iterative search
+    ME_TESA,        ///< transformed exhaustive search algorithm
+};
+
+enum AVDiscard{
+    /* We leave some space between them for extensions (drop some
+     * keyframes for intra-only or drop just some bidir frames). */
+    AVDISCARD_NONE   =-16, ///< discard nothing
+    AVDISCARD_DEFAULT=  0, ///< discard useless packets like 0 size packets in avi
+    AVDISCARD_NONREF =  8, ///< discard all non reference
+    AVDISCARD_BIDIR  = 16, ///< discard all bidirectional frames
+    AVDISCARD_NONKEY = 32, ///< discard all frames except keyframes
+    AVDISCARD_ALL    = 48, ///< discard all
+};
+
+enum AVColorPrimaries{
+    AVCOL_PRI_BT709      =1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
+    AVCOL_PRI_UNSPECIFIED=2,
+    AVCOL_PRI_BT470M     =4,
+    AVCOL_PRI_BT470BG    =5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
+    AVCOL_PRI_SMPTE170M  =6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
+    AVCOL_PRI_SMPTE240M  =7, ///< functionally identical to above
+    AVCOL_PRI_FILM       =8,
+    AVCOL_PRI_NB           , ///< Not part of ABI
+};
+
+enum AVColorTransferCharacteristic{
+    AVCOL_TRC_BT709      =1, ///< also ITU-R BT1361
+    AVCOL_TRC_UNSPECIFIED=2,
+    AVCOL_TRC_GAMMA22    =4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
+    AVCOL_TRC_GAMMA28    =5, ///< also ITU-R BT470BG
+    AVCOL_TRC_NB           , ///< Not part of ABI
+};
+
+enum AVColorSpace{
+    AVCOL_SPC_RGB        =0,
+    AVCOL_SPC_BT709      =1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
+    AVCOL_SPC_UNSPECIFIED=2,
+    AVCOL_SPC_FCC        =4,
+    AVCOL_SPC_BT470BG    =5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
+    AVCOL_SPC_SMPTE170M  =6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above
+    AVCOL_SPC_SMPTE240M  =7,
+    AVCOL_SPC_NB           , ///< Not part of ABI
+};
+
+enum AVColorRange{
+    AVCOL_RANGE_UNSPECIFIED=0,
+    AVCOL_RANGE_MPEG       =1, ///< the normal 219*2^(n-8) "MPEG" YUV ranges
+    AVCOL_RANGE_JPEG       =2, ///< the normal     2^n-1   "JPEG" YUV ranges
+    AVCOL_RANGE_NB           , ///< Not part of ABI
+};
+
+/**
+ *  X   X      3 4 X      X are luma samples,
+ *             1 2        1-6 are possible chroma positions
+ *  X   X      5 6 X      0 is undefined/unknown position
+ */
+enum AVChromaLocation{
+    AVCHROMA_LOC_UNSPECIFIED=0,
+    AVCHROMA_LOC_LEFT       =1, ///< mpeg2/4, h264 default
+    AVCHROMA_LOC_CENTER     =2, ///< mpeg1, jpeg, h263
+    AVCHROMA_LOC_TOPLEFT    =3, ///< DV
+    AVCHROMA_LOC_TOP        =4,
+    AVCHROMA_LOC_BOTTOMLEFT =5,
+    AVCHROMA_LOC_BOTTOM     =6,
+    AVCHROMA_LOC_NB           , ///< Not part of ABI
+};
+
+#if FF_API_FLAC_GLOBAL_OPTS
+/**
+ * LPC analysis type
+ */
+enum AVLPCType {
+    AV_LPC_TYPE_DEFAULT     = -1, ///< use the codec default LPC type
+    AV_LPC_TYPE_NONE        =  0, ///< do not use LPC prediction or use all zero coefficients
+    AV_LPC_TYPE_FIXED       =  1, ///< fixed LPC coefficients
+    AV_LPC_TYPE_LEVINSON    =  2, ///< Levinson-Durbin recursion
+    AV_LPC_TYPE_CHOLESKY    =  3, ///< Cholesky factorization
+    AV_LPC_TYPE_NB              , ///< Not part of ABI
+};
+#endif
+
+enum AVAudioServiceType {
+    AV_AUDIO_SERVICE_TYPE_MAIN              = 0,
+    AV_AUDIO_SERVICE_TYPE_EFFECTS           = 1,
+    AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2,
+    AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED  = 3,
+    AV_AUDIO_SERVICE_TYPE_DIALOGUE          = 4,
+    AV_AUDIO_SERVICE_TYPE_COMMENTARY        = 5,
+    AV_AUDIO_SERVICE_TYPE_EMERGENCY         = 6,
+    AV_AUDIO_SERVICE_TYPE_VOICE_OVER        = 7,
+    AV_AUDIO_SERVICE_TYPE_KARAOKE           = 8,
+    AV_AUDIO_SERVICE_TYPE_NB                   , ///< Not part of ABI
+};
+
+typedef struct RcOverride{
+    int start_frame;
+    int end_frame;
+    int qscale; // If this is 0 then quality_factor will be used instead.
+    float quality_factor;
+} RcOverride;
+
+#define FF_MAX_B_FRAMES 16
+
+/* encoding support
+   These flags can be passed in AVCodecContext.flags before initialization.
+   Note: Not everything is supported yet.
+*/
+
+#define CODEC_FLAG_QSCALE 0x0002  ///< Use fixed qscale.
+#define CODEC_FLAG_4MV    0x0004  ///< 4 MV per MB allowed / advanced prediction for H.263.
+#define CODEC_FLAG_QPEL   0x0010  ///< Use qpel MC.
+#define CODEC_FLAG_GMC    0x0020  ///< Use GMC.
+#define CODEC_FLAG_MV0    0x0040  ///< Always try a MB with MV=<0,0>.
+/**
+ * The parent program guarantees that the input for B-frames containing
+ * streams is not written to for at least s->max_b_frames+1 frames, if
+ * this is not set the input will be copied.
+ */
+#define CODEC_FLAG_INPUT_PRESERVED 0x0100
+#define CODEC_FLAG_PASS1           0x0200   ///< Use internal 2pass ratecontrol in first pass mode.
+#define CODEC_FLAG_PASS2           0x0400   ///< Use internal 2pass ratecontrol in second pass mode.
+#define CODEC_FLAG_GRAY            0x2000   ///< Only decode/encode grayscale.
+#define CODEC_FLAG_EMU_EDGE        0x4000   ///< Don't draw edges.
+#define CODEC_FLAG_PSNR            0x8000   ///< error[?] variables will be set during encoding.
+#define CODEC_FLAG_TRUNCATED       0x00010000 /** Input bitstream might be truncated at a random
+                                                  location instead of only at frame boundaries. */
+#define CODEC_FLAG_NORMALIZE_AQP  0x00020000 ///< Normalize adaptive quantization.
+#define CODEC_FLAG_INTERLACED_DCT 0x00040000 ///< Use interlaced DCT.
+#define CODEC_FLAG_LOW_DELAY      0x00080000 ///< Force low delay.
+#define CODEC_FLAG_GLOBAL_HEADER  0x00400000 ///< Place global headers in extradata instead of every keyframe.
+#define CODEC_FLAG_BITEXACT       0x00800000 ///< Use only bitexact stuff (except (I)DCT).
+/* Fx : Flag for h263+ extra options */
+#define CODEC_FLAG_AC_PRED        0x01000000 ///< H.263 advanced intra coding / MPEG-4 AC prediction
+#define CODEC_FLAG_CBP_RD         0x04000000 ///< Use rate distortion optimization for cbp.
+#define CODEC_FLAG_QP_RD          0x08000000 ///< Use rate distortion optimization for qp selectioon.
+#define CODEC_FLAG_LOOP_FILTER    0x00000800 ///< loop filter
+#define CODEC_FLAG_INTERLACED_ME  0x20000000 ///< interlaced motion estimation
+#define CODEC_FLAG_CLOSED_GOP     0x80000000
+#define CODEC_FLAG2_FAST          0x00000001 ///< Allow non spec compliant speedup tricks.
+#define CODEC_FLAG2_STRICT_GOP    0x00000002 ///< Strictly enforce GOP size.
+#define CODEC_FLAG2_NO_OUTPUT     0x00000004 ///< Skip bitstream encoding.
+#define CODEC_FLAG2_LOCAL_HEADER  0x00000008 ///< Place global headers at every keyframe instead of in extradata.
+#define CODEC_FLAG2_SKIP_RD       0x00004000 ///< RD optimal MB level residual skipping
+#define CODEC_FLAG2_CHUNKS        0x00008000 ///< Input bitstream might be truncated at a packet boundaries instead of only at frame boundaries.
+/**
+ * @defgroup deprecated_flags Deprecated codec flags
+ * Use corresponding private codec options instead.
+ * @{
+ */
+#if FF_API_MPEGVIDEO_GLOBAL_OPTS
+#define CODEC_FLAG_OBMC           0x00000001 ///< OBMC
+#define CODEC_FLAG_H263P_AIV      0x00000008 ///< H.263 alternative inter VLC
+#define CODEC_FLAG_PART   0x0080  ///< Use data partitioning.
+#define CODEC_FLAG_ALT_SCAN       0x00100000 ///< Use alternate scan.
+#define CODEC_FLAG_H263P_UMV      0x02000000 ///< unlimited motion vector
+#define CODEC_FLAG_H263P_SLICE_STRUCT 0x10000000
+#define CODEC_FLAG_SVCD_SCAN_OFFSET 0x40000000 ///< Will reserve space for SVCD scan offset user data.
+#define CODEC_FLAG2_INTRA_VLC     0x00000800 ///< Use MPEG-2 intra VLC table.
+#define CODEC_FLAG2_DROP_FRAME_TIMECODE 0x00002000 ///< timecode is in drop frame format.
+#define CODEC_FLAG2_NON_LINEAR_QUANT 0x00010000 ///< Use MPEG-2 nonlinear quantizer.
+#endif
+#if FF_API_MJPEG_GLOBAL_OPTS
+#define CODEC_FLAG_EXTERN_HUFF     0x1000   ///< Use external Huffman table (for MJPEG).
+#endif
+#if FF_API_X264_GLOBAL_OPTS
+#define CODEC_FLAG2_BPYRAMID      0x00000010 ///< H.264 allow B-frames to be used as references.
+#define CODEC_FLAG2_WPRED         0x00000020 ///< H.264 weighted biprediction for B-frames
+#define CODEC_FLAG2_MIXED_REFS    0x00000040 ///< H.264 one reference per partition, as opposed to one reference per macroblock
+#define CODEC_FLAG2_8X8DCT        0x00000080 ///< H.264 high profile 8x8 transform
+#define CODEC_FLAG2_FASTPSKIP     0x00000100 ///< H.264 fast pskip
+#define CODEC_FLAG2_AUD           0x00000200 ///< H.264 access unit delimiters
+#define CODEC_FLAG2_BRDO          0x00000400 ///< B-frame rate-distortion optimization
+#define CODEC_FLAG2_MBTREE        0x00040000 ///< Use macroblock tree ratecontrol (x264 only)
+#define CODEC_FLAG2_PSY           0x00080000 ///< Use psycho visual optimizations.
+#define CODEC_FLAG2_SSIM          0x00100000 ///< Compute SSIM during encoding, error[] values are undefined.
+#define CODEC_FLAG2_INTRA_REFRESH 0x00200000 ///< Use periodic insertion of intra blocks instead of keyframes.
+#endif
+#if FF_API_SNOW_GLOBAL_OPTS
+#define CODEC_FLAG2_MEMC_ONLY     0x00001000 ///< Only do ME/MC (I frames -> ref, P frame -> ME+MC).
+#endif
+#if FF_API_LAME_GLOBAL_OPTS
+#define CODEC_FLAG2_BIT_RESERVOIR 0x00020000 ///< Use a bit reservoir when encoding if possible
+#endif
+/**
+ * @}
+ */
+
+/* Unsupported options :
+ *              Syntax Arithmetic coding (SAC)
+ *              Reference Picture Selection
+ *              Independent Segment Decoding */
+/* /Fx */
+/* codec capabilities */
+
+#define CODEC_CAP_DRAW_HORIZ_BAND 0x0001 ///< Decoder can use draw_horiz_band callback.
+/**
+ * Codec uses get_buffer() for allocating buffers and supports custom allocators.
+ * If not set, it might not use get_buffer() at all or use operations that
+ * assume the buffer was allocated by avcodec_default_get_buffer.
+ */
+#define CODEC_CAP_DR1             0x0002
+#if FF_API_PARSE_FRAME
+/* If 'parse_only' field is true, then avcodec_parse_frame() can be used. */
+#define CODEC_CAP_PARSE_ONLY      0x0004
+#endif
+#define CODEC_CAP_TRUNCATED       0x0008
+/* Codec can export data for HW decoding (XvMC). */
+#define CODEC_CAP_HWACCEL         0x0010
+/**
+ * Encoder or decoder requires flushing with NULL input at the end in order to
+ * give the complete and correct output.
+ *
+ * NOTE: If this flag is not set, the codec is guaranteed to never be fed with
+ *       with NULL data. The user can still send NULL data to the public encode
+ *       or decode function, but libavcodec will not pass it along to the codec
+ *       unless this flag is set.
+ *
+ * Decoders:
+ * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to get the delayed data until the decoder no longer
+ * returns frames.
+ *
+ * Encoders:
+ * The encoder needs to be fed with NULL data at the end of encoding until the
+ * encoder no longer returns data.
+ *
+ * NOTE: For encoders implementing the AVCodec.encode2() function, setting this
+ *       flag also means that the encoder must set the pts and duration for
+ *       each output packet. If this flag is not set, the pts and duration will
+ *       be determined by libavcodec from the input frame.
+ */
+#define CODEC_CAP_DELAY           0x0020
+/**
+ * Codec can be fed a final frame with a smaller size.
+ * This can be used to prevent truncation of the last audio samples.
+ */
+#define CODEC_CAP_SMALL_LAST_FRAME 0x0040
+/**
+ * Codec can export data for HW decoding (VDPAU).
+ */
+#define CODEC_CAP_HWACCEL_VDPAU    0x0080
+/**
+ * Codec can output multiple frames per AVPacket
+ * Normally demuxers return one frame at a time, demuxers which do not do
+ * are connected to a parser to split what they return into proper frames.
+ * This flag is reserved to the very rare category of codecs which have a
+ * bitstream that cannot be split into frames without timeconsuming
+ * operations like full decoding. Demuxers carring such bitstreams thus
+ * may return multiple frames in a packet. This has many disadvantages like
+ * prohibiting stream copy in many cases thus it should only be considered
+ * as a last resort.
+ */
+#define CODEC_CAP_SUBFRAMES        0x0100
+/**
+ * Codec is experimental and is thus avoided in favor of non experimental
+ * encoders
+ */
+#define CODEC_CAP_EXPERIMENTAL     0x0200
+/**
+ * Codec should fill in channel configuration and samplerate instead of container
+ */
+#define CODEC_CAP_CHANNEL_CONF     0x0400
+/**
+ * Codec is able to deal with negative linesizes
+ */
+#define CODEC_CAP_NEG_LINESIZES    0x0800
+/**
+ * Codec supports frame-level multithreading.
+ */
+#define CODEC_CAP_FRAME_THREADS    0x1000
+/**
+ * Codec supports slice-based (or partition-based) multithreading.
+ */
+#define CODEC_CAP_SLICE_THREADS    0x2000
+/**
+ * Codec supports changed parameters at any point.
+ */
+#define CODEC_CAP_PARAM_CHANGE     0x4000
+/**
+ * Codec supports avctx->thread_count == 0 (auto).
+ */
+#define CODEC_CAP_AUTO_THREADS     0x8000
+/**
+ * Audio encoder supports receiving a different number of samples in each call.
+ */
+#define CODEC_CAP_VARIABLE_FRAME_SIZE 0x10000
+
+//The following defines may change, don't expect compatibility if you use them.
+#define MB_TYPE_INTRA4x4   0x0001
+#define MB_TYPE_INTRA16x16 0x0002 //FIXME H.264-specific
+#define MB_TYPE_INTRA_PCM  0x0004 //FIXME H.264-specific
+#define MB_TYPE_16x16      0x0008
+#define MB_TYPE_16x8       0x0010
+#define MB_TYPE_8x16       0x0020
+#define MB_TYPE_8x8        0x0040
+#define MB_TYPE_INTERLACED 0x0080
+#define MB_TYPE_DIRECT2    0x0100 //FIXME
+#define MB_TYPE_ACPRED     0x0200
+#define MB_TYPE_GMC        0x0400
+#define MB_TYPE_SKIP       0x0800
+#define MB_TYPE_P0L0       0x1000
+#define MB_TYPE_P1L0       0x2000
+#define MB_TYPE_P0L1       0x4000
+#define MB_TYPE_P1L1       0x8000
+#define MB_TYPE_L0         (MB_TYPE_P0L0 | MB_TYPE_P1L0)
+#define MB_TYPE_L1         (MB_TYPE_P0L1 | MB_TYPE_P1L1)
+#define MB_TYPE_L0L1       (MB_TYPE_L0   | MB_TYPE_L1)
+#define MB_TYPE_QUANT      0x00010000
+#define MB_TYPE_CBP        0x00020000
+//Note bits 24-31 are reserved for codec specific use (h264 ref0, mpeg1 0mv, ...)
+
+/**
+ * Pan Scan area.
+ * This specifies the area which should be displayed.
+ * Note there may be multiple such areas for one frame.
+ */
+typedef struct AVPanScan{
+    /**
+     * id
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int id;
+
+    /**
+     * width and height in 1/16 pel
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int width;
+    int height;
+
+    /**
+     * position of the top left corner in 1/16 pel for up to 3 fields/frames
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int16_t position[3][2];
+}AVPanScan;
+
+#define FF_QSCALE_TYPE_MPEG1 0
+#define FF_QSCALE_TYPE_MPEG2 1
+#define FF_QSCALE_TYPE_H264  2
+#define FF_QSCALE_TYPE_VP56  3
+
+#define FF_BUFFER_TYPE_INTERNAL 1
+#define FF_BUFFER_TYPE_USER     2 ///< direct rendering buffers (image is (de)allocated by user)
+#define FF_BUFFER_TYPE_SHARED   4 ///< Buffer from somewhere else; don't deallocate image (data/base), all other tables are not shared.
+#define FF_BUFFER_TYPE_COPY     8 ///< Just a (modified) copy of some other buffer, don't deallocate anything.
+
+#if FF_API_OLD_FF_PICT_TYPES
+/* DEPRECATED, directly use the AV_PICTURE_TYPE_* enum values */
+#define FF_I_TYPE  AV_PICTURE_TYPE_I  ///< Intra
+#define FF_P_TYPE  AV_PICTURE_TYPE_P  ///< Predicted
+#define FF_B_TYPE  AV_PICTURE_TYPE_B  ///< Bi-dir predicted
+#define FF_S_TYPE  AV_PICTURE_TYPE_S  ///< S(GMC)-VOP MPEG4
+#define FF_SI_TYPE AV_PICTURE_TYPE_SI ///< Switching Intra
+#define FF_SP_TYPE AV_PICTURE_TYPE_SP ///< Switching Predicted
+#define FF_BI_TYPE AV_PICTURE_TYPE_BI
+#endif
+
+#define FF_BUFFER_HINTS_VALID    0x01 // Buffer hints value is meaningful (if 0 ignore).
+#define FF_BUFFER_HINTS_READABLE 0x02 // Codec will read from buffer.
+#define FF_BUFFER_HINTS_PRESERVE 0x04 // User must not alter buffer content.
+#define FF_BUFFER_HINTS_REUSABLE 0x08 // Codec will reuse the buffer (update).
+
+enum AVPacketSideDataType {
+    AV_PKT_DATA_PALETTE,
+    AV_PKT_DATA_NEW_EXTRADATA,
+    AV_PKT_DATA_PARAM_CHANGE,
+};
+
+typedef struct AVPacket {
+    /**
+     * Presentation timestamp in AVStream->time_base units; the time at which
+     * the decompressed packet will be presented to the user.
+     * Can be AV_NOPTS_VALUE if it is not stored in the file.
+     * pts MUST be larger or equal to dts as presentation cannot happen before
+     * decompression, unless one wants to view hex dumps. Some formats misuse
+     * the terms dts and pts/cts to mean something different. Such timestamps
+     * must be converted to true pts/dts before they are stored in AVPacket.
+     */
+    int64_t pts;
+    /**
+     * Decompression timestamp in AVStream->time_base units; the time at which
+     * the packet is decompressed.
+     * Can be AV_NOPTS_VALUE if it is not stored in the file.
+     */
+    int64_t dts;
+    uint8_t *data;
+    int   size;
+    int   stream_index;
+    /**
+     * A combination of AV_PKT_FLAG values
+     */
+    int   flags;
+    /**
+     * Additional packet data that can be provided by the container.
+     * Packet can contain several types of side information.
+     */
+    struct {
+        uint8_t *data;
+        int      size;
+        enum AVPacketSideDataType type;
+    } *side_data;
+    int side_data_elems;
+
+    /**
+     * Duration of this packet in AVStream->time_base units, 0 if unknown.
+     * Equals next_pts - this_pts in presentation order.
+     */
+    int   duration;
+    void  (*destruct)(struct AVPacket *);
+    void  *priv;
+    int64_t pos;                            ///< byte position in stream, -1 if unknown
+
+    /**
+     * Time difference in AVStream->time_base units from the pts of this
+     * packet to the point at which the output from the decoder has converged
+     * independent from the availability of previous frames. That is, the
+     * frames are virtually identical no matter if decoding started from
+     * the very first frame or from this keyframe.
+     * Is AV_NOPTS_VALUE if unknown.
+     * This field is not the display duration of the current packet.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
+     *
+     * The purpose of this field is to allow seeking in streams that have no
+     * keyframes in the conventional sense. It corresponds to the
+     * recovery point SEI in H.264 and match_time_delta in NUT. It is also
+     * essential for some types of subtitle streams to ensure that all
+     * subtitles are correctly displayed after seeking.
+     */
+    int64_t convergence_duration;
+} AVPacket;
+#define AV_PKT_FLAG_KEY     0x0001 ///< The packet contains a keyframe
+#define AV_PKT_FLAG_CORRUPT 0x0002 ///< The packet content is corrupted
+
+/**
+ * An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows:
+ * u32le param_flags
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT)
+ *     s32le channel_count
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT)
+ *     u64le channel_layout
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE)
+ *     s32le sample_rate
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS)
+ *     s32le width
+ *     s32le height
+ */
+
+enum AVSideDataParamChangeFlags {
+    AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT  = 0x0001,
+    AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT = 0x0002,
+    AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE    = 0x0004,
+    AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS     = 0x0008,
+};
+
+/**
+ * Audio Video Frame.
+ * New fields can be added to the end of AVFRAME with minor version
+ * bumps. Removal, reordering and changes to existing fields require
+ * a major version bump.
+ * sizeof(AVFrame) must not be used outside libav*.
+ */
+typedef struct AVFrame {
+#if FF_API_DATA_POINTERS
+#define AV_NUM_DATA_POINTERS 4
+#else
+#define AV_NUM_DATA_POINTERS 8
+#endif
+    /**
+     * pointer to the picture/channel planes.
+     * This might be different from the first allocated byte
+     * - encoding: Set by user
+     * - decoding: set by AVCodecContext.get_buffer()
+     */
+    uint8_t *data[AV_NUM_DATA_POINTERS];
+
+    /**
+     * Size, in bytes, of the data for each picture/channel plane.
+     *
+     * For audio, only linesize[0] may be set. For planar audio, each channel
+     * plane must be the same size.
+     *
+     * - encoding: Set by user (video only)
+     * - decoding: set by AVCodecContext.get_buffer()
+     */
+    int linesize[AV_NUM_DATA_POINTERS];
+
+    /**
+     * pointer to the first allocated byte of the picture. Can be used in get_buffer/release_buffer.
+     * This isn't used by libavcodec unless the default get/release_buffer() is used.
+     * - encoding:
+     * - decoding:
+     */
+    uint8_t *base[AV_NUM_DATA_POINTERS];
+    /**
+     * 1 -> keyframe, 0-> not
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int key_frame;
+
+    /**
+     * Picture type of the frame, see ?_TYPE below.
+     * - encoding: Set by libavcodec. for coded_picture (and set by user for input).
+     * - decoding: Set by libavcodec.
+     */
+    enum AVPictureType pict_type;
+
+    /**
+     * presentation timestamp in time_base units (time when frame should be shown to user)
+     * If AV_NOPTS_VALUE then frame_rate = 1/time_base will be assumed.
+     * - encoding: MUST be set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int64_t pts;
+
+    /**
+     * picture number in bitstream order
+     * - encoding: set by
+     * - decoding: Set by libavcodec.
+     */
+    int coded_picture_number;
+    /**
+     * picture number in display order
+     * - encoding: set by
+     * - decoding: Set by libavcodec.
+     */
+    int display_picture_number;
+
+    /**
+     * quality (between 1 (good) and FF_LAMBDA_MAX (bad))
+     * - encoding: Set by libavcodec. for coded_picture (and set by user for input).
+     * - decoding: Set by libavcodec.
+     */
+    int quality;
+
+#if FF_API_AVFRAME_AGE
+    /**
+     * @deprecated unused
+     */
+    attribute_deprecated int age;
+#endif
+
+    /**
+     * is this picture used as reference
+     * The values for this are the same as the MpegEncContext.picture_structure
+     * variable, that is 1->top field, 2->bottom field, 3->frame/both fields.
+     * Set to 4 for delayed, non-reference frames.
+     * - encoding: unused
+     * - decoding: Set by libavcodec. (before get_buffer() call)).
+     */
+    int reference;
+
+    /**
+     * QP table
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    int8_t *qscale_table;
+    /**
+     * QP store stride
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    int qstride;
+
+    /**
+     * mbskip_table[mb]>=1 if MB didn't change
+     * stride= mb_width = (width+15)>>4
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    uint8_t *mbskip_table;
+
+    /**
+     * motion vector table
+     * @code
+     * example:
+     * int mv_sample_log2= 4 - motion_subsample_log2;
+     * int mb_width= (width+15)>>4;
+     * int mv_stride= (mb_width << mv_sample_log2) + 1;
+     * motion_val[direction][x + y*mv_stride][0->mv_x, 1->mv_y];
+     * @endcode
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int16_t (*motion_val[2])[2];
+
+    /**
+     * macroblock type table
+     * mb_type_base + mb_width + 2
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    uint32_t *mb_type;
+
+    /**
+     * log2 of the size of the block which a single vector in motion_val represents:
+     * (4->16x16, 3->8x8, 2-> 4x4, 1-> 2x2)
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    uint8_t motion_subsample_log2;
+
+    /**
+     * for some private data of the user
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    void *opaque;
+
+    /**
+     * error
+     * - encoding: Set by libavcodec. if flags&CODEC_FLAG_PSNR.
+     * - decoding: unused
+     */
+    uint64_t error[AV_NUM_DATA_POINTERS];
+
+    /**
+     * type of the buffer (to keep track of who has to deallocate data[*])
+     * - encoding: Set by the one who allocates it.
+     * - decoding: Set by the one who allocates it.
+     * Note: User allocated (direct rendering) & internal buffers cannot coexist currently.
+     */
+    int type;
+
+    /**
+     * When decoding, this signals how much the picture must be delayed.
+     * extra_delay = repeat_pict / (2*fps)
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    int repeat_pict;
+
+    /**
+     *
+     */
+    int qscale_type;
+
+    /**
+     * The content of the picture is interlaced.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec. (default 0)
+     */
+    int interlaced_frame;
+
+    /**
+     * If the content is interlaced, is top field displayed first.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int top_field_first;
+
+    /**
+     * Pan scan.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVPanScan *pan_scan;
+
+    /**
+     * Tell user application that palette has changed from previous frame.
+     * - encoding: ??? (no palette-enabled encoder yet)
+     * - decoding: Set by libavcodec. (default 0).
+     */
+    int palette_has_changed;
+
+    /**
+     * codec suggestion on buffer type if != 0
+     * - encoding: unused
+     * - decoding: Set by libavcodec. (before get_buffer() call)).
+     */
+    int buffer_hints;
+
+    /**
+     * DCT coefficients
+     * - encoding: unused
+     * - decoding: Set by libavcodec.
+     */
+    short *dct_coeff;
+
+    /**
+     * motion reference frame index
+     * the order in which these are stored can depend on the codec.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    int8_t *ref_index[2];
+
+    /**
+     * reordered opaque 64bit (generally an integer or a double precision float
+     * PTS but can be anything).
+     * The user sets AVCodecContext.reordered_opaque to represent the input at
+     * that time,
+     * the decoder reorders values as needed and sets AVFrame.reordered_opaque
+     * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque
+     * @deprecated in favor of pkt_pts
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int64_t reordered_opaque;
+
+    /**
+     * hardware accelerator private data (Libav-allocated)
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    void *hwaccel_picture_private;
+
+    /**
+     * reordered pts from the last AVPacket that has been input into the decoder
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int64_t pkt_pts;
+
+    /**
+     * dts from the last AVPacket that has been input into the decoder
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int64_t pkt_dts;
+
+    /**
+     * the AVCodecContext which ff_thread_get_buffer() was last called on
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    struct AVCodecContext *owner;
+
+    /**
+     * used by multithreading to store frame-specific info
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    void *thread_opaque;
+
+    /**
+     * number of audio samples (per channel) described by this frame
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    int nb_samples;
+
+    /**
+     * pointers to the data planes/channels.
+     *
+     * For video, this should simply point to data[].
+     *
+     * For planar audio, each channel has a separate data pointer, and
+     * linesize[0] contains the size of each channel buffer.
+     * For packed audio, there is just one data pointer, and linesize[0]
+     * contains the total size of the buffer for all channels.
+     *
+     * Note: Both data and extended_data will always be set by get_buffer(),
+     * but for planar audio with more channels that can fit in data,
+     * extended_data must be used by the decoder in order to access all
+     * channels.
+     *
+     * encoding: unused
+     * decoding: set by AVCodecContext.get_buffer()
+     */
+    uint8_t **extended_data;
+
+    /**
+     * sample aspect ratio for the video frame, 0/1 if unknown\unspecified
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    AVRational sample_aspect_ratio;
+
+    /**
+     * width and height of the video frame
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int width, height;
+
+    /**
+     * format of the frame, -1 if unknown or unset
+     * Values correspond to enum PixelFormat for video frames,
+     * enum AVSampleFormat for audio)
+     * - encoding: unused
+     * - decoding: Read by user.
+     */
+    int format;
+} AVFrame;
+
+struct AVCodecInternal;
+
+enum AVFieldOrder {
+    AV_FIELD_UNKNOWN,
+    AV_FIELD_PROGRESSIVE,
+    AV_FIELD_TT,          //< Top coded_first, top displayed first
+    AV_FIELD_BB,          //< Bottom coded first, bottom displayed first
+    AV_FIELD_TB,          //< Top coded first, bottom displayed first
+    AV_FIELD_BT,          //< Bottom coded first, top displayed first
+};
+
+/**
+ * main external API structure.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVCodecContext) must not be used outside libav*.
+ */
+typedef struct AVCodecContext {
+    /**
+     * information on struct for av_log
+     * - set by avcodec_alloc_context3
+     */
+    const AVClass *av_class;
+    /**
+     * the average bitrate
+     * - encoding: Set by user; unused for constant quantizer encoding.
+     * - decoding: Set by libavcodec. 0 or some bitrate if this info is available in the stream.
+     */
+    int bit_rate;
+
+    /**
+     * number of bits the bitstream is allowed to diverge from the reference.
+     *           the reference can be CBR (for CBR pass1) or VBR (for pass2)
+     * - encoding: Set by user; unused for constant quantizer encoding.
+     * - decoding: unused
+     */
+    int bit_rate_tolerance;
+
+    /**
+     * CODEC_FLAG_*.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int flags;
+
+    /**
+     * Some codecs need additional format info. It is stored here.
+     * If any muxer uses this then ALL demuxers/parsers AND encoders for the
+     * specific codec MUST set it correctly otherwise stream copy breaks.
+     * In general use of this field by muxers is not recommended.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec. (FIXME: Is this OK?)
+     */
+    int sub_id;
+
+    /**
+     * Motion estimation algorithm used for video coding.
+     * 1 (zero), 2 (full), 3 (log), 4 (phods), 5 (epzs), 6 (x1), 7 (hex),
+     * 8 (umh), 9 (iter), 10 (tesa) [7, 8, 10 are x264 specific, 9 is snow specific]
+     * - encoding: MUST be set by user.
+     * - decoding: unused
+     */
+    int me_method;
+
+    /**
+     * some codecs need / can use extradata like Huffman tables.
+     * mjpeg: Huffman tables
+     * rv10: additional flags
+     * mpeg4: global headers (they can be in the bitstream or here)
+     * The allocated memory should be FF_INPUT_BUFFER_PADDING_SIZE bytes larger
+     * than extradata_size to avoid prolems if it is read with the bitstream reader.
+     * The bytewise contents of extradata must not depend on the architecture or CPU endianness.
+     * - encoding: Set/allocated/freed by libavcodec.
+     * - decoding: Set/allocated/freed by user.
+     */
+    uint8_t *extradata;
+    int extradata_size;
+
+    /**
+     * This is the fundamental unit of time (in seconds) in terms
+     * of which frame timestamps are represented. For fixed-fps content,
+     * timebase should be 1/framerate and timestamp increments should be
+     * identically 1.
+     * - encoding: MUST be set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVRational time_base;
+
+    /* video only */
+    /**
+     * picture width / height.
+     * - encoding: MUST be set by user.
+     * - decoding: Set by libavcodec.
+     * Note: For compatibility it is possible to set this instead of
+     * coded_width/height before decoding.
+     */
+    int width, height;
+
+#define FF_ASPECT_EXTENDED 15
+
+    /**
+     * the number of pictures in a group of pictures, or 0 for intra_only
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int gop_size;
+
+    /**
+     * Pixel format, see PIX_FMT_xxx.
+     * May be set by the demuxer if known from headers.
+     * May be overriden by the decoder if it knows better.
+     * - encoding: Set by user.
+     * - decoding: Set by user if known, overridden by libavcodec if known
+     */
+    enum PixelFormat pix_fmt;
+
+    /**
+     * If non NULL, 'draw_horiz_band' is called by the libavcodec
+     * decoder to draw a horizontal band. It improves cache usage. Not
+     * all codecs can do that. You must check the codec capabilities
+     * beforehand.
+     * When multithreading is used, it may be called from multiple threads
+     * at the same time; threads might draw different parts of the same AVFrame,
+     * or multiple AVFrames, and there is no guarantee that slices will be drawn
+     * in order.
+     * The function is also used by hardware acceleration APIs.
+     * It is called at least once during frame decoding to pass
+     * the data needed for hardware render.
+     * In that mode instead of pixel data, AVFrame points to
+     * a structure specific to the acceleration API. The application
+     * reads the structure and can change some fields to indicate progress
+     * or mark state.
+     * - encoding: unused
+     * - decoding: Set by user.
+     * @param height the height of the slice
+     * @param y the y position of the slice
+     * @param type 1->top field, 2->bottom field, 3->frame
+     * @param offset offset into the AVFrame.data from which the slice should be read
+     */
+    void (*draw_horiz_band)(struct AVCodecContext *s,
+                            const AVFrame *src, int offset[AV_NUM_DATA_POINTERS],
+                            int y, int type, int height);
+
+    /* audio only */
+    int sample_rate; ///< samples per second
+    int channels;    ///< number of audio channels
+
+    /**
+     * audio sample format
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    enum AVSampleFormat sample_fmt;  ///< sample format
+
+    /* The following data should not be initialized. */
+    /**
+     * Samples per packet, initialized when calling 'init'.
+     */
+    int frame_size;
+    int frame_number;   ///< audio or video frame number
+
+    /**
+     * Number of frames the decoded output will be delayed relative to
+     * the encoded input.
+     * - encoding: Set by libavcodec.
+     * - decoding: unused
+     */
+    int delay;
+
+    /* - encoding parameters */
+    float qcompress;  ///< amount of qscale change between easy & hard scenes (0.0-1.0)
+    float qblur;      ///< amount of qscale smoothing over time (0.0-1.0)
+
+    /**
+     * minimum quantizer
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int qmin;
+
+    /**
+     * maximum quantizer
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int qmax;
+
+    /**
+     * maximum quantizer difference between frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_qdiff;
+
+    /**
+     * maximum number of B-frames between non-B-frames
+     * Note: The output will be delayed by max_b_frames+1 relative to the input.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_b_frames;
+
+    /**
+     * qscale factor between IP and B-frames
+     * If > 0 then the last P-frame quantizer will be used (q= lastp_q*factor+offset).
+     * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float b_quant_factor;
+
+    /** obsolete FIXME remove */
+    int rc_strategy;
+#define FF_RC_STRATEGY_XVID 1
+
+    int b_frame_strategy;
+
+    struct AVCodec *codec;
+
+    void *priv_data;
+
+    int rtp_payload_size;   /* The size of the RTP payload: the coder will  */
+                            /* do its best to deliver a chunk with size     */
+                            /* below rtp_payload_size, the chunk will start */
+                            /* with a start code on some codecs like H.263. */
+                            /* This doesn't take account of any particular  */
+                            /* headers inside the transmitted RTP payload.  */
+
+
+    /* The RTP callback: This function is called    */
+    /* every time the encoder has a packet to send. */
+    /* It depends on the encoder if the data starts */
+    /* with a Start Code (it should). H.263 does.   */
+    /* mb_nb contains the number of macroblocks     */
+    /* encoded in the RTP payload.                  */
+    void (*rtp_callback)(struct AVCodecContext *avctx, void *data, int size, int mb_nb);
+
+    /* statistics, used for 2-pass encoding */
+    int mv_bits;
+    int header_bits;
+    int i_tex_bits;
+    int p_tex_bits;
+    int i_count;
+    int p_count;
+    int skip_count;
+    int misc_bits;
+
+    /**
+     * number of bits used for the previously encoded frame
+     * - encoding: Set by libavcodec.
+     * - decoding: unused
+     */
+    int frame_bits;
+
+    /**
+     * Private data of the user, can be used to carry app specific stuff.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    void *opaque;
+
+    char codec_name[32];
+    enum AVMediaType codec_type; /* see AVMEDIA_TYPE_xxx */
+    enum CodecID codec_id; /* see CODEC_ID_xxx */
+
+    /**
+     * fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
+     * This is used to work around some encoder bugs.
+     * A demuxer should set this to what is stored in the field used to identify the codec.
+     * If there are multiple such fields in a container then the demuxer should choose the one
+     * which maximizes the information about the used codec.
+     * If the codec tag field in a container is larger than 32 bits then the demuxer should
+     * remap the longer ID to 32 bits with a table or other structure. Alternatively a new
+     * extra_codec_tag + size could be added but for this a clear advantage must be demonstrated
+     * first.
+     * - encoding: Set by user, if not then the default based on codec_id will be used.
+     * - decoding: Set by user, will be converted to uppercase by libavcodec during init.
+     */
+    unsigned int codec_tag;
+
+    /**
+     * Work around bugs in encoders which sometimes cannot be detected automatically.
+     * - encoding: Set by user
+     * - decoding: Set by user
+     */
+    int workaround_bugs;
+#define FF_BUG_AUTODETECT       1  ///< autodetection
+#define FF_BUG_OLD_MSMPEG4      2
+#define FF_BUG_XVID_ILACE       4
+#define FF_BUG_UMP4             8
+#define FF_BUG_NO_PADDING       16
+#define FF_BUG_AMV              32
+#define FF_BUG_AC_VLC           0  ///< Will be removed, libavcodec can now handle these non-compliant files by default.
+#define FF_BUG_QPEL_CHROMA      64
+#define FF_BUG_STD_QPEL         128
+#define FF_BUG_QPEL_CHROMA2     256
+#define FF_BUG_DIRECT_BLOCKSIZE 512
+#define FF_BUG_EDGE             1024
+#define FF_BUG_HPEL_CHROMA      2048
+#define FF_BUG_DC_CLIP          4096
+#define FF_BUG_MS               8192 ///< Work around various bugs in Microsoft's broken decoders.
+#define FF_BUG_TRUNCATED       16384
+//#define FF_BUG_FAKE_SCALABILITY 16 //Autodetection should work 100%.
+
+    /**
+     * luma single coefficient elimination threshold
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int luma_elim_threshold;
+
+    /**
+     * chroma single coeff elimination threshold
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int chroma_elim_threshold;
+
+    /**
+     * strictly follow the standard (MPEG4, ...).
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     * Setting this to STRICT or higher means the encoder and decoder will
+     * generally do stupid things, whereas setting it to unofficial or lower
+     * will mean the encoder might produce output that is not supported by all
+     * spec-compliant decoders. Decoders don't differentiate between normal,
+     * unofficial and experimental (that is, they always try to decode things
+     * when they can) unless they are explicitly asked to behave stupidly
+     * (=strictly conform to the specs)
+     */
+    int strict_std_compliance;
+#define FF_COMPLIANCE_VERY_STRICT   2 ///< Strictly conform to an older more strict version of the spec or reference software.
+#define FF_COMPLIANCE_STRICT        1 ///< Strictly conform to all the things in the spec no matter what consequences.
+#define FF_COMPLIANCE_NORMAL        0
+#define FF_COMPLIANCE_UNOFFICIAL   -1 ///< Allow unofficial extensions
+#define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things.
+
+    /**
+     * qscale offset between IP and B-frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float b_quant_offset;
+
+#if FF_API_ER
+    /**
+     * Error recognition; higher values will detect more errors but may
+     * misdetect some more or less valid parts as errors.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    attribute_deprecated int error_recognition;
+#define FF_ER_CAREFUL         1
+#define FF_ER_COMPLIANT       2
+#define FF_ER_AGGRESSIVE      3
+#define FF_ER_VERY_AGGRESSIVE 4
+#define FF_ER_EXPLODE         5
+#endif /* FF_API_ER */
+
+    /**
+     * Called at the beginning of each frame to get a buffer for it.
+     *
+     * The function will set AVFrame.data[], AVFrame.linesize[].
+     * AVFrame.extended_data[] must also be set, but it should be the same as
+     * AVFrame.data[] except for planar audio with more channels than can fit
+     * in AVFrame.data[]. In that case, AVFrame.data[] shall still contain as
+     * many data pointers as it can hold.
+     *
+     * if CODEC_CAP_DR1 is not set then get_buffer() must call
+     * avcodec_default_get_buffer() instead of providing buffers allocated by
+     * some other means.
+     *
+     * AVFrame.data[] should be 32- or 16-byte-aligned unless the CPU doesn't
+     * need it. avcodec_default_get_buffer() aligns the output buffer properly,
+     * but if get_buffer() is overridden then alignment considerations should
+     * be taken into account.
+     *
+     * @see avcodec_default_get_buffer()
+     *
+     * Video:
+     *
+     * If pic.reference is set then the frame will be read later by libavcodec.
+     * avcodec_align_dimensions2() should be used to find the required width and
+     * height, as they normally need to be rounded up to the next multiple of 16.
+     *
+     * If frame multithreading is used and thread_safe_callbacks is set,
+     * it may be called from a different thread, but not from more than one at
+     * once. Does not need to be reentrant.
+     *
+     * @see release_buffer(), reget_buffer()
+     * @see avcodec_align_dimensions2()
+     *
+     * Audio:
+     *
+     * Decoders request a buffer of a particular size by setting
+     * AVFrame.nb_samples prior to calling get_buffer(). The decoder may,
+     * however, utilize only part of the buffer by setting AVFrame.nb_samples
+     * to a smaller value in the output frame.
+     *
+     * Decoders cannot use the buffer after returning from
+     * avcodec_decode_audio4(), so they will not call release_buffer(), as it
+     * is assumed to be released immediately upon return.
+     *
+     * As a convenience, av_samples_get_buffer_size() and
+     * av_samples_fill_arrays() in libavutil may be used by custom get_buffer()
+     * functions to find the required data size and to fill data pointers and
+     * linesize. In AVFrame.linesize, only linesize[0] may be set for audio
+     * since all planes must be the same size.
+     *
+     * @see av_samples_get_buffer_size(), av_samples_fill_arrays()
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*get_buffer)(struct AVCodecContext *c, AVFrame *pic);
+
+    /**
+     * Called to release buffers which were allocated with get_buffer.
+     * A released buffer can be reused in get_buffer().
+     * pic.data[*] must be set to NULL.
+     * May be called from a different thread if frame multithreading is used,
+     * but not by more than one thread at once, so does not need to be reentrant.
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     */
+    void (*release_buffer)(struct AVCodecContext *c, AVFrame *pic);
+
+    /**
+     * Size of the frame reordering buffer in the decoder.
+     * For MPEG-2 it is 1 IPB or 0 low delay IP.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int has_b_frames;
+
+    /**
+     * number of bytes per packet if constant and known or 0
+     * Used by some WAV based audio codecs.
+     */
+    int block_align;
+
+#if FF_API_PARSE_FRAME
+    /**
+     * If true, only parsing is done. The frame data is returned.
+     * Only MPEG audio decoders support this now.
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    attribute_deprecated int parse_only;
+#endif
+
+    /**
+     * 0-> h263 quant 1-> mpeg quant
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mpeg_quant;
+
+    /**
+     * pass1 encoding statistics output buffer
+     * - encoding: Set by libavcodec.
+     * - decoding: unused
+     */
+    char *stats_out;
+
+    /**
+     * pass2 encoding statistics input buffer
+     * Concatenated stuff from stats_out of pass1 should be placed here.
+     * - encoding: Allocated/set/freed by user.
+     * - decoding: unused
+     */
+    char *stats_in;
+
+    /**
+     * ratecontrol qmin qmax limiting method
+     * 0-> clipping, 1-> use a nice continous function to limit qscale wthin qmin/qmax.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float rc_qsquish;
+
+    float rc_qmod_amp;
+    int rc_qmod_freq;
+
+    /**
+     * ratecontrol override, see RcOverride
+     * - encoding: Allocated/set/freed by user.
+     * - decoding: unused
+     */
+    RcOverride *rc_override;
+    int rc_override_count;
+
+    /**
+     * rate control equation
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    const char *rc_eq;
+
+    /**
+     * maximum bitrate
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_max_rate;
+
+    /**
+     * minimum bitrate
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_min_rate;
+
+    /**
+     * decoder bitstream buffer size
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_buffer_size;
+    float rc_buffer_aggressivity;
+
+    /**
+     * qscale factor between P and I-frames
+     * If > 0 then the last p frame quantizer will be used (q= lastp_q*factor+offset).
+     * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float i_quant_factor;
+
+    /**
+     * qscale offset between P and I-frames
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float i_quant_offset;
+
+    /**
+     * initial complexity for pass1 ratecontrol
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float rc_initial_cplx;
+
+    /**
+     * DCT algorithm, see FF_DCT_* below
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int dct_algo;
+#define FF_DCT_AUTO    0
+#define FF_DCT_FASTINT 1
+#define FF_DCT_INT     2
+#define FF_DCT_MMX     3
+#define FF_DCT_MLIB    4
+#define FF_DCT_ALTIVEC 5
+#define FF_DCT_FAAN    6
+
+    /**
+     * luminance masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float lumi_masking;
+
+    /**
+     * temporary complexity masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float temporal_cplx_masking;
+
+    /**
+     * spatial complexity masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float spatial_cplx_masking;
+
+    /**
+     * p block masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float p_masking;
+
+    /**
+     * darkness masking (0-> disabled)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float dark_masking;
+
+    /**
+     * IDCT algorithm, see FF_IDCT_* below.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int idct_algo;
+#define FF_IDCT_AUTO          0
+#define FF_IDCT_INT           1
+#define FF_IDCT_SIMPLE        2
+#define FF_IDCT_SIMPLEMMX     3
+#define FF_IDCT_LIBMPEG2MMX   4
+#define FF_IDCT_PS2           5
+#define FF_IDCT_MLIB          6
+#define FF_IDCT_ARM           7
+#define FF_IDCT_ALTIVEC       8
+#define FF_IDCT_SH4           9
+#define FF_IDCT_SIMPLEARM     10
+#define FF_IDCT_H264          11
+#define FF_IDCT_VP3           12
+#define FF_IDCT_IPP           13
+#define FF_IDCT_XVIDMMX       14
+#define FF_IDCT_CAVS          15
+#define FF_IDCT_SIMPLEARMV5TE 16
+#define FF_IDCT_SIMPLEARMV6   17
+#define FF_IDCT_SIMPLEVIS     18
+#define FF_IDCT_WMV2          19
+#define FF_IDCT_FAAN          20
+#define FF_IDCT_EA            21
+#define FF_IDCT_SIMPLENEON    22
+#define FF_IDCT_SIMPLEALPHA   23
+#define FF_IDCT_BINK          24
+
+    /**
+     * slice count
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by user (or 0).
+     */
+    int slice_count;
+    /**
+     * slice offsets in the frame in bytes
+     * - encoding: Set/allocated by libavcodec.
+     * - decoding: Set/allocated by user (or NULL).
+     */
+    int *slice_offset;
+
+    /**
+     * error concealment flags
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int error_concealment;
+#define FF_EC_GUESS_MVS   1
+#define FF_EC_DEBLOCK     2
+
+    /**
+     * dsp_mask could be add used to disable unwanted CPU features
+     * CPU features (i.e. MMX, SSE. ...)
+     *
+     * With the FORCE flag you may instead enable given CPU features.
+     * (Dangerous: Usable in case of misdetection, improper usage however will
+     * result into program crash.)
+     */
+    unsigned dsp_mask;
+
+    /**
+     * bits per sample/pixel from the demuxer (needed for huffyuv).
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by user.
+     */
+     int bits_per_coded_sample;
+
+    /**
+     * prediction method (needed for huffyuv)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int prediction_method;
+#define FF_PRED_LEFT   0
+#define FF_PRED_PLANE  1
+#define FF_PRED_MEDIAN 2
+
+    /**
+     * sample aspect ratio (0 if unknown)
+     * That is the width of a pixel divided by the height of the pixel.
+     * Numerator and denominator must be relatively prime and smaller than 256 for some video standards.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    AVRational sample_aspect_ratio;
+
+    /**
+     * the picture in the bitstream
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    AVFrame *coded_frame;
+
+    /**
+     * debug
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int debug;
+#define FF_DEBUG_PICT_INFO   1
+#define FF_DEBUG_RC          2
+#define FF_DEBUG_BITSTREAM   4
+#define FF_DEBUG_MB_TYPE     8
+#define FF_DEBUG_QP          16
+#define FF_DEBUG_MV          32
+#define FF_DEBUG_DCT_COEFF   0x00000040
+#define FF_DEBUG_SKIP        0x00000080
+#define FF_DEBUG_STARTCODE   0x00000100
+#define FF_DEBUG_PTS         0x00000200
+#define FF_DEBUG_ER          0x00000400
+#define FF_DEBUG_MMCO        0x00000800
+#define FF_DEBUG_BUGS        0x00001000
+#define FF_DEBUG_VIS_QP      0x00002000
+#define FF_DEBUG_VIS_MB_TYPE 0x00004000
+#define FF_DEBUG_BUFFERS     0x00008000
+#define FF_DEBUG_THREADS     0x00010000
+
+    /**
+     * debug
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int debug_mv;
+#define FF_DEBUG_VIS_MV_P_FOR  0x00000001 //visualize forward predicted MVs of P frames
+#define FF_DEBUG_VIS_MV_B_FOR  0x00000002 //visualize forward predicted MVs of B frames
+#define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames
+
+    /**
+     * error
+     * - encoding: Set by libavcodec if flags&CODEC_FLAG_PSNR.
+     * - decoding: unused
+     */
+    uint64_t error[AV_NUM_DATA_POINTERS];
+
+    /**
+     * motion estimation comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_cmp;
+    /**
+     * subpixel motion estimation comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_sub_cmp;
+    /**
+     * macroblock comparison function (not supported yet)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_cmp;
+    /**
+     * interlaced DCT comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int ildct_cmp;
+#define FF_CMP_SAD    0
+#define FF_CMP_SSE    1
+#define FF_CMP_SATD   2
+#define FF_CMP_DCT    3
+#define FF_CMP_PSNR   4
+#define FF_CMP_BIT    5
+#define FF_CMP_RD     6
+#define FF_CMP_ZERO   7
+#define FF_CMP_VSAD   8
+#define FF_CMP_VSSE   9
+#define FF_CMP_NSSE   10
+#define FF_CMP_W53    11
+#define FF_CMP_W97    12
+#define FF_CMP_DCTMAX 13
+#define FF_CMP_DCT264 14
+#define FF_CMP_CHROMA 256
+
+    /**
+     * ME diamond size & shape
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int dia_size;
+
+    /**
+     * amount of previous MV predictors (2a+1 x 2a+1 square)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int last_predictor_count;
+
+    /**
+     * prepass for motion estimation
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int pre_me;
+
+    /**
+     * motion estimation prepass comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_pre_cmp;
+
+    /**
+     * ME prepass diamond size & shape
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int pre_dia_size;
+
+    /**
+     * subpel ME quality
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_subpel_quality;
+
+    /**
+     * callback to negotiate the pixelFormat
+     * @param fmt is the list of formats which are supported by the codec,
+     * it is terminated by -1 as 0 is a valid format, the formats are ordered by quality.
+     * The first is always the native one.
+     * @return the chosen format
+     * - encoding: unused
+     * - decoding: Set by user, if not set the native format will be chosen.
+     */
+    enum PixelFormat (*get_format)(struct AVCodecContext *s, const enum PixelFormat * fmt);
+
+    /**
+     * DTG active format information (additional aspect ratio
+     * information only used in DVB MPEG-2 transport streams)
+     * 0 if not set.
+     *
+     * - encoding: unused
+     * - decoding: Set by decoder.
+     */
+    int dtg_active_format;
+#define FF_DTG_AFD_SAME         8
+#define FF_DTG_AFD_4_3          9
+#define FF_DTG_AFD_16_9         10
+#define FF_DTG_AFD_14_9         11
+#define FF_DTG_AFD_4_3_SP_14_9  13
+#define FF_DTG_AFD_16_9_SP_14_9 14
+#define FF_DTG_AFD_SP_4_3       15
+
+    /**
+     * maximum motion estimation search range in subpel units
+     * If 0 then no limit.
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_range;
+
+    /**
+     * intra quantizer bias
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int intra_quant_bias;
+#define FF_DEFAULT_QUANT_BIAS 999999
+
+    /**
+     * inter quantizer bias
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int inter_quant_bias;
+
+    /**
+     * color table ID
+     * - encoding: unused
+     * - decoding: Which clrtable should be used for 8bit RGB images.
+     *             Tables have to be stored somewhere. FIXME
+     */
+    int color_table_id;
+
+#if FF_API_INTERNAL_CONTEXT
+    /**
+     * internal_buffer count
+     * Don't touch, used by libavcodec default_get_buffer().
+     * @deprecated this field was moved to an internal context
+     */
+    attribute_deprecated int internal_buffer_count;
+
+    /**
+     * internal_buffers
+     * Don't touch, used by libavcodec default_get_buffer().
+     * @deprecated this field was moved to an internal context
+     */
+    attribute_deprecated void *internal_buffer;
+#endif
+
+    /**
+     * Global quality for codecs which cannot change it per frame.
+     * This should be proportional to MPEG-1/2/4 qscale.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int global_quality;
+
+#define FF_CODER_TYPE_VLC       0
+#define FF_CODER_TYPE_AC        1
+#define FF_CODER_TYPE_RAW       2
+#define FF_CODER_TYPE_RLE       3
+#define FF_CODER_TYPE_DEFLATE   4
+    /**
+     * coder type
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int coder_type;
+
+    /**
+     * context model
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int context_model;
+#if 0
+    /**
+     *
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    uint8_t * (*realloc)(struct AVCodecContext *s, uint8_t *buf, int buf_size);
+#endif
+
+    /**
+     * slice flags
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int slice_flags;
+#define SLICE_FLAG_CODED_ORDER    0x0001 ///< draw_horiz_band() is called in coded order instead of display
+#define SLICE_FLAG_ALLOW_FIELD    0x0002 ///< allow draw_horiz_band() with field slices (MPEG2 field pics)
+#define SLICE_FLAG_ALLOW_PLANE    0x0004 ///< allow draw_horiz_band() with 1 component at a time (SVQ1)
+
+    /**
+     * XVideo Motion Acceleration
+     * - encoding: forbidden
+     * - decoding: set by decoder
+     */
+    int xvmc_acceleration;
+
+    /**
+     * macroblock decision mode
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_decision;
+#define FF_MB_DECISION_SIMPLE 0        ///< uses mb_cmp
+#define FF_MB_DECISION_BITS   1        ///< chooses the one which needs the fewest bits
+#define FF_MB_DECISION_RD     2        ///< rate distortion
+
+    /**
+     * custom intra quantization matrix
+     * - encoding: Set by user, can be NULL.
+     * - decoding: Set by libavcodec.
+     */
+    uint16_t *intra_matrix;
+
+    /**
+     * custom inter quantization matrix
+     * - encoding: Set by user, can be NULL.
+     * - decoding: Set by libavcodec.
+     */
+    uint16_t *inter_matrix;
+
+    /**
+     * fourcc from the AVI stream header (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
+     * This is used to work around some encoder bugs.
+     * - encoding: unused
+     * - decoding: Set by user, will be converted to uppercase by libavcodec during init.
+     */
+    unsigned int stream_codec_tag;
+
+    /**
+     * scene change detection threshold
+     * 0 is default, larger means fewer detected scene changes.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int scenechange_threshold;
+
+    /**
+     * minimum Lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int lmin;
+
+    /**
+     * maximum Lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int lmax;
+
+#if FF_API_PALETTE_CONTROL
+    /**
+     * palette control structure
+     * - encoding: ??? (no palette-enabled encoder yet)
+     * - decoding: Set by user.
+     */
+    struct AVPaletteControl *palctrl;
+#endif
+
+    /**
+     * noise reduction strength
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int noise_reduction;
+
+    /**
+     * Called at the beginning of a frame to get cr buffer for it.
+     * Buffer type (size, hints) must be the same. libavcodec won't check it.
+     * libavcodec will pass previous buffer in pic, function should return
+     * same buffer or new buffer with old frame "painted" into it.
+     * If pic.data[0] == NULL must behave like get_buffer().
+     * if CODEC_CAP_DR1 is not set then reget_buffer() must call
+     * avcodec_default_reget_buffer() instead of providing buffers allocated by
+     * some other means.
+     * - encoding: unused
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*reget_buffer)(struct AVCodecContext *c, AVFrame *pic);
+
+    /**
+     * Number of bits which should be loaded into the rc buffer before decoding starts.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int rc_initial_buffer_occupancy;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int inter_threshold;
+
+    /**
+     * CODEC_FLAG2_*
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int flags2;
+
+    /**
+     * Simulates errors in the bitstream to test error concealment.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int error_rate;
+
+#if FF_API_ANTIALIAS_ALGO
+    /**
+     * MP3 antialias algorithm, see FF_AA_* below.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    attribute_deprecated int antialias_algo;
+#define FF_AA_AUTO    0
+#define FF_AA_FASTINT 1 //not implemented yet
+#define FF_AA_INT     2
+#define FF_AA_FLOAT   3
+#endif
+
+    /**
+     * quantizer noise shaping
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int quantizer_noise_shaping;
+
+    /**
+     * thread count
+     * is used to decide how many independent tasks should be passed to execute()
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int thread_count;
+
+    /**
+     * The codec may call this to execute several independent things.
+     * It will return only after finishing all tasks.
+     * The user may replace this with some multithreaded implementation,
+     * the default implementation will execute the parts serially.
+     * @param count the number of things to execute
+     * - encoding: Set by libavcodec, user can override.
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*execute)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size);
+
+    /**
+     * thread opaque
+     * Can be used by execute() to store some per AVCodecContext stuff.
+     * - encoding: set by execute()
+     * - decoding: set by execute()
+     */
+    void *thread_opaque;
+
+    /**
+     * Motion estimation threshold below which no motion estimation is
+     * performed, but instead the user specified motion vectors are used.
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int me_threshold;
+
+    /**
+     * Macroblock threshold below which the user specified macroblock types will be used.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int mb_threshold;
+
+    /**
+     * precision of the intra DC coefficient - 8
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int intra_dc_precision;
+
+    /**
+     * noise vs. sse weight for the nsse comparsion function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+     int nsse_weight;
+
+    /**
+     * Number of macroblock rows at the top which are skipped.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+     int skip_top;
+
+    /**
+     * Number of macroblock rows at the bottom which are skipped.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+     int skip_bottom;
+
+    /**
+     * profile
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+     int profile;
+#define FF_PROFILE_UNKNOWN -99
+#define FF_PROFILE_RESERVED -100
+
+#define FF_PROFILE_AAC_MAIN 0
+#define FF_PROFILE_AAC_LOW  1
+#define FF_PROFILE_AAC_SSR  2
+#define FF_PROFILE_AAC_LTP  3
+
+#define FF_PROFILE_DTS         20
+#define FF_PROFILE_DTS_ES      30
+#define FF_PROFILE_DTS_96_24   40
+#define FF_PROFILE_DTS_HD_HRA  50
+#define FF_PROFILE_DTS_HD_MA   60
+
+#define FF_PROFILE_MPEG2_422    0
+#define FF_PROFILE_MPEG2_HIGH   1
+#define FF_PROFILE_MPEG2_SS     2
+#define FF_PROFILE_MPEG2_SNR_SCALABLE  3
+#define FF_PROFILE_MPEG2_MAIN   4
+#define FF_PROFILE_MPEG2_SIMPLE 5
+
+#define FF_PROFILE_H264_CONSTRAINED  (1<<9)  // 8+1; constraint_set1_flag
+#define FF_PROFILE_H264_INTRA        (1<<11) // 8+3; constraint_set3_flag
+
+#define FF_PROFILE_H264_BASELINE             66
+#define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED)
+#define FF_PROFILE_H264_MAIN                 77
+#define FF_PROFILE_H264_EXTENDED             88
+#define FF_PROFILE_H264_HIGH                 100
+#define FF_PROFILE_H264_HIGH_10              110
+#define FF_PROFILE_H264_HIGH_10_INTRA        (110|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_422             122
+#define FF_PROFILE_H264_HIGH_422_INTRA       (122|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_HIGH_444             144
+#define FF_PROFILE_H264_HIGH_444_PREDICTIVE  244
+#define FF_PROFILE_H264_HIGH_444_INTRA       (244|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_CAVLC_444            44
+
+#define FF_PROFILE_VC1_SIMPLE   0
+#define FF_PROFILE_VC1_MAIN     1
+#define FF_PROFILE_VC1_COMPLEX  2
+#define FF_PROFILE_VC1_ADVANCED 3
+
+#define FF_PROFILE_MPEG4_SIMPLE                     0
+#define FF_PROFILE_MPEG4_SIMPLE_SCALABLE            1
+#define FF_PROFILE_MPEG4_CORE                       2
+#define FF_PROFILE_MPEG4_MAIN                       3
+#define FF_PROFILE_MPEG4_N_BIT                      4
+#define FF_PROFILE_MPEG4_SCALABLE_TEXTURE           5
+#define FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION      6
+#define FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE     7
+#define FF_PROFILE_MPEG4_HYBRID                     8
+#define FF_PROFILE_MPEG4_ADVANCED_REAL_TIME         9
+#define FF_PROFILE_MPEG4_CORE_SCALABLE             10
+#define FF_PROFILE_MPEG4_ADVANCED_CODING           11
+#define FF_PROFILE_MPEG4_ADVANCED_CORE             12
+#define FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE 13
+#define FF_PROFILE_MPEG4_SIMPLE_STUDIO             14
+#define FF_PROFILE_MPEG4_ADVANCED_SIMPLE           15
+
+    /**
+     * level
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+     int level;
+#define FF_LEVEL_UNKNOWN -99
+
+    /**
+     * low resolution decoding, 1-> 1/2 size, 2->1/4 size
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+     int lowres;
+
+    /**
+     * Bitstream width / height, may be different from width/height if lowres enabled.
+     * - encoding: unused
+     * - decoding: Set by user before init if known. Codec should override / dynamically change if needed.
+     */
+    int coded_width, coded_height;
+
+    /**
+     * frame skip threshold
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_threshold;
+
+    /**
+     * frame skip factor
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_factor;
+
+    /**
+     * frame skip exponent
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_exp;
+
+    /**
+     * frame skip comparison function
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int frame_skip_cmp;
+
+    /**
+     * Border processing masking, raises the quantizer for mbs on the borders
+     * of the picture.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    float border_masking;
+
+    /**
+     * minimum MB lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_lmin;
+
+    /**
+     * maximum MB lagrange multipler
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mb_lmax;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int me_penalty_compensation;
+
+    /**
+     *
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_loop_filter;
+
+    /**
+     *
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_idct;
+
+    /**
+     *
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    enum AVDiscard skip_frame;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int bidir_refine;
+
+    /**
+     *
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int brd_scale;
+
+#if FF_API_X264_GLOBAL_OPTS
+    /**
+     * constant rate factor - quality-based VBR - values ~correspond to qps
+     * - encoding: Set by user.
+     * - decoding: unused
+     *   @deprecated use 'crf' libx264 private option
+     */
+    attribute_deprecated float crf;
+
+    /**
+     * constant quantization parameter rate control method
+     * - encoding: Set by user.
+     * - decoding: unused
+     *   @deprecated use 'cqp' libx264 private option
+     */
+    attribute_deprecated int cqp;
+#endif
+
+    /**
+     * minimum GOP size
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int keyint_min;
+
+    /**
+     * number of reference frames
+     * - encoding: Set by user.
+     * - decoding: Set by lavc.
+     */
+    int refs;
+
+    /**
+     * chroma qp offset from luma
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int chromaoffset;
+
+#if FF_API_X264_GLOBAL_OPTS
+    /**
+     * Influence how often B-frames are used.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int bframebias;
+#endif
+
+    /**
+     * trellis RD quantization
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int trellis;
+
+#if FF_API_X264_GLOBAL_OPTS
+    /**
+     * Reduce fluctuations in qp (before curve compression).
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated float complexityblur;
+
+    /**
+     * in-loop deblocking filter alphac0 parameter
+     * alpha is in the range -6...6
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int deblockalpha;
+
+    /**
+     * in-loop deblocking filter beta parameter
+     * beta is in the range -6...6
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int deblockbeta;
+
+    /**
+     * macroblock subpartition sizes to consider - p8x8, p4x4, b8x8, i8x8, i4x4
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int partitions;
+#define X264_PART_I4X4 0x001  /* Analyze i4x4 */
+#define X264_PART_I8X8 0x002  /* Analyze i8x8 (requires 8x8 transform) */
+#define X264_PART_P8X8 0x010  /* Analyze p16x8, p8x16 and p8x8 */
+#define X264_PART_P4X4 0x020  /* Analyze p8x4, p4x8, p4x4 */
+#define X264_PART_B8X8 0x100  /* Analyze b16x8, b8x16 and b8x8 */
+
+    /**
+     * direct MV prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int directpred;
+#endif
+
+    /**
+     * Audio cutoff bandwidth (0 means "automatic")
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int cutoff;
+
+    /**
+     * Multiplied by qscale for each frame and added to scene_change_score.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int scenechange_factor;
+
+    /**
+     *
+     * Note: Value depends upon the compare function used for fullpel ME.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int mv0_threshold;
+
+    /**
+     * Adjust sensitivity of b_frame_strategy 1.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int b_sensitivity;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int compression_level;
+#define FF_COMPRESSION_DEFAULT -1
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int min_prediction_order;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int max_prediction_order;
+
+#if FF_API_FLAC_GLOBAL_OPTS
+    /**
+     * @name FLAC options
+     * @deprecated Use FLAC encoder private options instead.
+     * @{
+     */
+
+    /**
+     * LPC coefficient precision - used by FLAC encoder
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int lpc_coeff_precision;
+
+    /**
+     * search method for selecting prediction order
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int prediction_order_method;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int min_partition_order;
+
+    /**
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int max_partition_order;
+    /**
+     * @}
+     */
+#endif
+
+    /**
+     * GOP timecode frame start number, in non drop frame format
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int64_t timecode_frame_start;
+
+#if FF_API_REQUEST_CHANNELS
+    /**
+     * Decoder should decode to this many channels if it can (0 for default)
+     * - encoding: unused
+     * - decoding: Set by user.
+     * @deprecated Deprecated in favor of request_channel_layout.
+     */
+    int request_channels;
+#endif
+
+#if FF_API_DRC_SCALE
+    /**
+     * Percentage of dynamic range compression to be applied by the decoder.
+     * The default value is 1.0, corresponding to full compression.
+     * - encoding: unused
+     * - decoding: Set by user.
+     * @deprecated use AC3 decoder private option instead.
+     */
+    attribute_deprecated float drc_scale;
+#endif
+
+    /**
+     * opaque 64bit number (generally a PTS) that will be reordered and
+     * output in AVFrame.reordered_opaque
+     * @deprecated in favor of pkt_pts
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int64_t reordered_opaque;
+
+    /**
+     * Bits per sample/pixel of internal libavcodec pixel/sample format.
+     * - encoding: set by user.
+     * - decoding: set by libavcodec.
+     */
+    int bits_per_raw_sample;
+
+    /**
+     * Audio channel layout.
+     * - encoding: set by user.
+     * - decoding: set by libavcodec.
+     */
+    uint64_t channel_layout;
+
+    /**
+     * Request decoder to use this channel layout if it can (0 for default)
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    uint64_t request_channel_layout;
+
+    /**
+     * Ratecontrol attempt to use, at maximum, <value> of what can be used without an underflow.
+     * - encoding: Set by user.
+     * - decoding: unused.
+     */
+    float rc_max_available_vbv_use;
+
+    /**
+     * Ratecontrol attempt to use, at least, <value> times the amount needed to prevent a vbv overflow.
+     * - encoding: Set by user.
+     * - decoding: unused.
+     */
+    float rc_min_vbv_overflow_use;
+
+    /**
+     * Hardware accelerator in use
+     * - encoding: unused.
+     * - decoding: Set by libavcodec
+     */
+    struct AVHWAccel *hwaccel;
+
+    /**
+     * For some codecs, the time base is closer to the field rate than the frame rate.
+     * Most notably, H.264 and MPEG-2 specify time_base as half of frame duration
+     * if no telecine is used ...
+     *
+     * Set to time_base ticks per frame. Default 1, e.g., H.264/MPEG-2 set it to 2.
+     */
+    int ticks_per_frame;
+
+    /**
+     * Hardware accelerator context.
+     * For some hardware accelerators, a global context needs to be
+     * provided by the user. In that case, this holds display-dependent
+     * data Libav cannot instantiate itself. Please refer to the
+     * Libav HW accelerator documentation to know how to fill this
+     * is. e.g. for VA API, this is a struct vaapi_context.
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    void *hwaccel_context;
+
+    /**
+     * Chromaticity coordinates of the source primaries.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorPrimaries color_primaries;
+
+    /**
+     * Color Transfer Characteristic.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorTransferCharacteristic color_trc;
+
+    /**
+     * YUV colorspace type.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorSpace colorspace;
+
+    /**
+     * MPEG vs JPEG YUV range.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVColorRange color_range;
+
+    /**
+     * This defines the location of chroma samples.
+     * - encoding: Set by user
+     * - decoding: Set by libavcodec
+     */
+    enum AVChromaLocation chroma_sample_location;
+
+    /**
+     * The codec may call this to execute several independent things.
+     * It will return only after finishing all tasks.
+     * The user may replace this with some multithreaded implementation,
+     * the default implementation will execute the parts serially.
+     * Also see avcodec_thread_init and e.g. the --enable-pthread configure option.
+     * @param c context passed also to func
+     * @param count the number of things to execute
+     * @param arg2 argument passed unchanged to func
+     * @param ret return values of executed functions, must have space for "count" values. May be NULL.
+     * @param func function that will be called count times, with jobnr from 0 to count-1.
+     *             threadnr will be in the range 0 to c->thread_count-1 < MAX_THREADS and so that no
+     *             two instances of func executing at the same time will have the same threadnr.
+     * @return always 0 currently, but code should handle a future improvement where when any call to func
+     *         returns < 0 no further calls to func may be done and < 0 is returned.
+     * - encoding: Set by libavcodec, user can override.
+     * - decoding: Set by libavcodec, user can override.
+     */
+    int (*execute2)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count);
+
+#if FF_API_X264_GLOBAL_OPTS
+    /**
+     * explicit P-frame weighted prediction analysis method
+     * 0: off
+     * 1: fast blind weighting (one reference duplicate with -1 offset)
+     * 2: smart weighting (full fade detection analysis)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated int weighted_p_pred;
+
+    /**
+     * AQ mode
+     * 0: Disabled
+     * 1: Variance AQ (complexity mask)
+     * 2: Auto-variance AQ (experimental)
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated int aq_mode;
+
+    /**
+     * AQ strength
+     * Reduces blocking and blurring in flat and textured areas.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated float aq_strength;
+
+    /**
+     * PSY RD
+     * Strength of psychovisual optimization
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated float psy_rd;
+
+    /**
+     * PSY trellis
+     * Strength of psychovisual optimization
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated float psy_trellis;
+
+    /**
+     * RC lookahead
+     * Number of frames for frametype and ratecontrol lookahead
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated int rc_lookahead;
+
+    /**
+     * Constant rate factor maximum
+     * With CRF encoding mode and VBV restrictions enabled, prevents quality from being worse
+     * than crf_max, even if doing so would violate VBV restrictions.
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    attribute_deprecated float crf_max;
+#endif
+
+    int log_level_offset;
+
+#if FF_API_FLAC_GLOBAL_OPTS
+    /**
+     * Determine which LPC analysis algorithm to use.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated enum AVLPCType lpc_type;
+
+    /**
+     * Number of passes to use for Cholesky factorization during LPC analysis
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    attribute_deprecated int lpc_passes;
+#endif
+
+    /**
+     * Number of slices.
+     * Indicates number of picture subdivisions. Used for parallelized
+     * decoding.
+     * - encoding: Set by user
+     * - decoding: unused
+     */
+    int slices;
+
+    /**
+     * Header containing style information for text subtitles.
+     * For SUBTITLE_ASS subtitle type, it should contain the whole ASS
+     * [Script Info] and [V4+ Styles] section, plus the [Events] line and
+     * the Format line following. It shouldn't include any Dialogue line.
+     * - encoding: Set/allocated/freed by user (before avcodec_open2())
+     * - decoding: Set/allocated/freed by libavcodec (by avcodec_open2())
+     */
+    uint8_t *subtitle_header;
+    int subtitle_header_size;
+
+    /**
+     * Current packet as passed into the decoder, to avoid having
+     * to pass the packet into every function. Currently only valid
+     * inside lavc and get/release_buffer callbacks.
+     * - decoding: set by avcodec_decode_*, read by get_buffer() for setting pkt_pts
+     * - encoding: unused
+     */
+    AVPacket *pkt;
+
+#if FF_API_INTERNAL_CONTEXT
+    /**
+     * Whether this is a copy of the context which had init() called on it.
+     * This is used by multithreading - shared tables and picture pointers
+     * should be freed from the original context only.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     *
+     * @deprecated this field has been moved to an internal context
+     */
+    attribute_deprecated int is_copy;
+#endif
+
+    /**
+     * Which multithreading methods to use.
+     * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread,
+     * so clients which cannot provide future frames should not use it.
+     *
+     * - encoding: Set by user, otherwise the default is used.
+     * - decoding: Set by user, otherwise the default is used.
+     */
+    int thread_type;
+#define FF_THREAD_FRAME   1 ///< Decode more than one frame at once
+#define FF_THREAD_SLICE   2 ///< Decode more than one part of a single frame at once
+
+    /**
+     * Which multithreading methods are in use by the codec.
+     * - encoding: Set by libavcodec.
+     * - decoding: Set by libavcodec.
+     */
+    int active_thread_type;
+
+    /**
+     * Set by the client if its custom get_buffer() callback can be called
+     * from another thread, which allows faster multithreaded decoding.
+     * draw_horiz_band() will be called from other threads regardless of this setting.
+     * Ignored if the default get_buffer() is used.
+     * - encoding: Set by user.
+     * - decoding: Set by user.
+     */
+    int thread_safe_callbacks;
+
+    /**
+     * VBV delay coded in the last frame (in periods of a 27 MHz clock).
+     * Used for compliant TS muxing.
+     * - encoding: Set by libavcodec.
+     * - decoding: unused.
+     */
+    uint64_t vbv_delay;
+
+    /**
+     * Type of service that the audio stream conveys.
+     * - encoding: Set by user.
+     * - decoding: Set by libavcodec.
+     */
+    enum AVAudioServiceType audio_service_type;
+
+    /**
+     * Used to request a sample format from the decoder.
+     * - encoding: unused.
+     * - decoding: Set by user.
+     */
+    enum AVSampleFormat request_sample_fmt;
+
+    /**
+     * Error recognition; may misdetect some more or less valid parts as errors.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int err_recognition;
+#define AV_EF_CRCCHECK  (1<<0)
+#define AV_EF_BITSTREAM (1<<1)
+#define AV_EF_BUFFER    (1<<2)
+#define AV_EF_EXPLODE   (1<<3)
+
+    /**
+     * Private context used for internal data.
+     *
+     * Unlike priv_data, this is not codec-specific. It is used in general
+     * libavcodec functions.
+     */
+    struct AVCodecInternal *internal;
+
+    /** Field order
+     * - encoding: set by libavcodec
+     * - decoding: Set by libavcodec
+     */
+    enum AVFieldOrder field_order;
+} AVCodecContext;
+
+/**
+ * AVProfile.
+ */
+typedef struct AVProfile {
+    int profile;
+    const char *name; ///< short name for the profile
+} AVProfile;
+
+typedef struct AVCodecDefault AVCodecDefault;
+
+/**
+ * AVCodec.
+ */
+typedef struct AVCodec {
+    /**
+     * Name of the codec implementation.
+     * The name is globally unique among encoders and among decoders (but an
+     * encoder and a decoder can share the same name).
+     * This is the primary way to find a codec from the user perspective.
+     */
+    const char *name;
+    enum AVMediaType type;
+    enum CodecID id;
+    int priv_data_size;
+    int (*init)(AVCodecContext *);
+    int (*encode)(AVCodecContext *, uint8_t *buf, int buf_size, void *data);
+    int (*close)(AVCodecContext *);
+    int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt);
+    /**
+     * Codec capabilities.
+     * see CODEC_CAP_*
+     */
+    int capabilities;
+    struct AVCodec *next;
+    /**
+     * Flush buffers.
+     * Will be called when seeking
+     */
+    void (*flush)(AVCodecContext *);
+    const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0}
+    const enum PixelFormat *pix_fmts;       ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1
+    /**
+     * Descriptive name for the codec, meant to be more human readable than name.
+     * You should use the NULL_IF_CONFIG_SMALL() macro to define it.
+     */
+    const char *long_name;
+    const int *supported_samplerates;       ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
+    const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
+    const uint64_t *channel_layouts;         ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
+    uint8_t max_lowres;                     ///< maximum value for lowres supported by the decoder
+    const AVClass *priv_class;              ///< AVClass for the private context
+    const AVProfile *profiles;              ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
+
+    /**
+     * @name Frame-level threading support functions
+     * @{
+     */
+    /**
+     * If defined, called on thread contexts when they are created.
+     * If the codec allocates writable tables in init(), re-allocate them here.
+     * priv_data will be set to a copy of the original.
+     */
+    int (*init_thread_copy)(AVCodecContext *);
+    /**
+     * Copy necessary context variables from a previous thread context to the current one.
+     * If not defined, the next thread will start automatically; otherwise, the codec
+     * must call ff_thread_finish_setup().
+     *
+     * dst and src will (rarely) point to the same context, in which case memcpy should be skipped.
+     */
+    int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src);
+    /** @} */
+
+    /**
+     * Private codec-specific defaults.
+     */
+    const AVCodecDefault *defaults;
+
+    /**
+     * Initialize codec static data, called from avcodec_register().
+     */
+    void (*init_static_data)(struct AVCodec *codec);
+
+    /**
+     * Encode data to an AVPacket.
+     *
+     * @param      avctx          codec context
+     * @param      avpkt          output AVPacket (may contain a user-provided buffer)
+     * @param[in]  frame          AVFrame containing the raw data to be encoded
+     * @param[out] got_packet_ptr encoder sets to 0 or 1 to indicate that a
+     *                            non-empty packet was returned in avpkt.
+     * @return 0 on success, negative error code on failure
+     */
+    int (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame,
+                   int *got_packet_ptr);
+} AVCodec;
+
+/**
+ * AVHWAccel.
+ */
+typedef struct AVHWAccel {
+    /**
+     * Name of the hardware accelerated codec.
+     * The name is globally unique among encoders and among decoders (but an
+     * encoder and a decoder can share the same name).
+     */
+    const char *name;
+
+    /**
+     * Type of codec implemented by the hardware accelerator.
+     *
+     * See AVMEDIA_TYPE_xxx
+     */
+    enum AVMediaType type;
+
+    /**
+     * Codec implemented by the hardware accelerator.
+     *
+     * See CODEC_ID_xxx
+     */
+    enum CodecID id;
+
+    /**
+     * Supported pixel format.
+     *
+     * Only hardware accelerated formats are supported here.
+     */
+    enum PixelFormat pix_fmt;
+
+    /**
+     * Hardware accelerated codec capabilities.
+     * see FF_HWACCEL_CODEC_CAP_*
+     */
+    int capabilities;
+
+    struct AVHWAccel *next;
+
+    /**
+     * Called at the beginning of each frame or field picture.
+     *
+     * Meaningful frame information (codec specific) is guaranteed to
+     * be parsed at this point. This function is mandatory.
+     *
+     * Note that buf can be NULL along with buf_size set to 0.
+     * Otherwise, this means the whole frame is available at this point.
+     *
+     * @param avctx the codec context
+     * @param buf the frame data buffer base
+     * @param buf_size the size of the frame in bytes
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*start_frame)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+    /**
+     * Callback for each slice.
+     *
+     * Meaningful slice information (codec specific) is guaranteed to
+     * be parsed at this point. This function is mandatory.
+     *
+     * @param avctx the codec context
+     * @param buf the slice data buffer base
+     * @param buf_size the size of the slice in bytes
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*decode_slice)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+    /**
+     * Called at the end of each frame or field picture.
+     *
+     * The whole picture is parsed at this point and can now be sent
+     * to the hardware accelerator. This function is mandatory.
+     *
+     * @param avctx the codec context
+     * @return zero if successful, a negative value otherwise
+     */
+    int (*end_frame)(AVCodecContext *avctx);
+
+    /**
+     * Size of HW accelerator private data.
+     *
+     * Private data is allocated with av_mallocz() before
+     * AVCodecContext.get_buffer() and deallocated after
+     * AVCodecContext.release_buffer().
+     */
+    int priv_data_size;
+} AVHWAccel;
+
+/**
+ * four components are given, that's all.
+ * the last component is alpha
+ */
+typedef struct AVPicture {
+    uint8_t *data[AV_NUM_DATA_POINTERS];
+    int linesize[AV_NUM_DATA_POINTERS];     ///< number of bytes per line
+} AVPicture;
+
+#define AVPALETTE_SIZE 1024
+#define AVPALETTE_COUNT 256
+#if FF_API_PALETTE_CONTROL
+/**
+ * AVPaletteControl
+ * This structure defines a method for communicating palette changes
+ * between and demuxer and a decoder.
+ *
+ * @deprecated Use AVPacket to send palette changes instead.
+ * This is totally broken.
+ */
+typedef struct AVPaletteControl {
+
+    /* Demuxer sets this to 1 to indicate the palette has changed;
+     * decoder resets to 0. */
+    int palette_changed;
+
+    /* 4-byte ARGB palette entries, stored in native byte order; note that
+     * the individual palette components should be on a 8-bit scale; if
+     * the palette data comes from an IBM VGA native format, the component
+     * data is probably 6 bits in size and needs to be scaled. */
+    unsigned int palette[AVPALETTE_COUNT];
+
+} AVPaletteControl attribute_deprecated;
+#endif
+
+enum AVSubtitleType {
+    SUBTITLE_NONE,
+
+    SUBTITLE_BITMAP,                ///< A bitmap, pict will be set
+
+    /**
+     * Plain text, the text field must be set by the decoder and is
+     * authoritative. ass and pict fields may contain approximations.
+     */
+    SUBTITLE_TEXT,
+
+    /**
+     * Formatted text, the ass field must be set by the decoder and is
+     * authoritative. pict and text fields may contain approximations.
+     */
+    SUBTITLE_ASS,
+};
+
+typedef struct AVSubtitleRect {
+    int x;         ///< top left corner  of pict, undefined when pict is not set
+    int y;         ///< top left corner  of pict, undefined when pict is not set
+    int w;         ///< width            of pict, undefined when pict is not set
+    int h;         ///< height           of pict, undefined when pict is not set
+    int nb_colors; ///< number of colors in pict, undefined when pict is not set
+
+    /**
+     * data+linesize for the bitmap of this subtitle.
+     * can be set for text/ass as well once they where rendered
+     */
+    AVPicture pict;
+    enum AVSubtitleType type;
+
+    char *text;                     ///< 0 terminated plain UTF-8 text
+
+    /**
+     * 0 terminated ASS/SSA compatible event line.
+     * The pressentation of this is unaffected by the other values in this
+     * struct.
+     */
+    char *ass;
+} AVSubtitleRect;
+
+typedef struct AVSubtitle {
+    uint16_t format; /* 0 = graphics */
+    uint32_t start_display_time; /* relative to packet pts, in ms */
+    uint32_t end_display_time; /* relative to packet pts, in ms */
+    unsigned num_rects;
+    AVSubtitleRect **rects;
+    int64_t pts;    ///< Same as packet pts, in AV_TIME_BASE
+} AVSubtitle;
+
+/* packet functions */
+
+/**
+ * @deprecated use NULL instead
+ */
+attribute_deprecated void av_destruct_packet_nofree(AVPacket *pkt);
+
+/**
+ * Default packet destructor.
+ */
+void av_destruct_packet(AVPacket *pkt);
+
+/**
+ * Initialize optional fields of a packet with default values.
+ *
+ * @param pkt packet
+ */
+void av_init_packet(AVPacket *pkt);
+
+/**
+ * Allocate the payload of a packet and initialize its fields with
+ * default values.
+ *
+ * @param pkt packet
+ * @param size wanted payload size
+ * @return 0 if OK, AVERROR_xxx otherwise
+ */
+int av_new_packet(AVPacket *pkt, int size);
+
+/**
+ * Reduce packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param size new size
+ */
+void av_shrink_packet(AVPacket *pkt, int size);
+
+/**
+ * Increase packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param grow_by number of bytes by which to increase the size of the packet
+ */
+int av_grow_packet(AVPacket *pkt, int grow_by);
+
+/**
+ * @warning This is a hack - the packet memory allocation stuff is broken. The
+ * packet is allocated if it was not really allocated.
+ */
+int av_dup_packet(AVPacket *pkt);
+
+/**
+ * Free a packet.
+ *
+ * @param pkt packet to free
+ */
+void av_free_packet(AVPacket *pkt);
+
+/**
+ * Allocate new information of a packet.
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size side information size
+ * @return pointer to fresh allocated data or NULL otherwise
+ */
+uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int size);
+
+/**
+ * Get side information from packet.
+ *
+ * @param pkt packet
+ * @param type desired side information type
+ * @param size pointer for side information size to store (optional)
+ * @return pointer to data if present or NULL otherwise
+ */
+uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+                                 int *size);
+
+/* resample.c */
+
+struct ReSampleContext;
+struct AVResampleContext;
+
+typedef struct ReSampleContext ReSampleContext;
+
+/**
+ *  Initialize audio resampling context.
+ *
+ * @param output_channels  number of output channels
+ * @param input_channels   number of input channels
+ * @param output_rate      output sample rate
+ * @param input_rate       input sample rate
+ * @param sample_fmt_out   requested output sample format
+ * @param sample_fmt_in    input sample format
+ * @param filter_length    length of each FIR filter in the filterbank relative to the cutoff frequency
+ * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
+ * @param linear           if 1 then the used FIR filter will be linearly interpolated
+                           between the 2 closest, if 0 the closest will be used
+ * @param cutoff           cutoff frequency, 1.0 corresponds to half the output sampling rate
+ * @return allocated ReSampleContext, NULL if error occurred
+ */
+ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
+                                        int output_rate, int input_rate,
+                                        enum AVSampleFormat sample_fmt_out,
+                                        enum AVSampleFormat sample_fmt_in,
+                                        int filter_length, int log2_phase_count,
+                                        int linear, double cutoff);
+
+int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples);
+
+/**
+ * Free resample context.
+ *
+ * @param s a non-NULL pointer to a resample context previously
+ *          created with av_audio_resample_init()
+ */
+void audio_resample_close(ReSampleContext *s);
+
+
+/**
+ * Initialize an audio resampler.
+ * Note, if either rate is not an integer then simply scale both rates up so they are.
+ * @param filter_length length of each FIR filter in the filterbank relative to the cutoff freq
+ * @param log2_phase_count log2 of the number of entries in the polyphase filterbank
+ * @param linear If 1 then the used FIR filter will be linearly interpolated
+                 between the 2 closest, if 0 the closest will be used
+ * @param cutoff cutoff frequency, 1.0 corresponds to half the output sampling rate
+ */
+struct AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_length, int log2_phase_count, int linear, double cutoff);
+
+/**
+ * Resample an array of samples using a previously configured context.
+ * @param src an array of unconsumed samples
+ * @param consumed the number of samples of src which have been consumed are returned here
+ * @param src_size the number of unconsumed samples available
+ * @param dst_size the amount of space in samples available in dst
+ * @param update_ctx If this is 0 then the context will not be modified, that way several channels can be resampled with the same context.
+ * @return the number of samples written in dst or -1 if an error occurred
+ */
+int av_resample(struct AVResampleContext *c, short *dst, short *src, int *consumed, int src_size, int dst_size, int update_ctx);
+
+
+/**
+ * Compensate samplerate/timestamp drift. The compensation is done by changing
+ * the resampler parameters, so no audible clicks or similar distortions occur
+ * @param compensation_distance distance in output samples over which the compensation should be performed
+ * @param sample_delta number of output samples which should be output less
+ *
+ * example: av_resample_compensate(c, 10, 500)
+ * here instead of 510 samples only 500 samples would be output
+ *
+ * note, due to rounding the actual compensation might be slightly different,
+ * especially if the compensation_distance is large and the in_rate used during init is small
+ */
+void av_resample_compensate(struct AVResampleContext *c, int sample_delta, int compensation_distance);
+void av_resample_close(struct AVResampleContext *c);
+
+/**
+ * Allocate memory for a picture.  Call avpicture_free() to free it.
+ *
+ * @see avpicture_fill()
+ *
+ * @param picture the picture to be filled in
+ * @param pix_fmt the format of the picture
+ * @param width the width of the picture
+ * @param height the height of the picture
+ * @return zero if successful, a negative value if not
+ */
+int avpicture_alloc(AVPicture *picture, enum PixelFormat pix_fmt, int width, int height);
+
+/**
+ * Free a picture previously allocated by avpicture_alloc().
+ * The data buffer used by the AVPicture is freed, but the AVPicture structure
+ * itself is not.
+ *
+ * @param picture the AVPicture to be freed
+ */
+void avpicture_free(AVPicture *picture);
+
+/**
+ * Fill in the AVPicture fields.
+ * The fields of the given AVPicture are filled in by using the 'ptr' address
+ * which points to the image data buffer. Depending on the specified picture
+ * format, one or multiple image data pointers and line sizes will be set.
+ * If a planar format is specified, several pointers will be set pointing to
+ * the different picture planes and the line sizes of the different planes
+ * will be stored in the lines_sizes array.
+ * Call with ptr == NULL to get the required size for the ptr buffer.
+ *
+ * To allocate the buffer and fill in the AVPicture fields in one call,
+ * use avpicture_alloc().
+ *
+ * @param picture AVPicture whose fields are to be filled in
+ * @param ptr Buffer which will contain or contains the actual image data
+ * @param pix_fmt The format in which the picture data is stored.
+ * @param width the width of the image in pixels
+ * @param height the height of the image in pixels
+ * @return size of the image data in bytes
+ */
+int avpicture_fill(AVPicture *picture, uint8_t *ptr,
+                   enum PixelFormat pix_fmt, int width, int height);
+
+/**
+ * Copy pixel data from an AVPicture into a buffer.
+ * The data is stored compactly, without any gaps for alignment or padding
+ * which may be applied by avpicture_fill().
+ *
+ * @see avpicture_get_size()
+ *
+ * @param[in] src AVPicture containing image data
+ * @param[in] pix_fmt The format in which the picture data is stored.
+ * @param[in] width the width of the image in pixels.
+ * @param[in] height the height of the image in pixels.
+ * @param[out] dest A buffer into which picture data will be copied.
+ * @param[in] dest_size The size of 'dest'.
+ * @return The number of bytes written to dest, or a negative value (error code) on error.
+ */
+int avpicture_layout(const AVPicture* src, enum PixelFormat pix_fmt, int width, int height,
+                     unsigned char *dest, int dest_size);
+
+/**
+ * Calculate the size in bytes that a picture of the given width and height
+ * would occupy if stored in the given picture format.
+ * Note that this returns the size of a compact representation as generated
+ * by avpicture_layout(), which can be smaller than the size required for e.g.
+ * avpicture_fill().
+ *
+ * @param pix_fmt the given picture format
+ * @param width the width of the image
+ * @param height the height of the image
+ * @return Image data size in bytes or -1 on error (e.g. too large dimensions).
+ */
+int avpicture_get_size(enum PixelFormat pix_fmt, int width, int height);
+void avcodec_get_chroma_sub_sample(enum PixelFormat pix_fmt, int *h_shift, int *v_shift);
+
+#if FF_API_GET_PIX_FMT_NAME
+/**
+ * @deprecated Deprecated in favor of av_get_pix_fmt_name().
+ */
+attribute_deprecated
+const char *avcodec_get_pix_fmt_name(enum PixelFormat pix_fmt);
+#endif
+
+void avcodec_set_dimensions(AVCodecContext *s, int width, int height);
+
+/**
+ * Return a value representing the fourCC code associated to the
+ * pixel format pix_fmt, or 0 if no associated fourCC code can be
+ * found.
+ */
+unsigned int avcodec_pix_fmt_to_codec_tag(enum PixelFormat pix_fmt);
+
+/**
+ * Put a string representing the codec tag codec_tag in buf.
+ *
+ * @param buf_size size in bytes of buf
+ * @return the length of the string that would have been generated if
+ * enough space had been available, excluding the trailing null
+ */
+size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag);
+
+#define FF_LOSS_RESOLUTION  0x0001 /**< loss due to resolution change */
+#define FF_LOSS_DEPTH       0x0002 /**< loss due to color depth change */
+#define FF_LOSS_COLORSPACE  0x0004 /**< loss due to color space conversion */
+#define FF_LOSS_ALPHA       0x0008 /**< loss of alpha bits */
+#define FF_LOSS_COLORQUANT  0x0010 /**< loss due to color quantization */
+#define FF_LOSS_CHROMA      0x0020 /**< loss of chroma (e.g. RGB to gray conversion) */
+
+/**
+ * Compute what kind of losses will occur when converting from one specific
+ * pixel format to another.
+ * When converting from one pixel format to another, information loss may occur.
+ * For example, when converting from RGB24 to GRAY, the color information will
+ * be lost. Similarly, other losses occur when converting from some formats to
+ * other formats. These losses can involve loss of chroma, but also loss of
+ * resolution, loss of color depth, loss due to the color space conversion, loss
+ * of the alpha bits or loss due to color quantization.
+ * avcodec_get_fix_fmt_loss() informs you about the various types of losses
+ * which will occur when converting from one pixel format to another.
+ *
+ * @param[in] dst_pix_fmt destination pixel format
+ * @param[in] src_pix_fmt source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @return Combination of flags informing you what kind of losses will occur.
+ */
+int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_pix_fmt,
+                             int has_alpha);
+
+/**
+ * Find the best pixel format to convert to given a certain source pixel
+ * format.  When converting from one pixel format to another, information loss
+ * may occur.  For example, when converting from RGB24 to GRAY, the color
+ * information will be lost. Similarly, other losses occur when converting from
+ * some formats to other formats. avcodec_find_best_pix_fmt() searches which of
+ * the given pixel formats should be used to suffer the least amount of loss.
+ * The pixel formats from which it chooses one, are determined by the
+ * pix_fmt_mask parameter.
+ *
+ * @code
+ * src_pix_fmt = PIX_FMT_YUV420P;
+ * pix_fmt_mask = (1 << PIX_FMT_YUV422P) || (1 << PIX_FMT_RGB24);
+ * dst_pix_fmt = avcodec_find_best_pix_fmt(pix_fmt_mask, src_pix_fmt, alpha, &loss);
+ * @endcode
+ *
+ * @param[in] pix_fmt_mask bitmask determining which pixel format to choose from
+ * @param[in] src_pix_fmt source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur.
+ * @return The best pixel format to convert to or -1 if none was found.
+ */
+enum PixelFormat avcodec_find_best_pix_fmt(int64_t pix_fmt_mask, enum PixelFormat src_pix_fmt,
+                              int has_alpha, int *loss_ptr);
+
+#if FF_API_GET_ALPHA_INFO
+#define FF_ALPHA_TRANSP       0x0001 /* image has some totally transparent pixels */
+#define FF_ALPHA_SEMI_TRANSP  0x0002 /* image has some transparent pixels */
+
+/**
+ * Tell if an image really has transparent alpha values.
+ * @return ored mask of FF_ALPHA_xxx constants
+ */
+attribute_deprecated
+int img_get_alpha_info(const AVPicture *src,
+                       enum PixelFormat pix_fmt, int width, int height);
+#endif
+
+/* deinterlace a picture */
+/* deinterlace - if not supported return -1 */
+int avpicture_deinterlace(AVPicture *dst, const AVPicture *src,
+                          enum PixelFormat pix_fmt, int width, int height);
+
+/* external high level API */
+
+/**
+ * If c is NULL, returns the first registered codec,
+ * if c is non-NULL, returns the next registered codec after c,
+ * or NULL if c is the last one.
+ */
+AVCodec *av_codec_next(AVCodec *c);
+
+/**
+ * Return the LIBAVCODEC_VERSION_INT constant.
+ */
+unsigned avcodec_version(void);
+
+/**
+ * Return the libavcodec build-time configuration.
+ */
+const char *avcodec_configuration(void);
+
+/**
+ * Return the libavcodec license.
+ */
+const char *avcodec_license(void);
+
+#if FF_API_AVCODEC_INIT
+/**
+ * @deprecated this function is called automatically from avcodec_register()
+ * and avcodec_register_all(), there is no need to call it manually
+ */
+attribute_deprecated
+void avcodec_init(void);
+#endif
+
+/**
+ * Register the codec codec and initialize libavcodec.
+ *
+ * @warning either this function or avcodec_register_all() must be called
+ * before any other libavcodec functions.
+ *
+ * @see avcodec_register_all()
+ */
+void avcodec_register(AVCodec *codec);
+
+/**
+ * Find a registered encoder with a matching codec ID.
+ *
+ * @param id CodecID of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder(enum CodecID id);
+
+/**
+ * Find a registered encoder with the specified name.
+ *
+ * @param name name of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder_by_name(const char *name);
+
+/**
+ * Find a registered decoder with a matching codec ID.
+ *
+ * @param id CodecID of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder(enum CodecID id);
+
+/**
+ * Find a registered decoder with the specified name.
+ *
+ * @param name name of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder_by_name(const char *name);
+void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode);
+
+/**
+ * Return a name for the specified profile, if available.
+ *
+ * @param codec the codec that is searched for the given profile
+ * @param profile the profile value for which a name is requested
+ * @return A name for the profile if found, NULL otherwise.
+ */
+const char *av_get_profile_name(const AVCodec *codec, int profile);
+
+#if FF_API_ALLOC_CONTEXT
+/**
+ * Set the fields of the given AVCodecContext to default values.
+ *
+ * @param s The AVCodecContext of which the fields should be set to default values.
+ * @deprecated use avcodec_get_context_defaults3
+ */
+attribute_deprecated
+void avcodec_get_context_defaults(AVCodecContext *s);
+
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+attribute_deprecated
+void avcodec_get_context_defaults2(AVCodecContext *s, enum AVMediaType);
+#endif
+
+/**
+ * Set the fields of the given AVCodecContext to default values corresponding
+ * to the given codec (defaults may be codec-dependent).
+ *
+ * Do not call this function if a non-NULL codec has been passed
+ * to avcodec_alloc_context3() that allocated this AVCodecContext.
+ * If codec is non-NULL, it is illegal to call avcodec_open2() with a
+ * different codec on this AVCodecContext.
+ */
+int avcodec_get_context_defaults3(AVCodecContext *s, AVCodec *codec);
+
+#if FF_API_ALLOC_CONTEXT
+/**
+ * Allocate an AVCodecContext and set its fields to default values.  The
+ * resulting struct can be deallocated by simply calling av_free().
+ *
+ * @return An AVCodecContext filled with default values or NULL on failure.
+ * @see avcodec_get_context_defaults
+ *
+ * @deprecated use avcodec_alloc_context3()
+ */
+attribute_deprecated
+AVCodecContext *avcodec_alloc_context(void);
+
+/** THIS FUNCTION IS NOT YET PART OF THE PUBLIC API!
+ *  we WILL change its arguments and name a few times! */
+attribute_deprecated
+AVCodecContext *avcodec_alloc_context2(enum AVMediaType);
+#endif
+
+/**
+ * Allocate an AVCodecContext and set its fields to default values.  The
+ * resulting struct can be deallocated by calling avcodec_close() on it followed
+ * by av_free().
+ *
+ * @param codec if non-NULL, allocate private data and initialize defaults
+ *              for the given codec. It is illegal to then call avcodec_open2()
+ *              with a different codec.
+ *
+ * @return An AVCodecContext filled with default values or NULL on failure.
+ * @see avcodec_get_context_defaults
+ */
+AVCodecContext *avcodec_alloc_context3(AVCodec *codec);
+
+/**
+ * Copy the settings of the source AVCodecContext into the destination
+ * AVCodecContext. The resulting destination codec context will be
+ * unopened, i.e. you are required to call avcodec_open2() before you
+ * can use this AVCodecContext to decode/encode video/audio data.
+ *
+ * @param dest target codec context, should be initialized with
+ *             avcodec_alloc_context3(), but otherwise uninitialized
+ * @param src source codec context
+ * @return AVERROR() on error (e.g. memory allocation error), 0 on success
+ */
+int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src);
+
+/**
+ * Set the fields of the given AVFrame to default values.
+ *
+ * @param pic The AVFrame of which the fields should be set to default values.
+ */
+void avcodec_get_frame_defaults(AVFrame *pic);
+
+/**
+ * Allocate an AVFrame and set its fields to default values.  The resulting
+ * struct can be deallocated by simply calling av_free().
+ *
+ * @return An AVFrame filled with default values or NULL on failure.
+ * @see avcodec_get_frame_defaults
+ */
+AVFrame *avcodec_alloc_frame(void);
+
+int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic);
+void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic);
+int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic);
+
+/**
+ * Return the amount of padding in pixels which the get_buffer callback must
+ * provide around the edge of the image for codecs which do not have the
+ * CODEC_FLAG_EMU_EDGE flag.
+ *
+ * @return Required padding in pixels.
+ */
+unsigned avcodec_get_edge_width(void);
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you do not use any horizontal
+ * padding.
+ *
+ * May only be used if a codec with CODEC_CAP_DR1 has been opened.
+ * If CODEC_FLAG_EMU_EDGE is not set, the dimensions must have been increased
+ * according to avcodec_get_edge_width() before.
+ */
+void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height);
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you also ensure that all
+ * line sizes are a multiple of the respective linesize_align[i].
+ *
+ * May only be used if a codec with CODEC_CAP_DR1 has been opened.
+ * If CODEC_FLAG_EMU_EDGE is not set, the dimensions must have been increased
+ * according to avcodec_get_edge_width() before.
+ */
+void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
+                               int linesize_align[AV_NUM_DATA_POINTERS]);
+
+enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat * fmt);
+
+#if FF_API_THREAD_INIT
+/**
+ * @deprecated Set s->thread_count before calling avcodec_open2() instead of calling this.
+ */
+attribute_deprecated
+int avcodec_thread_init(AVCodecContext *s, int thread_count);
+#endif
+
+int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size);
+int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count);
+//FIXME func typedef
+
+#if FF_API_AVCODEC_OPEN
+/**
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
+ * function the context has to be allocated.
+ *
+ * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
+ * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
+ * retrieving a codec.
+ *
+ * @warning This function is not thread safe!
+ *
+ * @code
+ * avcodec_register_all();
+ * codec = avcodec_find_decoder(CODEC_ID_H264);
+ * if (!codec)
+ *     exit(1);
+ *
+ * context = avcodec_alloc_context3(codec);
+ *
+ * if (avcodec_open(context, codec) < 0)
+ *     exit(1);
+ * @endcode
+ *
+ * @param avctx The context which will be set up to use the given codec.
+ * @param codec The codec to use within the context.
+ * @return zero on success, a negative value on error
+ * @see avcodec_alloc_context3, avcodec_find_decoder, avcodec_find_encoder, avcodec_close
+ *
+ * @deprecated use avcodec_open2
+ */
+attribute_deprecated
+int avcodec_open(AVCodecContext *avctx, AVCodec *codec);
+#endif
+
+/**
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
+ * function the context has to be allocated with avcodec_alloc_context3().
+ *
+ * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
+ * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
+ * retrieving a codec.
+ *
+ * @warning This function is not thread safe!
+ *
+ * @code
+ * avcodec_register_all();
+ * av_dict_set(&opts, "b", "2.5M", 0);
+ * codec = avcodec_find_decoder(CODEC_ID_H264);
+ * if (!codec)
+ *     exit(1);
+ *
+ * context = avcodec_alloc_context3(codec);
+ *
+ * if (avcodec_open2(context, codec, opts) < 0)
+ *     exit(1);
+ * @endcode
+ *
+ * @param avctx The context to initialize.
+ * @param codec The codec to open this context for. If a non-NULL codec has been
+ *              previously passed to avcodec_alloc_context3() or
+ *              avcodec_get_context_defaults3() for this context, then this
+ *              parameter MUST be either NULL or equal to the previously passed
+ *              codec.
+ * @param options A dictionary filled with AVCodecContext and codec-private options.
+ *                On return this object will be filled with options that were not found.
+ *
+ * @return zero on success, a negative value on error
+ * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(),
+ *      av_dict_set(), av_opt_find().
+ */
+int avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options);
+
+#if FF_API_OLD_DECODE_AUDIO
+/**
+ * Wrapper function which calls avcodec_decode_audio4.
+ *
+ * @deprecated Use avcodec_decode_audio4 instead.
+ *
+ * Decode the audio frame of size avpkt->size from avpkt->data into samples.
+ * Some decoders may support multiple frames in a single AVPacket, such
+ * decoders would then just decode the first frame. In this case,
+ * avcodec_decode_audio3 has to be called again with an AVPacket that contains
+ * the remaining data in order to decode the second frame etc.
+ * If no frame
+ * could be outputted, frame_size_ptr is zero. Otherwise, it is the
+ * decompressed frame size in bytes.
+ *
+ * @warning You must set frame_size_ptr to the allocated size of the
+ * output buffer before calling avcodec_decode_audio3().
+ *
+ * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than
+ * the actual read bytes because some optimized bitstream readers read 32 or 64
+ * bits at once and could read over the end.
+ *
+ * @warning The end of the input buffer avpkt->data should be set to 0 to ensure that
+ * no overreading happens for damaged MPEG streams.
+ *
+ * @warning You must not provide a custom get_buffer() when using
+ * avcodec_decode_audio3().  Doing so will override it with
+ * avcodec_default_get_buffer.  Use avcodec_decode_audio4() instead,
+ * which does allow the application to provide a custom get_buffer().
+ *
+ * @note You might have to align the input buffer avpkt->data and output buffer
+ * samples. The alignment requirements depend on the CPU: On some CPUs it isn't
+ * necessary at all, on others it won't work at all if not aligned and on others
+ * it will work but it will have an impact on performance.
+ *
+ * In practice, avpkt->data should have 4 byte alignment at minimum and
+ * samples should be 16 byte aligned unless the CPU doesn't need it
+ * (AltiVec and SSE do).
+ *
+ * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay
+ * between input and output, these need to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to return the remaining frames.
+ *
+ * @param avctx the codec context
+ * @param[out] samples the output buffer, sample type in avctx->sample_fmt
+ *                     If the sample format is planar, each channel plane will
+ *                     be the same size, with no padding between channels.
+ * @param[in,out] frame_size_ptr the output buffer size in bytes
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ *            You can create such packet with av_init_packet() and by then setting
+ *            data and size, some decoders might in addition need other fields.
+ *            All decoders are designed to use the least fields possible though.
+ * @return On error a negative value is returned, otherwise the number of bytes
+ * used or zero if no frame data was decompressed (used) from the input AVPacket.
+ */
+attribute_deprecated int avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
+                         int *frame_size_ptr,
+                         AVPacket *avpkt);
+#endif
+
+/**
+ * Decode the audio frame of size avpkt->size from avpkt->data into frame.
+ *
+ * Some decoders may support multiple frames in a single AVPacket. Such
+ * decoders would then just decode the first frame. In this case,
+ * avcodec_decode_audio4 has to be called again with an AVPacket containing
+ * the remaining data in order to decode the second frame, etc...
+ * Even if no frames are returned, the packet needs to be fed to the decoder
+ * with remaining data until it is completely consumed or an error occurs.
+ *
+ * @warning The input buffer, avpkt->data must be FF_INPUT_BUFFER_PADDING_SIZE
+ *          larger than the actual read bytes because some optimized bitstream
+ *          readers read 32 or 64 bits at once and could read over the end.
+ *
+ * @note You might have to align the input buffer. The alignment requirements
+ *       depend on the CPU and the decoder.
+ *
+ * @param      avctx the codec context
+ * @param[out] frame The AVFrame in which to store decoded audio samples.
+ *                   Decoders request a buffer of a particular size by setting
+ *                   AVFrame.nb_samples prior to calling get_buffer(). The
+ *                   decoder may, however, only utilize part of the buffer by
+ *                   setting AVFrame.nb_samples to a smaller value in the
+ *                   output frame.
+ * @param[out] got_frame_ptr Zero if no frame could be decoded, otherwise it is
+ *                           non-zero.
+ * @param[in]  avpkt The input AVPacket containing the input buffer.
+ *                   At least avpkt->data and avpkt->size should be set. Some
+ *                   decoders might also require additional fields to be set.
+ * @return A negative error code is returned if an error occurred during
+ *         decoding, otherwise the number of bytes consumed from the input
+ *         AVPacket is returned.
+ */
+int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame,
+                          int *got_frame_ptr, AVPacket *avpkt);
+
+/**
+ * Decode the video frame of size avpkt->size from avpkt->data into picture.
+ * Some decoders may support multiple frames in a single AVPacket, such
+ * decoders would then just decode the first frame.
+ *
+ * @warning The input buffer must be FF_INPUT_BUFFER_PADDING_SIZE larger than
+ * the actual read bytes because some optimized bitstream readers read 32 or 64
+ * bits at once and could read over the end.
+ *
+ * @warning The end of the input buffer buf should be set to 0 to ensure that
+ * no overreading happens for damaged MPEG streams.
+ *
+ * @note You might have to align the input buffer avpkt->data.
+ * The alignment requirements depend on the CPU: on some CPUs it isn't
+ * necessary at all, on others it won't work at all if not aligned and on others
+ * it will work but it will have an impact on performance.
+ *
+ * In practice, avpkt->data should have 4 byte alignment at minimum.
+ *
+ * @note Codecs which have the CODEC_CAP_DELAY capability set have a delay
+ * between input and output, these need to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to return the remaining frames.
+ *
+ * @param avctx the codec context
+ * @param[out] picture The AVFrame in which the decoded video frame will be stored.
+ *             Use avcodec_alloc_frame to get an AVFrame, the codec will
+ *             allocate memory for the actual bitmap.
+ *             with default get/release_buffer(), the decoder frees/reuses the bitmap as it sees fit.
+ *             with overridden get/release_buffer() (needs CODEC_CAP_DR1) the user decides into what buffer the decoder
+ *                   decodes and the decoder tells the user once it does not need the data anymore,
+ *                   the user app can at this point free/reuse/keep the memory as it sees fit.
+ *
+ * @param[in] avpkt The input AVpacket containing the input buffer.
+ *            You can create such packet with av_init_packet() and by then setting
+ *            data and size, some decoders might in addition need other fields like
+ *            flags&AV_PKT_FLAG_KEY. All decoders are designed to use the least
+ *            fields possible.
+ * @param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero.
+ * @return On error a negative value is returned, otherwise the number of bytes
+ * used or zero if no frame could be decompressed.
+ */
+int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
+                         int *got_picture_ptr,
+                         AVPacket *avpkt);
+
+/**
+ * Decode a subtitle message.
+ * Return a negative value on error, otherwise return the number of bytes used.
+ * If no subtitle could be decompressed, got_sub_ptr is zero.
+ * Otherwise, the subtitle is stored in *sub.
+ * Note that CODEC_CAP_DR1 is not available for subtitle codecs. This is for
+ * simplicity, because the performance difference is expect to be negligible
+ * and reusing a get_buffer written for video codecs would probably perform badly
+ * due to a potentially very different allocation pattern.
+ *
+ * @param avctx the codec context
+ * @param[out] sub The AVSubtitle in which the decoded subtitle will be stored, must be
+                   freed with avsubtitle_free if *got_sub_ptr is set.
+ * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero.
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ */
+int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
+                            int *got_sub_ptr,
+                            AVPacket *avpkt);
+
+/**
+ * Free all allocated data in the given subtitle struct.
+ *
+ * @param sub AVSubtitle to free.
+ */
+void avsubtitle_free(AVSubtitle *sub);
+
+#if FF_API_OLD_ENCODE_AUDIO
+/**
+ * Encode an audio frame from samples into buf.
+ *
+ * @deprecated Use avcodec_encode_audio2 instead.
+ *
+ * @note The output buffer should be at least FF_MIN_BUFFER_SIZE bytes large.
+ * However, for codecs with avctx->frame_size equal to 0 (e.g. PCM) the user
+ * will know how much space is needed because it depends on the value passed
+ * in buf_size as described below. In that case a lower value can be used.
+ *
+ * @param avctx the codec context
+ * @param[out] buf the output buffer
+ * @param[in] buf_size the output buffer size
+ * @param[in] samples the input buffer containing the samples
+ * The number of samples read from this buffer is frame_size*channels,
+ * both of which are defined in avctx.
+ * For codecs which have avctx->frame_size equal to 0 (e.g. PCM) the number of
+ * samples read from samples is equal to:
+ * buf_size * 8 / (avctx->channels * av_get_bits_per_sample(avctx->codec_id))
+ * This also implies that av_get_bits_per_sample() must not return 0 for these
+ * codecs.
+ * @return On error a negative value is returned, on success zero or the number
+ * of bytes used to encode the data read from the input buffer.
+ */
+int attribute_deprecated avcodec_encode_audio(AVCodecContext *avctx,
+                                              uint8_t *buf, int buf_size,
+                                              const short *samples);
+#endif
+
+/**
+ * Encode a frame of audio.
+ *
+ * Takes input samples from frame and writes the next output packet, if
+ * available, to avpkt. The output packet does not necessarily contain data for
+ * the most recent frame, as encoders can delay, split, and combine input frames
+ * internally as needed.
+ *
+ * @param avctx     codec context
+ * @param avpkt     output AVPacket.
+ *                  The user can supply an output buffer by setting
+ *                  avpkt->data and avpkt->size prior to calling the
+ *                  function, but if the size of the user-provided data is not
+ *                  large enough, encoding will fail. All other AVPacket fields
+ *                  will be reset by the encoder using av_init_packet(). If
+ *                  avpkt->data is NULL, the encoder will allocate it.
+ *                  The encoder will set avpkt->size to the size of the
+ *                  output packet.
+ * @param[in] frame AVFrame containing the raw audio data to be encoded.
+ *                  May be NULL when flushing an encoder that has the
+ *                  CODEC_CAP_DELAY capability set.
+ *                  There are 2 codec capabilities that affect the allowed
+ *                  values of frame->nb_samples.
+ *                  If CODEC_CAP_SMALL_LAST_FRAME is set, then only the final
+ *                  frame may be smaller than avctx->frame_size, and all other
+ *                  frames must be equal to avctx->frame_size.
+ *                  If CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame
+ *                  can have any number of samples.
+ *                  If neither is set, frame->nb_samples must be equal to
+ *                  avctx->frame_size for all frames.
+ * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the
+ *                            output packet is non-empty, and to 0 if it is
+ *                            empty. If the function returns an error, the
+ *                            packet can be assumed to be invalid, and the
+ *                            value of got_packet_ptr is undefined and should
+ *                            not be used.
+ * @return          0 on success, negative error code on failure
+ */
+int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt,
+                          const AVFrame *frame, int *got_packet_ptr);
+
+/**
+ * Fill audio frame data and linesize.
+ * AVFrame extended_data channel pointers are allocated if necessary for
+ * planar audio.
+ *
+ * @param frame       the AVFrame
+ *                    frame->nb_samples must be set prior to calling the
+ *                    function. This function fills in frame->data,
+ *                    frame->extended_data, frame->linesize[0].
+ * @param nb_channels channel count
+ * @param sample_fmt  sample format
+ * @param buf         buffer to use for frame data
+ * @param buf_size    size of buffer
+ * @param align       plane size sample alignment
+ * @return            0 on success, negative error code on failure
+ */
+int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
+                             enum AVSampleFormat sample_fmt, const uint8_t *buf,
+                             int buf_size, int align);
+
+/**
+ * Encode a video frame from pict into buf.
+ * The input picture should be
+ * stored using a specific format, namely avctx.pix_fmt.
+ *
+ * @param avctx the codec context
+ * @param[out] buf the output buffer for the bitstream of encoded frame
+ * @param[in] buf_size the size of the output buffer in bytes
+ * @param[in] pict the input picture to encode
+ * @return On error a negative value is returned, on success zero or the number
+ * of bytes used from the output buffer.
+ */
+int avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
+                         const AVFrame *pict);
+int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
+                            const AVSubtitle *sub);
+
+/**
+ * Close a given AVCodecContext and free all the data associated with it
+ * (but not the AVCodecContext itself).
+ *
+ * Calling this function on an AVCodecContext that hasn't been opened will free
+ * the codec-specific data allocated in avcodec_alloc_context3() /
+ * avcodec_get_context_defaults3() with a non-NULL codec. Subsequent calls will
+ * do nothing.
+ */
+int avcodec_close(AVCodecContext *avctx);
+
+/**
+ * Register all the codecs, parsers and bitstream filters which were enabled at
+ * configuration time. If you do not call this function you can select exactly
+ * which formats you want to support, by using the individual registration
+ * functions.
+ *
+ * @see avcodec_register
+ * @see av_register_codec_parser
+ * @see av_register_bitstream_filter
+ */
+void avcodec_register_all(void);
+
+/**
+ * Flush buffers, should be called when seeking or when switching to a different stream.
+ */
+void avcodec_flush_buffers(AVCodecContext *avctx);
+
+void avcodec_default_free_buffers(AVCodecContext *s);
+
+/* misc useful functions */
+
+#if FF_API_OLD_FF_PICT_TYPES
+/**
+ * Return a single letter to describe the given picture type pict_type.
+ *
+ * @param[in] pict_type the picture type
+ * @return A single character representing the picture type.
+ * @deprecated Use av_get_picture_type_char() instead.
+ */
+attribute_deprecated
+char av_get_pict_type_char(int pict_type);
+#endif
+
+/**
+ * Return codec bits per sample.
+ *
+ * @param[in] codec_id the codec
+ * @return Number of bits per sample or zero if unknown for the given codec.
+ */
+int av_get_bits_per_sample(enum CodecID codec_id);
+
+#if FF_API_OLD_SAMPLE_FMT
+/**
+ * @deprecated Use av_get_bytes_per_sample() instead.
+ */
+attribute_deprecated
+int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt);
+#endif
+
+/* frame parsing */
+typedef struct AVCodecParserContext {
+    void *priv_data;
+    struct AVCodecParser *parser;
+    int64_t frame_offset; /* offset of the current frame */
+    int64_t cur_offset; /* current offset
+                           (incremented by each av_parser_parse()) */
+    int64_t next_frame_offset; /* offset of the next frame */
+    /* video info */
+    int pict_type; /* XXX: Put it back in AVCodecContext. */
+    /**
+     * This field is used for proper frame duration computation in lavf.
+     * It signals, how much longer the frame duration of the current frame
+     * is compared to normal frame duration.
+     *
+     * frame_duration = (1 + repeat_pict) * time_base
+     *
+     * It is used by codecs like H.264 to display telecined material.
+     */
+    int repeat_pict; /* XXX: Put it back in AVCodecContext. */
+    int64_t pts;     /* pts of the current frame */
+    int64_t dts;     /* dts of the current frame */
+
+    /* private data */
+    int64_t last_pts;
+    int64_t last_dts;
+    int fetch_timestamp;
+
+#define AV_PARSER_PTS_NB 4
+    int cur_frame_start_index;
+    int64_t cur_frame_offset[AV_PARSER_PTS_NB];
+    int64_t cur_frame_pts[AV_PARSER_PTS_NB];
+    int64_t cur_frame_dts[AV_PARSER_PTS_NB];
+
+    int flags;
+#define PARSER_FLAG_COMPLETE_FRAMES           0x0001
+#define PARSER_FLAG_ONCE                      0x0002
+/// Set if the parser has a valid file offset
+#define PARSER_FLAG_FETCHED_OFFSET            0x0004
+
+    int64_t offset;      ///< byte offset from starting packet start
+    int64_t cur_frame_end[AV_PARSER_PTS_NB];
+
+    /**
+     * Set by parser to 1 for key frames and 0 for non-key frames.
+     * It is initialized to -1, so if the parser doesn't set this flag,
+     * old-style fallback using AV_PICTURE_TYPE_I picture type as key frames
+     * will be used.
+     */
+    int key_frame;
+
+    /**
+     * Time difference in stream time base units from the pts of this
+     * packet to the point at which the output from the decoder has converged
+     * independent from the availability of previous frames. That is, the
+     * frames are virtually identical no matter if decoding started from
+     * the very first frame or from this keyframe.
+     * Is AV_NOPTS_VALUE if unknown.
+     * This field is not the display duration of the current frame.
+     * This field has no meaning if the packet does not have AV_PKT_FLAG_KEY
+     * set.
+     *
+     * The purpose of this field is to allow seeking in streams that have no
+     * keyframes in the conventional sense. It corresponds to the
+     * recovery point SEI in H.264 and match_time_delta in NUT. It is also
+     * essential for some types of subtitle streams to ensure that all
+     * subtitles are correctly displayed after seeking.
+     */
+    int64_t convergence_duration;
+
+    // Timestamp generation support:
+    /**
+     * Synchronization point for start of timestamp generation.
+     *
+     * Set to >0 for sync point, 0 for no sync point and <0 for undefined
+     * (default).
+     *
+     * For example, this corresponds to presence of H.264 buffering period
+     * SEI message.
+     */
+    int dts_sync_point;
+
+    /**
+     * Offset of the current timestamp against last timestamp sync point in
+     * units of AVCodecContext.time_base.
+     *
+     * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+     * contain a valid timestamp offset.
+     *
+     * Note that the timestamp of sync point has usually a nonzero
+     * dts_ref_dts_delta, which refers to the previous sync point. Offset of
+     * the next frame after timestamp sync point will be usually 1.
+     *
+     * For example, this corresponds to H.264 cpb_removal_delay.
+     */
+    int dts_ref_dts_delta;
+
+    /**
+     * Presentation delay of current frame in units of AVCodecContext.time_base.
+     *
+     * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+     * contain valid non-negative timestamp delta (presentation time of a frame
+     * must not lie in the past).
+     *
+     * This delay represents the difference between decoding and presentation
+     * time of the frame.
+     *
+     * For example, this corresponds to H.264 dpb_output_delay.
+     */
+    int pts_dts_delta;
+
+    /**
+     * Position of the packet in file.
+     *
+     * Analogous to cur_frame_pts/dts
+     */
+    int64_t cur_frame_pos[AV_PARSER_PTS_NB];
+
+    /**
+     * Byte position of currently parsed frame in stream.
+     */
+    int64_t pos;
+
+    /**
+     * Previous frame byte position.
+     */
+    int64_t last_pos;
+} AVCodecParserContext;
+
+typedef struct AVCodecParser {
+    int codec_ids[5]; /* several codec IDs are permitted */
+    int priv_data_size;
+    int (*parser_init)(AVCodecParserContext *s);
+    int (*parser_parse)(AVCodecParserContext *s,
+                        AVCodecContext *avctx,
+                        const uint8_t **poutbuf, int *poutbuf_size,
+                        const uint8_t *buf, int buf_size);
+    void (*parser_close)(AVCodecParserContext *s);
+    int (*split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size);
+    struct AVCodecParser *next;
+} AVCodecParser;
+
+AVCodecParser *av_parser_next(AVCodecParser *c);
+
+void av_register_codec_parser(AVCodecParser *parser);
+AVCodecParserContext *av_parser_init(int codec_id);
+
+/**
+ * Parse a packet.
+ *
+ * @param s             parser context.
+ * @param avctx         codec context.
+ * @param poutbuf       set to pointer to parsed buffer or NULL if not yet finished.
+ * @param poutbuf_size  set to size of parsed buffer or zero if not yet finished.
+ * @param buf           input buffer.
+ * @param buf_size      input length, to signal EOF, this should be 0 (so that the last frame can be output).
+ * @param pts           input presentation timestamp.
+ * @param dts           input decoding timestamp.
+ * @param pos           input byte position in stream.
+ * @return the number of bytes of the input bitstream used.
+ *
+ * Example:
+ * @code
+ *   while(in_len){
+ *       len = av_parser_parse2(myparser, AVCodecContext, &data, &size,
+ *                                        in_data, in_len,
+ *                                        pts, dts, pos);
+ *       in_data += len;
+ *       in_len  -= len;
+ *
+ *       if(size)
+ *          decode_frame(data, size);
+ *   }
+ * @endcode
+ */
+int av_parser_parse2(AVCodecParserContext *s,
+                     AVCodecContext *avctx,
+                     uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size,
+                     int64_t pts, int64_t dts,
+                     int64_t pos);
+
+int av_parser_change(AVCodecParserContext *s,
+                     AVCodecContext *avctx,
+                     uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size, int keyframe);
+void av_parser_close(AVCodecParserContext *s);
+
+
+typedef struct AVBitStreamFilterContext {
+    void *priv_data;
+    struct AVBitStreamFilter *filter;
+    AVCodecParserContext *parser;
+    struct AVBitStreamFilterContext *next;
+} AVBitStreamFilterContext;
+
+
+typedef struct AVBitStreamFilter {
+    const char *name;
+    int priv_data_size;
+    int (*filter)(AVBitStreamFilterContext *bsfc,
+                  AVCodecContext *avctx, const char *args,
+                  uint8_t **poutbuf, int *poutbuf_size,
+                  const uint8_t *buf, int buf_size, int keyframe);
+    void (*close)(AVBitStreamFilterContext *bsfc);
+    struct AVBitStreamFilter *next;
+} AVBitStreamFilter;
+
+void av_register_bitstream_filter(AVBitStreamFilter *bsf);
+AVBitStreamFilterContext *av_bitstream_filter_init(const char *name);
+int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc,
+                               AVCodecContext *avctx, const char *args,
+                               uint8_t **poutbuf, int *poutbuf_size,
+                               const uint8_t *buf, int buf_size, int keyframe);
+void av_bitstream_filter_close(AVBitStreamFilterContext *bsf);
+
+AVBitStreamFilter *av_bitstream_filter_next(AVBitStreamFilter *f);
+
+/* memory */
+
+/**
+ * Reallocate the given block if it is not large enough, otherwise do nothing.
+ *
+ * @see av_realloc
+ */
+void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Allocate a buffer, reusing the given one if large enough.
+ *
+ * Contrary to av_fast_realloc the current buffer contents might not be
+ * preserved and on error the old buffer is freed, thus no special
+ * handling to avoid memleaks is necessary.
+ *
+ * @param ptr pointer to pointer to already allocated buffer, overwritten with pointer to new buffer
+ * @param size size of the buffer *ptr points to
+ * @param min_size minimum size of *ptr buffer after returning, *ptr will be NULL and
+ *                 *size 0 if an error occurred.
+ */
+void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Copy image src to dst. Wraps av_picture_data_copy() above.
+ */
+void av_picture_copy(AVPicture *dst, const AVPicture *src,
+                     enum PixelFormat pix_fmt, int width, int height);
+
+/**
+ * Crop image top and left side.
+ */
+int av_picture_crop(AVPicture *dst, const AVPicture *src,
+                    enum PixelFormat pix_fmt, int top_band, int left_band);
+
+/**
+ * Pad image.
+ */
+int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum PixelFormat pix_fmt,
+            int padtop, int padbottom, int padleft, int padright, int *color);
+
+/**
+ * Encode extradata length to a buffer. Used by xiph codecs.
+ *
+ * @param s buffer to write to; must be at least (v/255+1) bytes long
+ * @param v size of extradata in bytes
+ * @return number of bytes written to the buffer.
+ */
+unsigned int av_xiphlacing(unsigned char *s, unsigned int v);
+
+/**
+ * Log a generic warning message about a missing feature. This function is
+ * intended to be used internally by Libav (libavcodec, libavformat, etc.)
+ * only, and would normally not be used by applications.
+ * @param[in] avc a pointer to an arbitrary struct of which the first field is
+ * a pointer to an AVClass struct
+ * @param[in] feature string containing the name of the missing feature
+ * @param[in] want_sample indicates if samples are wanted which exhibit this feature.
+ * If want_sample is non-zero, additional verbage will be added to the log
+ * message which tells the user how to report samples to the development
+ * mailing list.
+ */
+void av_log_missing_feature(void *avc, const char *feature, int want_sample);
+
+/**
+ * Log a generic warning message asking for a sample. This function is
+ * intended to be used internally by Libav (libavcodec, libavformat, etc.)
+ * only, and would normally not be used by applications.
+ * @param[in] avc a pointer to an arbitrary struct of which the first field is
+ * a pointer to an AVClass struct
+ * @param[in] msg string containing an optional message, or NULL if no message
+ */
+void av_log_ask_for_sample(void *avc, const char *msg, ...) av_printf_format(2, 3);
+
+/**
+ * Register the hardware accelerator hwaccel.
+ */
+void av_register_hwaccel(AVHWAccel *hwaccel);
+
+/**
+ * If hwaccel is NULL, returns the first registered hardware accelerator,
+ * if hwaccel is non-NULL, returns the next registered hardware accelerator
+ * after hwaccel, or NULL if hwaccel is the last one.
+ */
+AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel);
+
+
+/**
+ * Lock operation used by lockmgr
+ */
+enum AVLockOp {
+  AV_LOCK_CREATE,  ///< Create a mutex
+  AV_LOCK_OBTAIN,  ///< Lock the mutex
+  AV_LOCK_RELEASE, ///< Unlock the mutex
+  AV_LOCK_DESTROY, ///< Free mutex resources
+};
+
+/**
+ * Register a user provided lock manager supporting the operations
+ * specified by AVLockOp. mutex points to a (void *) where the
+ * lockmgr should store/get a pointer to a user allocated mutex. It's
+ * NULL upon AV_LOCK_CREATE and != NULL for all other ops.
+ *
+ * @param cb User defined callback. Note: Libav may invoke calls to this
+ *           callback during the call to av_lockmgr_register().
+ *           Thus, the application must be prepared to handle that.
+ *           If cb is set to NULL the lockmgr will be unregistered.
+ *           Also note that during unregistration the previously registered
+ *           lockmgr callback may also be invoked.
+ */
+int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op));
+
+/**
+ * Get the type of the given codec.
+ */
+enum AVMediaType avcodec_get_type(enum CodecID codec_id);
+
+/**
+ * Get the AVClass for AVCodecContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_class(void);
+
+/**
+ * @return a positive value if s is open (i.e. avcodec_open2() was called on it
+ * with no corresponding avcodec_close()), 0 otherwise.
+ */
+int avcodec_is_open(AVCodecContext *s);
+
+#endif /* AVCODEC_AVCODEC_H */
diff --git a/make/stub_includes/libav/libavcodec/avfft.h b/make/stub_includes/libav/libavcodec/avfft.h
new file mode 100644
index 0000000..91fe2f4
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/avfft.h
@@ -0,0 +1,99 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVFFT_H
+#define AVCODEC_AVFFT_H
+
+typedef float FFTSample;
+
+typedef struct FFTComplex {
+    FFTSample re, im;
+} FFTComplex;
+
+typedef struct FFTContext FFTContext;
+
+/**
+ * Set up a complex FFT.
+ * @param nbits           log2 of the length of the input array
+ * @param inverse         if 0 perform the forward transform, if 1 perform the inverse
+ */
+FFTContext *av_fft_init(int nbits, int inverse);
+
+/**
+ * Do the permutation needed BEFORE calling ff_fft_calc().
+ */
+void av_fft_permute(FFTContext *s, FFTComplex *z);
+
+/**
+ * Do a complex FFT with the parameters defined in av_fft_init(). The
+ * input data must be permuted before. No 1.0/sqrt(n) normalization is done.
+ */
+void av_fft_calc(FFTContext *s, FFTComplex *z);
+
+void av_fft_end(FFTContext *s);
+
+FFTContext *av_mdct_init(int nbits, int inverse, double scale);
+void av_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_end(FFTContext *s);
+
+/* Real Discrete Fourier Transform */
+
+enum RDFTransformType {
+    DFT_R2C,
+    IDFT_C2R,
+    IDFT_R2C,
+    DFT_C2R,
+};
+
+typedef struct RDFTContext RDFTContext;
+
+/**
+ * Set up a real FFT.
+ * @param nbits           log2 of the length of the input array
+ * @param trans           the type of transform
+ */
+RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans);
+void av_rdft_calc(RDFTContext *s, FFTSample *data);
+void av_rdft_end(RDFTContext *s);
+
+/* Discrete Cosine Transform */
+
+typedef struct DCTContext DCTContext;
+
+enum DCTTransformType {
+    DCT_II = 0,
+    DCT_III,
+    DCT_I,
+    DST_I,
+};
+
+/**
+ * Set up DCT.
+ * @param nbits           size of the input array:
+ *                        (1 << nbits)     for DCT-II, DCT-III and DST-I
+ *                        (1 << nbits) + 1 for DCT-I
+ *
+ * @note the first element of the input of DST-I is ignored
+ */
+DCTContext *av_dct_init(int nbits, enum DCTTransformType type);
+void av_dct_calc(DCTContext *s, FFTSample *data);
+void av_dct_end (DCTContext *s);
+
+#endif /* AVCODEC_AVFFT_H */
diff --git a/make/stub_includes/libav/libavcodec/dxva2.h b/make/stub_includes/libav/libavcodec/dxva2.h
new file mode 100644
index 0000000..374ae03
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/dxva2.h
@@ -0,0 +1,71 @@
+/*
+ * DXVA2 HW acceleration
+ *
+ * copyright (c) 2009 Laurent Aimar
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_DXVA_H
+#define AVCODEC_DXVA_H
+
+#include <stdint.h>
+
+#include <d3d9.h>
+#include <dxva2api.h>
+
+#define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 ///< Work around for DXVA2 and old UVD/UVD+ ATI video cards
+
+/**
+ * This structure is used to provides the necessary configurations and data
+ * to the DXVA2 Libav HWAccel implementation.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+struct dxva_context {
+    /**
+     * DXVA2 decoder object
+     */
+    IDirectXVideoDecoder *decoder;
+
+    /**
+     * DXVA2 configuration used to create the decoder
+     */
+    const DXVA2_ConfigPictureDecode *cfg;
+
+    /**
+     * The number of surface in the surface array
+     */
+    unsigned surface_count;
+
+    /**
+     * The array of Direct3D surfaces used to create the decoder
+     */
+    LPDIRECT3DSURFACE9 *surface;
+
+    /**
+     * A bit field configuring the workarounds needed for using the decoder
+     */
+    uint64_t workaround;
+
+    /**
+     * Private to the Libav AVHWAccel implementation
+     */
+    unsigned report_id;
+};
+
+#endif /* AVCODEC_DXVA_H */
diff --git a/make/stub_includes/libav/libavcodec/opt.h b/make/stub_includes/libav/libavcodec/opt.h
new file mode 100644
index 0000000..2380e74
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/opt.h
@@ -0,0 +1,34 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * This header is provided for compatibility only and will be removed
+ * on next major bump
+ */
+
+#ifndef AVCODEC_OPT_H
+#define AVCODEC_OPT_H
+
+#include "libavcodec/version.h"
+
+#if FF_API_OPT_H
+#include "libavutil/opt.h"
+#endif
+
+#endif /* AVCODEC_OPT_H */
diff --git a/make/stub_includes/libav/libavcodec/vaapi.h b/make/stub_includes/libav/libavcodec/vaapi.h
new file mode 100644
index 0000000..36fb386
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/vaapi.h
@@ -0,0 +1,167 @@
+/*
+ * Video Acceleration API (shared data between Libav and the video player)
+ * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1
+ *
+ * Copyright (C) 2008-2009 Splitted-Desktop Systems
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VAAPI_H
+#define AVCODEC_VAAPI_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup VAAPI_Decoding VA API Decoding
+ * @ingroup Decoder
+ * @{
+ */
+
+/**
+ * This structure is used to share data between the Libav library and
+ * the client video application.
+ * This shall be zero-allocated and available as
+ * AVCodecContext.hwaccel_context. All user members can be set once
+ * during initialization or through each AVCodecContext.get_buffer()
+ * function call. In any case, they must be valid prior to calling
+ * decoding functions.
+ */
+struct vaapi_context {
+    /**
+     * Window system dependent data
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    void *display;
+
+    /**
+     * Configuration ID
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    uint32_t config_id;
+
+    /**
+     * Context ID (video decode pipeline)
+     *
+     * - encoding: unused
+     * - decoding: Set by user
+     */
+    uint32_t context_id;
+
+    /**
+     * VAPictureParameterBuffer ID
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t pic_param_buf_id;
+
+    /**
+     * VAIQMatrixBuffer ID
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t iq_matrix_buf_id;
+
+    /**
+     * VABitPlaneBuffer ID (for VC-1 decoding)
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t bitplane_buf_id;
+
+    /**
+     * Slice parameter/data buffer IDs
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t *slice_buf_ids;
+
+    /**
+     * Number of effective slice buffer IDs to send to the HW
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int n_slice_buf_ids;
+
+    /**
+     * Size of pre-allocated slice_buf_ids
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_buf_ids_alloc;
+
+    /**
+     * Pointer to VASliceParameterBuffers
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    void *slice_params;
+
+    /**
+     * Size of a VASliceParameterBuffer element
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_param_size;
+
+    /**
+     * Size of pre-allocated slice_params
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_params_alloc;
+
+    /**
+     * Number of slices currently filled in
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    unsigned int slice_count;
+
+    /**
+     * Pointer to slice data buffer base
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    const uint8_t *slice_data;
+
+    /**
+     * Current size of slice data
+     *
+     * - encoding: unused
+     * - decoding: Set by libavcodec
+     */
+    uint32_t slice_data_size;
+};
+
+/* @} */
+
+#endif /* AVCODEC_VAAPI_H */
diff --git a/make/stub_includes/libav/libavcodec/vda.h b/make/stub_includes/libav/libavcodec/vda.h
new file mode 100644
index 0000000..2cb51c5
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/vda.h
@@ -0,0 +1,144 @@
+/*
+ * VDA HW acceleration
+ *
+ * copyright (c) 2011 Sebastien Zwickert
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VDA_H
+#define AVCODEC_VDA_H
+
+#include <pthread.h>
+#include <stdint.h>
+
+// emmintrin.h is unable to compile with -std=c99 -Werror=missing-prototypes
+// http://openradar.appspot.com/8026390
+#undef __GNUC_STDC_INLINE__
+
+#define Picture QuickdrawPicture
+#include <VideoDecodeAcceleration/VDADecoder.h>
+#undef Picture
+
+/**
+ *  This structure is used to store a decoded frame information and data.
+ */
+typedef struct vda_frame {
+    /**
+    * The PTS of the frame.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    int64_t             pts;
+
+    /**
+    * The CoreVideo buffer that contains the decoded data.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    CVPixelBufferRef    cv_buffer;
+
+    /**
+    * A pointer to the next frame.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    struct vda_frame    *next_frame;
+} vda_frame;
+
+/**
+ * This structure is used to provide the necessary configurations and data
+ * to the VDA Libav HWAccel implementation.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+struct vda_context {
+    /**
+    * VDA decoder object.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    VDADecoder          decoder;
+
+    /**
+    * VDA frames queue ordered by presentation timestamp.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    vda_frame           *queue;
+
+    /**
+    * Mutex for locking queue operations.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by libavcodec.
+    */
+    pthread_mutex_t     queue_mutex;
+
+    /**
+    * The frame width.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by user.
+    */
+    int                 width;
+
+    /**
+    * The frame height.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by user.
+    */
+    int                 height;
+
+    /**
+    * The frame format.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by user.
+    */
+    int                 format;
+
+    /**
+    * The pixel format for output image buffers.
+    *
+    * - encoding: unused
+    * - decoding: Set/Unset by user.
+    */
+    OSType              cv_pix_fmt_type;
+};
+
+/** Create the video decoder. */
+int ff_vda_create_decoder(struct vda_context *vda_ctx,
+                          uint8_t *extradata,
+                          int extradata_size);
+
+/** Destroy the video decoder. */
+int ff_vda_destroy_decoder(struct vda_context *vda_ctx);
+
+/** Return the top frame of the queue. */
+vda_frame *ff_vda_queue_pop(struct vda_context *vda_ctx);
+
+/** Release the given frame. */
+void ff_vda_release_vda_frame(vda_frame *frame);
+
+#endif /* AVCODEC_VDA_H */
diff --git a/make/stub_includes/libav/libavcodec/vdpau.h b/make/stub_includes/libav/libavcodec/vdpau.h
new file mode 100644
index 0000000..6f13860
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/vdpau.h
@@ -0,0 +1,88 @@
+/*
+ * The Video Decode and Presentation API for UNIX (VDPAU) is used for
+ * hardware-accelerated decoding of MPEG-1/2, H.264 and VC-1.
+ *
+ * Copyright (C) 2008 NVIDIA
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VDPAU_H
+#define AVCODEC_VDPAU_H
+
+/**
+ * @defgroup Decoder VDPAU Decoder and Renderer
+ *
+ * VDPAU hardware acceleration has two modules
+ * - VDPAU decoding
+ * - VDPAU presentation
+ *
+ * The VDPAU decoding module parses all headers using Libav
+ * parsing mechanisms and uses VDPAU for the actual decoding.
+ *
+ * As per the current implementation, the actual decoding
+ * and rendering (API calls) are done as part of the VDPAU
+ * presentation (vo_vdpau.c) module.
+ *
+ * @defgroup  VDPAU_Decoding VDPAU Decoding
+ * @ingroup Decoder
+ * @{
+ */
+
+#include <vdpau/vdpau.h>
+#include <vdpau/vdpau_x11.h>
+
+/** @brief The videoSurface is used for rendering. */
+#define FF_VDPAU_STATE_USED_FOR_RENDER 1
+
+/**
+ * @brief The videoSurface is needed for reference/prediction.
+ * The codec manipulates this.
+ */
+#define FF_VDPAU_STATE_USED_FOR_REFERENCE 2
+
+/**
+ * @brief This structure is used as a callback between the Libav
+ * decoder (vd_) and presentation (vo_) module.
+ * This is used for defining a video frame containing surface,
+ * picture parameter, bitstream information etc which are passed
+ * between the Libav decoder and its clients.
+ */
+struct vdpau_render_state {
+    VdpVideoSurface surface; ///< Used as rendered surface, never changed.
+
+    int state; ///< Holds FF_VDPAU_STATE_* values.
+
+    /** picture parameter information for all supported codecs */
+    union VdpPictureInfo {
+        VdpPictureInfoH264        h264;
+        VdpPictureInfoMPEG1Or2    mpeg;
+        VdpPictureInfoVC1          vc1;
+        VdpPictureInfoMPEG4Part2 mpeg4;
+    } info;
+
+    /** Describe size/location of the compressed video data.
+        Set to 0 when freeing bitstream_buffers. */
+    int bitstream_buffers_allocated;
+    int bitstream_buffers_used;
+    /** The user is responsible for freeing this buffer using av_freep(). */
+    VdpBitstreamBuffer *bitstream_buffers;
+};
+
+/* @}*/
+
+#endif /* AVCODEC_VDPAU_H */
diff --git a/make/stub_includes/libav/libavcodec/version.h b/make/stub_includes/libav/libavcodec/version.h
new file mode 100644
index 0000000..77e1682
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/version.h
@@ -0,0 +1,126 @@
+/*
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VERSION_H
+#define AVCODEC_VERSION_H
+
+#define LIBAVCODEC_VERSION_MAJOR 53
+#define LIBAVCODEC_VERSION_MINOR 35
+#define LIBAVCODEC_VERSION_MICRO  0
+
+#define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
+                                               LIBAVCODEC_VERSION_MINOR, \
+                                               LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_VERSION      AV_VERSION(LIBAVCODEC_VERSION_MAJOR,    \
+                                           LIBAVCODEC_VERSION_MINOR,    \
+                                           LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_BUILD        LIBAVCODEC_VERSION_INT
+
+#define LIBAVCODEC_IDENT        "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION)
+
+/**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_PALETTE_CONTROL
+#define FF_API_PALETTE_CONTROL  (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_SAMPLE_FMT
+#define FF_API_OLD_SAMPLE_FMT   (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_AUDIOCONVERT
+#define FF_API_OLD_AUDIOCONVERT (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_ANTIALIAS_ALGO
+#define FF_API_ANTIALIAS_ALGO   (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_REQUEST_CHANNELS
+#define FF_API_REQUEST_CHANNELS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OPT_H
+#define FF_API_OPT_H            (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_THREAD_INIT
+#define FF_API_THREAD_INIT      (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_FF_PICT_TYPES
+#define FF_API_OLD_FF_PICT_TYPES (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FLAC_GLOBAL_OPTS
+#define FF_API_FLAC_GLOBAL_OPTS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_GET_PIX_FMT_NAME
+#define FF_API_GET_PIX_FMT_NAME (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_ALLOC_CONTEXT
+#define FF_API_ALLOC_CONTEXT    (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_AVCODEC_OPEN
+#define FF_API_AVCODEC_OPEN     (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_DRC_SCALE
+#define FF_API_DRC_SCALE        (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_ER
+#define FF_API_ER               (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_AVCODEC_INIT
+#define FF_API_AVCODEC_INIT     (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_X264_GLOBAL_OPTS
+#define FF_API_X264_GLOBAL_OPTS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_MPEGVIDEO_GLOBAL_OPTS
+#define FF_API_MPEGVIDEO_GLOBAL_OPTS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_LAME_GLOBAL_OPTS
+#define FF_API_LAME_GLOBAL_OPTS  (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_SNOW_GLOBAL_OPTS
+#define FF_API_SNOW_GLOBAL_OPTS  (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_MJPEG_GLOBAL_OPTS
+#define FF_API_MJPEG_GLOBAL_OPTS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_GET_ALPHA_INFO
+#define FF_API_GET_ALPHA_INFO    (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PARSE_FRAME
+#define FF_API_PARSE_FRAME (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_INTERNAL_CONTEXT
+#define FF_API_INTERNAL_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_TIFFENC_COMPLEVEL
+#define FF_API_TIFFENC_COMPLEVEL (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_DATA_POINTERS
+#define FF_API_DATA_POINTERS (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_DECODE_AUDIO
+#define FF_API_OLD_DECODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_AVFRAME_AGE
+#define FF_API_AVFRAME_AGE (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_ENCODE_AUDIO
+#define FF_API_OLD_ENCODE_AUDIO (LIBAVCODEC_VERSION_MAJOR < 54)
+#endif
+
+#endif /* AVCODEC_VERSION_H */
diff --git a/make/stub_includes/libav/libavcodec/xvmc.h b/make/stub_includes/libav/libavcodec/xvmc.h
new file mode 100644
index 0000000..1239015
--- /dev/null
+++ b/make/stub_includes/libav/libavcodec/xvmc.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2003 Ivan Kalvachev
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_XVMC_H
+#define AVCODEC_XVMC_H
+
+#include <X11/extensions/XvMC.h>
+
+#include "avcodec.h"
+
+#define AV_XVMC_ID                    0x1DC711C0  /**< special value to ensure that regular pixel routines haven't corrupted the struct
+                                                       the number is 1337 speak for the letters IDCT MCo (motion compensation) */
+
+struct xvmc_pix_fmt {
+    /** The field contains the special constant value AV_XVMC_ID.
+        It is used as a test that the application correctly uses the API,
+        and that there is no corruption caused by pixel routines.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             xvmc_id;
+
+    /** Pointer to the block array allocated by XvMCCreateBlocks().
+        The array has to be freed by XvMCDestroyBlocks().
+        Each group of 64 values represents one data block of differential
+        pixel information (in MoCo mode) or coefficients for IDCT.
+        - application - set the pointer during initialization
+        - libavcodec  - fills coefficients/pixel data into the array
+    */
+    short*          data_blocks;
+
+    /** Pointer to the macroblock description array allocated by
+        XvMCCreateMacroBlocks() and freed by XvMCDestroyMacroBlocks().
+        - application - set the pointer during initialization
+        - libavcodec  - fills description data into the array
+    */
+    XvMCMacroBlock* mv_blocks;
+
+    /** Number of macroblock descriptions that can be stored in the mv_blocks
+        array.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             allocated_mv_blocks;
+
+    /** Number of blocks that can be stored at once in the data_blocks array.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             allocated_data_blocks;
+
+    /** Indicate that the hardware would interpret data_blocks as IDCT
+        coefficients and perform IDCT on them.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             idct;
+
+    /** In MoCo mode it indicates that intra macroblocks are assumed to be in
+        unsigned format; same as the XVMC_INTRA_UNSIGNED flag.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    int             unsigned_intra;
+
+    /** Pointer to the surface allocated by XvMCCreateSurface().
+        It has to be freed by XvMCDestroySurface() on application exit.
+        It identifies the frame and its state on the video hardware.
+        - application - set during initialization
+        - libavcodec  - unchanged
+    */
+    XvMCSurface*    p_surface;
+
+/** Set by the decoder before calling ff_draw_horiz_band(),
+    needed by the XvMCRenderSurface function. */
+//@{
+    /** Pointer to the surface used as past reference
+        - application - unchanged
+        - libavcodec  - set
+    */
+    XvMCSurface*    p_past_surface;
+
+    /** Pointer to the surface used as future reference
+        - application - unchanged
+        - libavcodec  - set
+    */
+    XvMCSurface*    p_future_surface;
+
+    /** top/bottom field or frame
+        - application - unchanged
+        - libavcodec  - set
+    */
+    unsigned int    picture_structure;
+
+    /** XVMC_SECOND_FIELD - 1st or 2nd field in the sequence
+        - application - unchanged
+        - libavcodec  - set
+    */
+    unsigned int    flags;
+//}@
+
+    /** Number of macroblock descriptions in the mv_blocks array
+        that have already been passed to the hardware.
+        - application - zeroes it on get_buffer().
+                        A successful ff_draw_horiz_band() may increment it
+                        with filled_mb_block_num or zero both.
+        - libavcodec  - unchanged
+    */
+    int             start_mv_blocks_num;
+
+    /** Number of new macroblock descriptions in the mv_blocks array (after
+        start_mv_blocks_num) that are filled by libavcodec and have to be
+        passed to the hardware.
+        - application - zeroes it on get_buffer() or after successful
+                        ff_draw_horiz_band().
+        - libavcodec  - increment with one of each stored MB
+    */
+    int             filled_mv_blocks_num;
+
+    /** Number of the the next free data block; one data block consists of
+        64 short values in the data_blocks array.
+        All blocks before this one have already been claimed by placing their
+        position into the corresponding block description structure field,
+        that are part of the mv_blocks array.
+        - application - zeroes it on get_buffer().
+                        A successful ff_draw_horiz_band() may zero it together
+                        with start_mb_blocks_num.
+        - libavcodec  - each decoded macroblock increases it by the number
+                        of coded blocks it contains.
+    */
+    int             next_free_data_block_num;
+};
+
+#endif /* AVCODEC_XVMC_H */
diff --git a/make/stub_includes/libav/libavformat/avformat.h b/make/stub_includes/libav/libavformat/avformat.h
new file mode 100644
index 0000000..22a89d3
--- /dev/null
+++ b/make/stub_includes/libav/libavformat/avformat.h
@@ -0,0 +1,2026 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_AVFORMAT_H
+#define AVFORMAT_AVFORMAT_H
+
+/**
+ * @file
+ * @ingroup libavf
+ * Main libavformat public API header
+ */
+
+/**
+ * @defgroup libavf I/O and Muxing/Demuxing Library
+ * @{
+ *
+ * Libavformat (lavf) is a library for dealing with various media container
+ * formats. Its main two purposes are demuxing - i.e. splitting a media file
+ * into component streams, and the reverse process of muxing - writing supplied
+ * data in a specified container format. It also has an @ref lavf_io
+ * "I/O module" which supports a number of protocols for accessing the data (e.g.
+ * file, tcp, http and others). Before using lavf, you need to call
+ * av_register_all() to register all compiled muxers, demuxers and protocols.
+ * Unless you are absolutely sure you won't use libavformat's network
+ * capabilities, you should also call avformat_network_init().
+ *
+ * A supported input format is described by an AVInputFormat struct, conversely
+ * an output format is described by AVOutputFormat. You can iterate over all
+ * registered input/output formats using the av_iformat_next() /
+ * av_oformat_next() functions. The protocols layer is not part of the public
+ * API, so you can only get the names of supported protocols with the
+ * avio_enum_protocols() function.
+ *
+ * Main lavf structure used for both muxing and demuxing is AVFormatContext,
+ * which exports all information about the file being read or written. As with
+ * most Libav structures, its size is not part of public ABI, so it cannot be
+ * allocated on stack or directly with av_malloc(). To create an
+ * AVFormatContext, use avformat_alloc_context() (some functions, like
+ * avformat_open_input() might do that for you).
+ *
+ * Most importantly an AVFormatContext contains:
+ * @li the @ref AVFormatContext.iformat "input" or @ref AVFormatContext.oformat
+ * "output" format. It is either autodetected or set by user for input;
+ * always set by user for output.
+ * @li an @ref AVFormatContext.streams "array" of AVStreams, which describe all
+ * elementary streams stored in the file. AVStreams are typically referred to
+ * using their index in this array.
+ * @li an @ref AVFormatContext.pb "I/O context". It is either opened by lavf or
+ * set by user for input, always set by user for output (unless you are dealing
+ * with an AVFMT_NOFILE format).
+ *
+ * @defgroup lavf_decoding Demuxing
+ * @{
+ * Demuxers read a media file and split it into chunks of data (@em packets). A
+ * @ref AVPacket "packet" contains one or more frames which belong a single
+ * elementary stream. In lavf API this process is represented by the
+ * avformat_open_input() function for opening a file, av_read_frame() for
+ * reading a single packet and finally avformat_close_input(), which does the
+ * cleanup.
+ *
+ * @section lavf_decoding_open Opening a media file
+ * The minimum information required to open a file is its URL or filename, which
+ * is passed to avformat_open_input(), as in the following code:
+ * @code
+ * const char    *url = "in.mp3";
+ * AVFormatContext *s = NULL;
+ * int ret = avformat_open_input(&s, url, NULL, NULL);
+ * if (ret < 0)
+ *     abort();
+ * @endcode
+ * The above code attempts to allocate an AVFormatContext, open the
+ * specified file (autodetecting the format) and read the header, exporting the
+ * information stored there into s. Some formats do not have a header or do not
+ * store enough information there, so it is recommended that you call the
+ * avformat_find_stream_info() function which tries to read and decode a few
+ * frames to find missing information.
+ *
+ * In some cases you might want to preallocate an AVFormatContext yourself with
+ * avformat_alloc_context() and do some tweaking on it before passing it to
+ * avformat_open_input(). One such case is when you want to use custom functions
+ * for reading input data instead of lavf internal I/O layer.
+ * To do that, create your own AVIOContext with avio_alloc_context(), passing
+ * your reading callbacks to it. Then set the @em pb field of your
+ * AVFormatContext to newly created AVIOContext.
+ *
+ * After you have finished reading the file, you must close it with
+ * avformat_close_input(). It will free everything associated with the file.
+ *
+ * @section lavf_decoding_read Reading from an opened file
+ *
+ * @section lavf_decoding_seek Seeking
+ * @}
+ *
+ * @defgroup lavf_encoding Muxing
+ * @{
+ * @}
+ *
+ * @defgroup lavf_io I/O Read/Write
+ * @{
+ * @}
+ *
+ * @defgroup lavf_codec Demuxers
+ * @{
+ * @defgroup lavf_codec_native Native Demuxers
+ * @{
+ * @}
+ * @defgroup lavf_codec_wrappers External library wrappers
+ * @{
+ * @}
+ * @}
+ * @defgroup lavf_protos I/O Protocols
+ * @{
+ * @}
+ * @defgroup lavf_internal Internal
+ * @{
+ * @}
+ * @}
+ *
+ */
+
+#include <time.h>
+#include <stdio.h>  /* FILE */
+#include "libavcodec/avcodec.h"
+#include "libavutil/dict.h"
+#include "libavutil/log.h"
+
+#include "avio.h"
+#include "libavformat/version.h"
+
+struct AVFormatContext;
+
+
+/**
+ * @defgroup metadata_api Public Metadata API
+ * @{
+ * @ingroup libavf
+ * The metadata API allows libavformat to export metadata tags to a client
+ * application when demuxing. Conversely it allows a client application to
+ * set metadata when muxing.
+ *
+ * Metadata is exported or set as pairs of key/value strings in the 'metadata'
+ * fields of the AVFormatContext, AVStream, AVChapter and AVProgram structs
+ * using the @ref lavu_dict "AVDictionary" API. Like all strings in Libav,
+ * metadata is assumed to be UTF-8 encoded Unicode. Note that metadata
+ * exported by demuxers isn't checked to be valid UTF-8 in most cases.
+ *
+ * Important concepts to keep in mind:
+ * -  Keys are unique; there can never be 2 tags with the same key. This is
+ *    also meant semantically, i.e., a demuxer should not knowingly produce
+ *    several keys that are literally different but semantically identical.
+ *    E.g., key=Author5, key=Author6. In this example, all authors must be
+ *    placed in the same tag.
+ * -  Metadata is flat, not hierarchical; there are no subtags. If you
+ *    want to store, e.g., the email address of the child of producer Alice
+ *    and actor Bob, that could have key=alice_and_bobs_childs_email_address.
+ * -  Several modifiers can be applied to the tag name. This is done by
+ *    appending a dash character ('-') and the modifier name in the order
+ *    they appear in the list below -- e.g. foo-eng-sort, not foo-sort-eng.
+ *    -  language -- a tag whose value is localized for a particular language
+ *       is appended with the ISO 639-2/B 3-letter language code.
+ *       For example: Author-ger=Michael, Author-eng=Mike
+ *       The original/default language is in the unqualified "Author" tag.
+ *       A demuxer should set a default if it sets any translated tag.
+ *    -  sorting  -- a modified version of a tag that should be used for
+ *       sorting will have '-sort' appended. E.g. artist="The Beatles",
+ *       artist-sort="Beatles, The".
+ *
+ * -  Demuxers attempt to export metadata in a generic format, however tags
+ *    with no generic equivalents are left as they are stored in the container.
+ *    Follows a list of generic tag names:
+ *
+ @verbatim
+ album        -- name of the set this work belongs to
+ album_artist -- main creator of the set/album, if different from artist.
+                 e.g. "Various Artists" for compilation albums.
+ artist       -- main creator of the work
+ comment      -- any additional description of the file.
+ composer     -- who composed the work, if different from artist.
+ copyright    -- name of copyright holder.
+ creation_time-- date when the file was created, preferably in ISO 8601.
+ date         -- date when the work was created, preferably in ISO 8601.
+ disc         -- number of a subset, e.g. disc in a multi-disc collection.
+ encoder      -- name/settings of the software/hardware that produced the file.
+ encoded_by   -- person/group who created the file.
+ filename     -- original name of the file.
+ genre        -- <self-evident>.
+ language     -- main language in which the work is performed, preferably
+                 in ISO 639-2 format. Multiple languages can be specified by
+                 separating them with commas.
+ performer    -- artist who performed the work, if different from artist.
+                 E.g for "Also sprach Zarathustra", artist would be "Richard
+                 Strauss" and performer "London Philharmonic Orchestra".
+ publisher    -- name of the label/publisher.
+ service_name     -- name of the service in broadcasting (channel name).
+ service_provider -- name of the service provider in broadcasting.
+ title        -- name of the work.
+ track        -- number of this work in the set, can be in form current/total.
+ variant_bitrate -- the total bitrate of the bitrate variant that the current stream is part of
+ @endverbatim
+ *
+ * Look in the examples section for an application example how to use the Metadata API.
+ *
+ * @}
+ */
+
+#if FF_API_OLD_METADATA2
+/**
+ * @defgroup old_metadata Old metadata API
+ * The following functions are deprecated, use
+ * their equivalents from libavutil/dict.h instead.
+ * @{
+ */
+
+#define AV_METADATA_MATCH_CASE      AV_DICT_MATCH_CASE
+#define AV_METADATA_IGNORE_SUFFIX   AV_DICT_IGNORE_SUFFIX
+#define AV_METADATA_DONT_STRDUP_KEY AV_DICT_DONT_STRDUP_KEY
+#define AV_METADATA_DONT_STRDUP_VAL AV_DICT_DONT_STRDUP_VAL
+#define AV_METADATA_DONT_OVERWRITE  AV_DICT_DONT_OVERWRITE
+
+typedef attribute_deprecated AVDictionary AVMetadata;
+typedef attribute_deprecated AVDictionaryEntry  AVMetadataTag;
+
+typedef struct AVMetadataConv AVMetadataConv;
+
+/**
+ * Get a metadata element with matching key.
+ *
+ * @param prev Set to the previous matching element to find the next.
+ *             If set to NULL the first matching element is returned.
+ * @param flags Allows case as well as suffix-insensitive comparisons.
+ * @return Found tag or NULL, changing key or value leads to undefined behavior.
+ */
+attribute_deprecated AVDictionaryEntry *
+av_metadata_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags);
+
+/**
+ * Set the given tag in *pm, overwriting an existing tag.
+ *
+ * @param pm pointer to a pointer to a metadata struct. If *pm is NULL
+ * a metadata struct is allocated and put in *pm.
+ * @param key tag key to add to *pm (will be av_strduped depending on flags)
+ * @param value tag value to add to *pm (will be av_strduped depending on flags).
+ *        Passing a NULL value will cause an existing tag to be deleted.
+ * @return >= 0 on success otherwise an error code <0
+ */
+attribute_deprecated int av_metadata_set2(AVDictionary **pm, const char *key, const char *value, int flags);
+
+/**
+ * This function is provided for compatibility reason and currently does nothing.
+ */
+attribute_deprecated void av_metadata_conv(struct AVFormatContext *ctx, const AVMetadataConv *d_conv,
+                                                                        const AVMetadataConv *s_conv);
+
+/**
+ * Copy metadata from one AVDictionary struct into another.
+ * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL,
+ *            this function will allocate a struct for you and put it in *dst
+ * @param src pointer to source AVDictionary struct
+ * @param flags flags to use when setting metadata in *dst
+ * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag
+ */
+attribute_deprecated void av_metadata_copy(AVDictionary **dst, AVDictionary *src, int flags);
+
+/**
+ * Free all the memory allocated for an AVDictionary struct.
+ */
+attribute_deprecated void av_metadata_free(AVDictionary **m);
+/**
+ * @}
+ */
+#endif
+
+
+/* packet functions */
+
+
+/**
+ * Allocate and read the payload of a packet and initialize its
+ * fields with default values.
+ *
+ * @param pkt packet
+ * @param size desired payload size
+ * @return >0 (read size) if OK, AVERROR_xxx otherwise
+ */
+int av_get_packet(AVIOContext *s, AVPacket *pkt, int size);
+
+
+/**
+ * Read data and append it to the current content of the AVPacket.
+ * If pkt->size is 0 this is identical to av_get_packet.
+ * Note that this uses av_grow_packet and thus involves a realloc
+ * which is inefficient. Thus this function should only be used
+ * when there is no reasonable way to know (an upper bound of)
+ * the final size.
+ *
+ * @param pkt packet
+ * @param size amount of data to read
+ * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data
+ *         will not be lost even if an error occurs.
+ */
+int av_append_packet(AVIOContext *s, AVPacket *pkt, int size);
+
+/*************************************************/
+/* fractional numbers for exact pts handling */
+
+/**
+ * The exact value of the fractional number is: 'val + num / den'.
+ * num is assumed to be 0 <= num < den.
+ */
+typedef struct AVFrac {
+    int64_t val, num, den;
+} AVFrac;
+
+/*************************************************/
+/* input/output formats */
+
+struct AVCodecTag;
+
+/**
+ * This structure contains the data a format has to probe a file.
+ */
+typedef struct AVProbeData {
+    const char *filename;
+    unsigned char *buf; /**< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. */
+    int buf_size;       /**< Size of buf except extra allocated bytes */
+} AVProbeData;
+
+#define AVPROBE_SCORE_MAX 100               ///< maximum score, half of that is used for file-extension-based detection
+#define AVPROBE_PADDING_SIZE 32             ///< extra allocated bytes at the end of the probe buffer
+
+typedef struct AVFormatParameters {
+#if FF_API_FORMAT_PARAMETERS
+    attribute_deprecated AVRational time_base;
+    attribute_deprecated int sample_rate;
+    attribute_deprecated int channels;
+    attribute_deprecated int width;
+    attribute_deprecated int height;
+    attribute_deprecated enum PixelFormat pix_fmt;
+    attribute_deprecated int channel; /**< Used to select DV channel. */
+    attribute_deprecated const char *standard; /**< deprecated, use demuxer-specific options instead. */
+    attribute_deprecated unsigned int mpeg2ts_raw:1;  /**< deprecated, use mpegtsraw demuxer */
+    /**< deprecated, use mpegtsraw demuxer-specific options instead */
+    attribute_deprecated unsigned int mpeg2ts_compute_pcr:1;
+    attribute_deprecated unsigned int initial_pause:1;       /**< Do not begin to play the stream
+                                                                  immediately (RTSP only). */
+    attribute_deprecated unsigned int prealloced_context:1;
+#endif
+} AVFormatParameters;
+
+/// Demuxer will use avio_open, no opened file should be provided by the caller.
+#define AVFMT_NOFILE        0x0001
+#define AVFMT_NEEDNUMBER    0x0002 /**< Needs '%d' in filename. */
+#define AVFMT_SHOW_IDS      0x0008 /**< Show format stream IDs numbers. */
+#define AVFMT_RAWPICTURE    0x0020 /**< Format wants AVPicture structure for
+                                      raw picture data. */
+#define AVFMT_GLOBALHEADER  0x0040 /**< Format wants global header. */
+#define AVFMT_NOTIMESTAMPS  0x0080 /**< Format does not need / have any timestamps. */
+#define AVFMT_GENERIC_INDEX 0x0100 /**< Use generic index building code. */
+#define AVFMT_TS_DISCONT    0x0200 /**< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps */
+#define AVFMT_VARIABLE_FPS  0x0400 /**< Format allows variable fps. */
+#define AVFMT_NODIMENSIONS  0x0800 /**< Format does not need width/height */
+#define AVFMT_NOSTREAMS     0x1000 /**< Format does not require any streams */
+#define AVFMT_NOBINSEARCH   0x2000 /**< Format does not allow to fallback to binary search via read_timestamp */
+#define AVFMT_NOGENSEARCH   0x4000 /**< Format does not allow to fallback to generic search */
+#define AVFMT_NO_BYTE_SEEK  0x8000 /**< Format does not allow seeking by bytes */
+
+/**
+ * @addtogroup lavf_encoding
+ * @{
+ */
+typedef struct AVOutputFormat {
+    const char *name;
+    /**
+     * Descriptive name for the format, meant to be more human-readable
+     * than name. You should use the NULL_IF_CONFIG_SMALL() macro
+     * to define it.
+     */
+    const char *long_name;
+    const char *mime_type;
+    const char *extensions; /**< comma-separated filename extensions */
+    /**
+     * size of private data so that it can be allocated in the wrapper
+     */
+    int priv_data_size;
+    /* output support */
+    enum CodecID audio_codec; /**< default audio codec */
+    enum CodecID video_codec; /**< default video codec */
+    int (*write_header)(struct AVFormatContext *);
+    int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
+    int (*write_trailer)(struct AVFormatContext *);
+    /**
+     * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE,
+     * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS,
+     * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS
+     */
+    int flags;
+    /**
+     * Currently only used to set pixel format if not YUV420P.
+     */
+    int (*set_parameters)(struct AVFormatContext *, AVFormatParameters *);
+    int (*interleave_packet)(struct AVFormatContext *, AVPacket *out,
+                             AVPacket *in, int flush);
+
+    /**
+     * List of supported codec_id-codec_tag pairs, ordered by "better
+     * choice first". The arrays are all terminated by CODEC_ID_NONE.
+     */
+    const struct AVCodecTag * const *codec_tag;
+
+    enum CodecID subtitle_codec; /**< default subtitle codec */
+
+#if FF_API_OLD_METADATA2
+    const AVMetadataConv *metadata_conv;
+#endif
+
+    const AVClass *priv_class; ///< AVClass for the private context
+
+    /**
+     * Test if the given codec can be stored in this container.
+     *
+     * @return 1 if the codec is supported, 0 if it is not.
+     *         A negative number if unknown.
+     */
+    int (*query_codec)(enum CodecID id, int std_compliance);
+
+    /* private fields */
+    struct AVOutputFormat *next;
+} AVOutputFormat;
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavf_decoding
+ * @{
+ */
+typedef struct AVInputFormat {
+    /**
+     * A comma separated list of short names for the format. New names
+     * may be appended with a minor bump.
+     */
+    const char *name;
+
+    /**
+     * Descriptive name for the format, meant to be more human-readable
+     * than name. You should use the NULL_IF_CONFIG_SMALL() macro
+     * to define it.
+     */
+    const char *long_name;
+
+    /**
+     * Size of private data so that it can be allocated in the wrapper.
+     */
+    int priv_data_size;
+
+    /**
+     * Tell if a given file has a chance of being parsed as this format.
+     * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes
+     * big so you do not have to check for that unless you need more.
+     */
+    int (*read_probe)(AVProbeData *);
+
+    /**
+     * Read the format header and initialize the AVFormatContext
+     * structure. Return 0 if OK. 'ap' if non-NULL contains
+     * additional parameters. Only used in raw format right
+     * now. 'av_new_stream' should be called to create new streams.
+     */
+    int (*read_header)(struct AVFormatContext *,
+                       AVFormatParameters *ap);
+
+    /**
+     * Read one packet and put it in 'pkt'. pts and flags are also
+     * set. 'av_new_stream' can be called only if the flag
+     * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a
+     * background thread).
+     * @return 0 on success, < 0 on error.
+     *         When returning an error, pkt must not have been allocated
+     *         or must be freed before returning
+     */
+    int (*read_packet)(struct AVFormatContext *, AVPacket *pkt);
+
+    /**
+     * Close the stream. The AVFormatContext and AVStreams are not
+     * freed by this function
+     */
+    int (*read_close)(struct AVFormatContext *);
+
+    /**
+     * Seek to a given timestamp relative to the frames in
+     * stream component stream_index.
+     * @param stream_index Must not be -1.
+     * @param flags Selects which direction should be preferred if no exact
+     *              match is available.
+     * @return >= 0 on success (but not necessarily the new offset)
+     */
+    int (*read_seek)(struct AVFormatContext *,
+                     int stream_index, int64_t timestamp, int flags);
+
+    /**
+     * Get the next timestamp in stream[stream_index].time_base units.
+     * @return the timestamp or AV_NOPTS_VALUE if an error occurred
+     */
+    int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index,
+                              int64_t *pos, int64_t pos_limit);
+
+    /**
+     * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS,
+     * AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH,
+     * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK.
+     */
+    int flags;
+
+    /**
+     * If extensions are defined, then no probe is done. You should
+     * usually not use extension format guessing because it is not
+     * reliable enough
+     */
+    const char *extensions;
+
+    /**
+     * General purpose read-only value that the format can use.
+     */
+    int value;
+
+    /**
+     * Start/resume playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
+    int (*read_play)(struct AVFormatContext *);
+
+    /**
+     * Pause playing - only meaningful if using a network-based format
+     * (RTSP).
+     */
+    int (*read_pause)(struct AVFormatContext *);
+
+    const struct AVCodecTag * const *codec_tag;
+
+    /**
+     * Seek to timestamp ts.
+     * Seeking will be done so that the point from which all active streams
+     * can be presented successfully will be closest to ts and within min/max_ts.
+     * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
+     */
+    int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
+
+#if FF_API_OLD_METADATA2
+    const AVMetadataConv *metadata_conv;
+#endif
+
+    const AVClass *priv_class; ///< AVClass for the private context
+
+    /* private fields */
+    struct AVInputFormat *next;
+} AVInputFormat;
+/**
+ * @}
+ */
+
+enum AVStreamParseType {
+    AVSTREAM_PARSE_NONE,
+    AVSTREAM_PARSE_FULL,       /**< full parsing and repack */
+    AVSTREAM_PARSE_HEADERS,    /**< Only parse headers, do not repack. */
+    AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on a packet boundary */
+    AVSTREAM_PARSE_FULL_ONCE,  /**< full parsing and repack of the first frame only, only implemented for H.264 currently */
+};
+
+typedef struct AVIndexEntry {
+    int64_t pos;
+    int64_t timestamp;
+#define AVINDEX_KEYFRAME 0x0001
+    int flags:2;
+    int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs. 32 bytes due to possible 8-byte alignment).
+    int min_distance;         /**< Minimum distance between this and the previous keyframe, used to avoid unneeded searching. */
+} AVIndexEntry;
+
+#define AV_DISPOSITION_DEFAULT   0x0001
+#define AV_DISPOSITION_DUB       0x0002
+#define AV_DISPOSITION_ORIGINAL  0x0004
+#define AV_DISPOSITION_COMMENT   0x0008
+#define AV_DISPOSITION_LYRICS    0x0010
+#define AV_DISPOSITION_KARAOKE   0x0020
+
+/**
+ * Track should be used during playback by default.
+ * Useful for subtitle track that should be displayed
+ * even when user did not explicitly ask for subtitles.
+ */
+#define AV_DISPOSITION_FORCED    0x0040
+#define AV_DISPOSITION_HEARING_IMPAIRED  0x0080  /**< stream for hearing impaired audiences */
+#define AV_DISPOSITION_VISUAL_IMPAIRED   0x0100  /**< stream for visual impaired audiences */
+#define AV_DISPOSITION_CLEAN_EFFECTS     0x0200  /**< stream without voice */
+
+/**
+ * Stream structure.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVStream) must not be used outside libav*.
+ */
+typedef struct AVStream {
+    int index;    /**< stream index in AVFormatContext */
+    int id;       /**< format-specific stream ID */
+    AVCodecContext *codec; /**< codec context */
+    /**
+     * Real base framerate of the stream.
+     * This is the lowest framerate with which all timestamps can be
+     * represented accurately (it is the least common multiple of all
+     * framerates in the stream). Note, this value is just a guess!
+     * For example, if the time base is 1/90000 and all frames have either
+     * approximately 3600 or 1800 timer ticks, then r_frame_rate will be 50/1.
+     */
+    AVRational r_frame_rate;
+    void *priv_data;
+
+#if FF_API_REORDER_PRIVATE
+    /* internal data used in av_find_stream_info() */
+    int64_t first_dts;
+#endif
+
+    /**
+     * encoding: pts generation when outputting stream
+     */
+    struct AVFrac pts;
+
+    /**
+     * This is the fundamental unit of time (in seconds) in terms
+     * of which frame timestamps are represented. For fixed-fps content,
+     * time base should be 1/framerate and timestamp increments should be 1.
+     * decoding: set by libavformat
+     * encoding: set by libavformat in av_write_header
+     */
+    AVRational time_base;
+#if FF_API_REORDER_PRIVATE
+    int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */
+#endif
+#if FF_API_STREAM_COPY
+    /* ffmpeg.c private use */
+    attribute_deprecated int stream_copy; /**< If set, just copy stream. */
+#endif
+    enum AVDiscard discard; ///< Selects which packets can be discarded at will and do not need to be demuxed.
+
+#if FF_API_AVSTREAM_QUALITY
+    //FIXME move stuff to a flags field?
+    /**
+     * Quality, as it has been removed from AVCodecContext and put in AVVideoFrame.
+     * MN: dunno if that is the right place for it
+     */
+    attribute_deprecated float quality;
+#endif
+
+    /**
+     * Decoding: pts of the first frame of the stream, in stream time base.
+     * Only set this if you are absolutely 100% sure that the value you set
+     * it to really is the pts of the first frame.
+     * This may be undefined (AV_NOPTS_VALUE).
+     */
+    int64_t start_time;
+
+    /**
+     * Decoding: duration of the stream, in stream time base.
+     * If a source file does not specify a duration, but does specify
+     * a bitrate, this value will be estimated from bitrate and file size.
+     */
+    int64_t duration;
+
+#if FF_API_REORDER_PRIVATE
+    /* av_read_frame() support */
+    enum AVStreamParseType need_parsing;
+    struct AVCodecParserContext *parser;
+
+    int64_t cur_dts;
+    int last_IP_duration;
+    int64_t last_IP_pts;
+    /* av_seek_frame() support */
+    AVIndexEntry *index_entries; /**< Only used if the format does not
+                                    support seeking natively. */
+    int nb_index_entries;
+    unsigned int index_entries_allocated_size;
+#endif
+
+    int64_t nb_frames;                 ///< number of frames in this stream if known or 0
+
+    int disposition; /**< AV_DISPOSITION_* bit field */
+
+#if FF_API_REORDER_PRIVATE
+    AVProbeData probe_data;
+#define MAX_REORDER_DELAY 16
+    int64_t pts_buffer[MAX_REORDER_DELAY+1];
+#endif
+
+    /**
+     * sample aspect ratio (0 if unknown)
+     * - encoding: Set by user.
+     * - decoding: Set by libavformat.
+     */
+    AVRational sample_aspect_ratio;
+
+    AVDictionary *metadata;
+
+#if FF_API_REORDER_PRIVATE
+    /* Intended mostly for av_read_frame() support. Not supposed to be used by */
+    /* external applications; try to use something else if at all possible.    */
+    const uint8_t *cur_ptr;
+    int cur_len;
+    AVPacket cur_pkt;
+
+    // Timestamp generation support:
+    /**
+     * Timestamp corresponding to the last dts sync point.
+     *
+     * Initialized when AVCodecParserContext.dts_sync_point >= 0 and
+     * a DTS is received from the underlying container. Otherwise set to
+     * AV_NOPTS_VALUE by default.
+     */
+    int64_t reference_dts;
+
+    /**
+     * Number of packets to buffer for codec probing
+     * NOT PART OF PUBLIC API
+     */
+#define MAX_PROBE_PACKETS 2500
+    int probe_packets;
+
+    /**
+     * last packet in packet_buffer for this stream when muxing.
+     * Used internally, NOT PART OF PUBLIC API, do not read or
+     * write from outside of libav*
+     */
+    struct AVPacketList *last_in_packet_buffer;
+#endif
+
+    /**
+     * Average framerate
+     */
+    AVRational avg_frame_rate;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+
+    /**
+     * Number of frames that have been demuxed during av_find_stream_info()
+     */
+    int codec_info_nb_frames;
+
+    /**
+     * Stream information used internally by av_find_stream_info()
+     */
+#define MAX_STD_TIMEBASES (60*12+5)
+    struct {
+        int64_t last_dts;
+        int64_t duration_gcd;
+        int duration_count;
+        double duration_error[MAX_STD_TIMEBASES];
+        int64_t codec_info_duration;
+        int nb_decoded_frames;
+    } *info;
+#if !FF_API_REORDER_PRIVATE
+    const uint8_t *cur_ptr;
+    int cur_len;
+    AVPacket cur_pkt;
+
+    // Timestamp generation support:
+    /**
+     * Timestamp corresponding to the last dts sync point.
+     *
+     * Initialized when AVCodecParserContext.dts_sync_point >= 0 and
+     * a DTS is received from the underlying container. Otherwise set to
+     * AV_NOPTS_VALUE by default.
+     */
+    int64_t reference_dts;
+    int64_t first_dts;
+    int64_t cur_dts;
+    int last_IP_duration;
+    int64_t last_IP_pts;
+
+    /**
+     * Number of packets to buffer for codec probing
+     */
+#define MAX_PROBE_PACKETS 2500
+    int probe_packets;
+
+    /**
+     * last packet in packet_buffer for this stream when muxing.
+     */
+    struct AVPacketList *last_in_packet_buffer;
+    AVProbeData probe_data;
+#define MAX_REORDER_DELAY 16
+    int64_t pts_buffer[MAX_REORDER_DELAY+1];
+    /* av_read_frame() support */
+    enum AVStreamParseType need_parsing;
+    struct AVCodecParserContext *parser;
+
+    AVIndexEntry *index_entries; /**< Only used if the format does not
+                                    support seeking natively. */
+    int nb_index_entries;
+    unsigned int index_entries_allocated_size;
+
+    int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */
+#endif
+} AVStream;
+
+#define AV_PROGRAM_RUNNING 1
+
+/**
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVProgram) must not be used outside libav*.
+ */
+typedef struct AVProgram {
+    int            id;
+    int            flags;
+    enum AVDiscard discard;        ///< selects which program to discard and which to feed to the caller
+    unsigned int   *stream_index;
+    unsigned int   nb_stream_indexes;
+    AVDictionary *metadata;
+} AVProgram;
+
+#define AVFMTCTX_NOHEADER      0x0001 /**< signal that no header is present
+                                         (streams are added dynamically) */
+
+typedef struct AVChapter {
+    int id;                 ///< unique ID to identify the chapter
+    AVRational time_base;   ///< time base in which the start/end timestamps are specified
+    int64_t start, end;     ///< chapter start/end time in time_base units
+    AVDictionary *metadata;
+} AVChapter;
+
+/**
+ * Format I/O context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVFormatContext) must not be used outside libav*, use
+ * avformat_alloc_context() to create an AVFormatContext.
+ */
+typedef struct AVFormatContext {
+    /**
+     * A class for logging and AVOptions. Set by avformat_alloc_context().
+     * Exports (de)muxer private options if they exist.
+     */
+    const AVClass *av_class;
+
+    /**
+     * Can only be iformat or oformat, not both at the same time.
+     *
+     * decoding: set by avformat_open_input().
+     * encoding: set by the user.
+     */
+    struct AVInputFormat *iformat;
+    struct AVOutputFormat *oformat;
+
+    /**
+     * Format private data. This is an AVOptions-enabled struct
+     * if and only if iformat/oformat.priv_class is not NULL.
+     */
+    void *priv_data;
+
+    /*
+     * I/O context.
+     *
+     * decoding: either set by the user before avformat_open_input() (then
+     * the user must close it manually) or set by avformat_open_input().
+     * encoding: set by the user.
+     *
+     * Do NOT set this field if AVFMT_NOFILE flag is set in
+     * iformat/oformat.flags. In such a case, the (de)muxer will handle
+     * I/O in some other way and this field will be NULL.
+     */
+    AVIOContext *pb;
+
+    /**
+     * A list of all streams in the file. New streams are created with
+     * avformat_new_stream().
+     *
+     * decoding: streams are created by libavformat in avformat_open_input().
+     * If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also
+     * appear in av_read_frame().
+     * encoding: streams are created by the user before avformat_write_header().
+     */
+    unsigned int nb_streams;
+    AVStream **streams;
+
+    char filename[1024]; /**< input or output filename */
+    /* stream info */
+#if FF_API_TIMESTAMP
+    /**
+     * @deprecated use 'creation_time' metadata tag instead
+     */
+    attribute_deprecated int64_t timestamp;
+#endif
+
+    int ctx_flags; /**< Format-specific flags, see AVFMTCTX_xx */
+#if FF_API_REORDER_PRIVATE
+    /* private data for pts handling (do not modify directly). */
+    /**
+     * This buffer is only needed when packets were already buffered but
+     * not decoded, for example to get the codec parameters in MPEG
+     * streams.
+     */
+    struct AVPacketList *packet_buffer;
+#endif
+
+    /**
+     * Decoding: position of the first frame of the component, in
+     * AV_TIME_BASE fractional seconds. NEVER set this value directly:
+     * It is deduced from the AVStream values.
+     */
+    int64_t start_time;
+
+    /**
+     * Decoding: duration of the stream, in AV_TIME_BASE fractional
+     * seconds. Only set this value if you know none of the individual stream
+     * durations and also do not set any of them. This is deduced from the
+     * AVStream values if not set.
+     */
+    int64_t duration;
+
+#if FF_API_FILESIZE
+    /**
+     * decoding: total file size, 0 if unknown
+     */
+    attribute_deprecated int64_t file_size;
+#endif
+
+    /**
+     * Decoding: total stream bitrate in bit/s, 0 if not
+     * available. Never set it directly if the file_size and the
+     * duration are known as Libav can compute it automatically.
+     */
+    int bit_rate;
+
+#if FF_API_REORDER_PRIVATE
+    /* av_read_frame() support */
+    AVStream *cur_st;
+
+    /* av_seek_frame() support */
+    int64_t data_offset; /**< offset of the first packet */
+#endif
+
+#if FF_API_MUXRATE
+    /**
+     * use mpeg muxer private options instead
+     */
+    attribute_deprecated int mux_rate;
+#endif
+    unsigned int packet_size;
+#if FF_API_PRELOAD
+    attribute_deprecated int preload;
+#endif
+    int max_delay;
+
+#if FF_API_LOOP_OUTPUT
+#define AVFMT_NOOUTPUTLOOP -1
+#define AVFMT_INFINITEOUTPUTLOOP 0
+    /**
+     * number of times to loop output in formats that support it
+     *
+     * @deprecated use the 'loop' private option in the gif muxer.
+     */
+    attribute_deprecated int loop_output;
+#endif
+
+    int flags;
+#define AVFMT_FLAG_GENPTS       0x0001 ///< Generate missing pts even if it requires parsing future frames.
+#define AVFMT_FLAG_IGNIDX       0x0002 ///< Ignore index.
+#define AVFMT_FLAG_NONBLOCK     0x0004 ///< Do not block when reading packets from input.
+#define AVFMT_FLAG_IGNDTS       0x0008 ///< Ignore DTS on frames that contain both DTS & PTS
+#define AVFMT_FLAG_NOFILLIN     0x0010 ///< Do not infer any values from other values, just return what is stored in the container
+#define AVFMT_FLAG_NOPARSE      0x0020 ///< Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled
+#if FF_API_FLAG_RTP_HINT
+#define AVFMT_FLAG_RTP_HINT     0x0040 ///< Deprecated, use the -movflags rtphint muxer specific AVOption instead
+#endif
+#define AVFMT_FLAG_CUSTOM_IO    0x0080 ///< The caller has supplied a custom AVIOContext, don't avio_close() it.
+#define AVFMT_FLAG_DISCARD_CORRUPT  0x0100 ///< Discard frames marked corrupted
+
+#if FF_API_LOOP_INPUT
+    /**
+     * @deprecated, use the 'loop' img2 demuxer private option.
+     */
+    attribute_deprecated int loop_input;
+#endif
+
+    /**
+     * decoding: size of data to probe; encoding: unused.
+     */
+    unsigned int probesize;
+
+    /**
+     * decoding: maximum time (in AV_TIME_BASE units) during which the input should
+     * be analyzed in avformat_find_stream_info().
+     */
+    int max_analyze_duration;
+
+    const uint8_t *key;
+    int keylen;
+
+    unsigned int nb_programs;
+    AVProgram **programs;
+
+    /**
+     * Forced video codec_id.
+     * Demuxing: Set by user.
+     */
+    enum CodecID video_codec_id;
+
+    /**
+     * Forced audio codec_id.
+     * Demuxing: Set by user.
+     */
+    enum CodecID audio_codec_id;
+
+    /**
+     * Forced subtitle codec_id.
+     * Demuxing: Set by user.
+     */
+    enum CodecID subtitle_codec_id;
+
+    /**
+     * Maximum amount of memory in bytes to use for the index of each stream.
+     * If the index exceeds this size, entries will be discarded as
+     * needed to maintain a smaller size. This can lead to slower or less
+     * accurate seeking (depends on demuxer).
+     * Demuxers for which a full in-memory index is mandatory will ignore
+     * this.
+     * muxing  : unused
+     * demuxing: set by user
+     */
+    unsigned int max_index_size;
+
+    /**
+     * Maximum amount of memory in bytes to use for buffering frames
+     * obtained from realtime capture devices.
+     */
+    unsigned int max_picture_buffer;
+
+    unsigned int nb_chapters;
+    AVChapter **chapters;
+
+    /**
+     * Flags to enable debugging.
+     */
+    int debug;
+#define FF_FDEBUG_TS        0x0001
+
+#if FF_API_REORDER_PRIVATE
+    /**
+     * Raw packets from the demuxer, prior to parsing and decoding.
+     * This buffer is used for buffering packets until the codec can
+     * be identified, as parsing cannot be done without knowing the
+     * codec.
+     */
+    struct AVPacketList *raw_packet_buffer;
+    struct AVPacketList *raw_packet_buffer_end;
+
+    struct AVPacketList *packet_buffer_end;
+#endif
+
+    AVDictionary *metadata;
+
+#if FF_API_REORDER_PRIVATE
+    /**
+     * Remaining size available for raw_packet_buffer, in bytes.
+     * NOT PART OF PUBLIC API
+     */
+#define RAW_PACKET_BUFFER_SIZE 2500000
+    int raw_packet_buffer_remaining_size;
+#endif
+
+    /**
+     * Start time of the stream in real world time, in microseconds
+     * since the unix epoch (00:00 1st January 1970). That is, pts=0
+     * in the stream was captured at this real world time.
+     * - encoding: Set by user.
+     * - decoding: Unused.
+     */
+    int64_t start_time_realtime;
+
+    /**
+     * decoding: number of frames used to probe fps
+     */
+    int fps_probe_size;
+
+    /**
+     * Error recognition; higher values will detect more errors but may
+     * misdetect some more or less valid parts as errors.
+     * - encoding: unused
+     * - decoding: Set by user.
+     */
+    int error_recognition;
+
+    /**
+     * Custom interrupt callbacks for the I/O layer.
+     *
+     * decoding: set by the user before avformat_open_input().
+     * encoding: set by the user before avformat_write_header()
+     * (mainly useful for AVFMT_NOFILE formats). The callback
+     * should also be passed to avio_open2() if it's used to
+     * open the file.
+     */
+    AVIOInterruptCB interrupt_callback;
+
+    /*****************************************************************
+     * All fields below this line are not part of the public API. They
+     * may not be used outside of libavformat and can be changed and
+     * removed at will.
+     * New public fields should be added right above.
+     *****************************************************************
+     */
+#if !FF_API_REORDER_PRIVATE
+    /**
+     * Raw packets from the demuxer, prior to parsing and decoding.
+     * This buffer is used for buffering packets until the codec can
+     * be identified, as parsing cannot be done without knowing the
+     * codec.
+     */
+    struct AVPacketList *raw_packet_buffer;
+    struct AVPacketList *raw_packet_buffer_end;
+    /**
+     * Remaining size available for raw_packet_buffer, in bytes.
+     */
+#define RAW_PACKET_BUFFER_SIZE 2500000
+    int raw_packet_buffer_remaining_size;
+
+    /**
+     * This buffer is only needed when packets were already buffered but
+     * not decoded, for example to get the codec parameters in MPEG
+     * streams.
+     */
+    struct AVPacketList *packet_buffer;
+    struct AVPacketList *packet_buffer_end;
+
+    /* av_read_frame() support */
+    AVStream *cur_st;
+
+    /* av_seek_frame() support */
+    int64_t data_offset; /**< offset of the first packet */
+#endif
+} AVFormatContext;
+
+typedef struct AVPacketList {
+    AVPacket pkt;
+    struct AVPacketList *next;
+} AVPacketList;
+
+
+/**
+ * @defgroup lavf_core Core functions
+ * @ingroup libavf
+ *
+ * Functions for querying libavformat capabilities, allocating core structures,
+ * etc.
+ * @{
+ */
+
+/**
+ * Return the LIBAVFORMAT_VERSION_INT constant.
+ */
+unsigned avformat_version(void);
+
+/**
+ * Return the libavformat build-time configuration.
+ */
+const char *avformat_configuration(void);
+
+/**
+ * Return the libavformat license.
+ */
+const char *avformat_license(void);
+
+/**
+ * Initialize libavformat and register all the muxers, demuxers and
+ * protocols. If you do not call this function, then you can select
+ * exactly which formats you want to support.
+ *
+ * @see av_register_input_format()
+ * @see av_register_output_format()
+ * @see av_register_protocol()
+ */
+void av_register_all(void);
+
+void av_register_input_format(AVInputFormat *format);
+void av_register_output_format(AVOutputFormat *format);
+
+/**
+ * Do global initialization of network components. This is optional,
+ * but recommended, since it avoids the overhead of implicitly
+ * doing the setup for each session.
+ *
+ * Calling this function will become mandatory if using network
+ * protocols at some major version bump.
+ */
+int avformat_network_init(void);
+
+/**
+ * Undo the initialization done by avformat_network_init.
+ */
+int avformat_network_deinit(void);
+
+/**
+ * If f is NULL, returns the first registered input format,
+ * if f is non-NULL, returns the next registered input format after f
+ * or NULL if f is the last one.
+ */
+AVInputFormat  *av_iformat_next(AVInputFormat  *f);
+
+/**
+ * If f is NULL, returns the first registered output format,
+ * if f is non-NULL, returns the next registered output format after f
+ * or NULL if f is the last one.
+ */
+AVOutputFormat *av_oformat_next(AVOutputFormat *f);
+
+/**
+ * Allocate an AVFormatContext.
+ * avformat_free_context() can be used to free the context and everything
+ * allocated by the framework within it.
+ */
+AVFormatContext *avformat_alloc_context(void);
+
+/**
+ * Free an AVFormatContext and all its streams.
+ * @param s context to free
+ */
+void avformat_free_context(AVFormatContext *s);
+
+/**
+ * Get the AVClass for AVFormatContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avformat_get_class(void);
+
+/**
+ * Add a new stream to a media file.
+ *
+ * When demuxing, it is called by the demuxer in read_header(). If the
+ * flag AVFMTCTX_NOHEADER is set in s.ctx_flags, then it may also
+ * be called in read_packet().
+ *
+ * When muxing, should be called by the user before avformat_write_header().
+ *
+ * @param c If non-NULL, the AVCodecContext corresponding to the new stream
+ * will be initialized to use this codec. This is needed for e.g. codec-specific
+ * defaults to be set, so codec should be provided if it is known.
+ *
+ * @return newly created stream or NULL on error.
+ */
+AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c);
+
+AVProgram *av_new_program(AVFormatContext *s, int id);
+
+/**
+ * @}
+ */
+
+
+#if FF_API_GUESS_IMG2_CODEC
+attribute_deprecated enum CodecID av_guess_image2_codec(const char *filename);
+#endif
+
+#if FF_API_PKT_DUMP
+attribute_deprecated void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload);
+attribute_deprecated void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt,
+                                          int dump_payload);
+#endif
+
+
+/**
+ * @addtogroup lavf_decoding
+ * @{
+ */
+
+/**
+ * Find AVInputFormat based on the short name of the input format.
+ */
+AVInputFormat *av_find_input_format(const char *short_name);
+
+/**
+ * Guess the file format.
+ *
+ * @param is_opened Whether the file is already opened; determines whether
+ *                  demuxers with or without AVFMT_NOFILE are probed.
+ */
+AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened);
+
+/**
+ * Guess the file format.
+ *
+ * @param is_opened Whether the file is already opened; determines whether
+ *                  demuxers with or without AVFMT_NOFILE are probed.
+ * @param score_max A probe score larger that this is required to accept a
+ *                  detection, the variable is set to the actual detection
+ *                  score afterwards.
+ *                  If the score is <= AVPROBE_SCORE_MAX / 4 it is recommended
+ *                  to retry with a larger probe buffer.
+ */
+AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max);
+
+/**
+ * Probe a bytestream to determine the input format. Each time a probe returns
+ * with a score that is too low, the probe buffer size is increased and another
+ * attempt is made. When the maximum probe size is reached, the input format
+ * with the highest score is returned.
+ *
+ * @param pb the bytestream to probe
+ * @param fmt the input format is put here
+ * @param filename the filename of the stream
+ * @param logctx the log context
+ * @param offset the offset within the bytestream to probe from
+ * @param max_probe_size the maximum probe buffer size (zero for default)
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
+                          const char *filename, void *logctx,
+                          unsigned int offset, unsigned int max_probe_size);
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * Allocate all the structures needed to read an input stream.
+ *        This does not open the needed codecs for decoding the stream[s].
+ * @deprecated use avformat_open_input instead.
+ */
+attribute_deprecated int av_open_input_stream(AVFormatContext **ic_ptr,
+                         AVIOContext *pb, const char *filename,
+                         AVInputFormat *fmt, AVFormatParameters *ap);
+
+/**
+ * Open a media file as input. The codecs are not opened. Only the file
+ * header (if present) is read.
+ *
+ * @param ic_ptr The opened media file handle is put here.
+ * @param filename filename to open
+ * @param fmt If non-NULL, force the file format to use.
+ * @param buf_size optional buffer size (zero if default is OK)
+ * @param ap Additional parameters needed when opening the file
+ *           (NULL if default).
+ * @return 0 if OK, AVERROR_xxx otherwise
+ *
+ * @deprecated use avformat_open_input instead.
+ */
+attribute_deprecated int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
+                       AVInputFormat *fmt,
+                       int buf_size,
+                       AVFormatParameters *ap);
+#endif
+
+/**
+ * Open an input stream and read the header. The codecs are not opened.
+ * The stream must be closed with av_close_input_file().
+ *
+ * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context).
+ *           May be a pointer to NULL, in which case an AVFormatContext is allocated by this
+ *           function and written into ps.
+ *           Note that a user-supplied AVFormatContext will be freed on failure.
+ * @param filename Name of the stream to open.
+ * @param fmt If non-NULL, this parameter forces a specific input format.
+ *            Otherwise the format is autodetected.
+ * @param options  A dictionary filled with AVFormatContext and demuxer-private options.
+ *                 On return this parameter will be destroyed and replaced with a dict containing
+ *                 options that were not found. May be NULL.
+ *
+ * @return 0 on success, a negative AVERROR on failure.
+ *
+ * @note If you want to use custom IO, preallocate the format context and set its pb field.
+ */
+int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options);
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * Read packets of a media file to get stream information. This
+ * is useful for file formats with no headers such as MPEG. This
+ * function also computes the real framerate in case of MPEG-2 repeat
+ * frame mode.
+ * The logical file position is not changed by this function;
+ * examined packets may be buffered for later processing.
+ *
+ * @param ic media file handle
+ * @return >=0 if OK, AVERROR_xxx on error
+ * @todo Let the user decide somehow what information is needed so that
+ *       we do not waste time getting stuff the user does not need.
+ *
+ * @deprecated use avformat_find_stream_info.
+ */
+attribute_deprecated
+int av_find_stream_info(AVFormatContext *ic);
+#endif
+
+/**
+ * Read packets of a media file to get stream information. This
+ * is useful for file formats with no headers such as MPEG. This
+ * function also computes the real framerate in case of MPEG-2 repeat
+ * frame mode.
+ * The logical file position is not changed by this function;
+ * examined packets may be buffered for later processing.
+ *
+ * @param ic media file handle
+ * @param options  If non-NULL, an ic.nb_streams long array of pointers to
+ *                 dictionaries, where i-th member contains options for
+ *                 codec corresponding to i-th stream.
+ *                 On return each dictionary will be filled with options that were not found.
+ * @return >=0 if OK, AVERROR_xxx on error
+ *
+ * @note this function isn't guaranteed to open all the codecs, so
+ *       options being non-empty at return is a perfectly normal behavior.
+ *
+ * @todo Let the user decide somehow what information is needed so that
+ *       we do not waste time getting stuff the user does not need.
+ */
+int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options);
+
+/**
+ * Find the "best" stream in the file.
+ * The best stream is determined according to various heuristics as the most
+ * likely to be what the user expects.
+ * If the decoder parameter is non-NULL, av_find_best_stream will find the
+ * default decoder for the stream's codec; streams for which no decoder can
+ * be found are ignored.
+ *
+ * @param ic                media file handle
+ * @param type              stream type: video, audio, subtitles, etc.
+ * @param wanted_stream_nb  user-requested stream number,
+ *                          or -1 for automatic selection
+ * @param related_stream    try to find a stream related (eg. in the same
+ *                          program) to this one, or -1 if none
+ * @param decoder_ret       if non-NULL, returns the decoder for the
+ *                          selected stream
+ * @param flags             flags; none are currently defined
+ * @return  the non-negative stream number in case of success,
+ *          AVERROR_STREAM_NOT_FOUND if no stream with the requested type
+ *          could be found,
+ *          AVERROR_DECODER_NOT_FOUND if streams were found but no decoder
+ * @note  If av_find_best_stream returns successfully and decoder_ret is not
+ *        NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec.
+ */
+int av_find_best_stream(AVFormatContext *ic,
+                        enum AVMediaType type,
+                        int wanted_stream_nb,
+                        int related_stream,
+                        AVCodec **decoder_ret,
+                        int flags);
+
+/**
+ * Read a transport packet from a media file.
+ *
+ * This function is obsolete and should never be used.
+ * Use av_read_frame() instead.
+ *
+ * @param s media file handle
+ * @param pkt is filled
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+int av_read_packet(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Return the next frame of a stream.
+ * This function returns what is stored in the file, and does not validate
+ * that what is there are valid frames for the decoder. It will split what is
+ * stored in the file into frames and return one for each call. It will not
+ * omit invalid data between valid frames so as to give the decoder the maximum
+ * information possible for decoding.
+ *
+ * The returned packet is valid
+ * until the next av_read_frame() or until av_close_input_file() and
+ * must be freed with av_free_packet. For video, the packet contains
+ * exactly one frame. For audio, it contains an integer number of
+ * frames if each frame has a known fixed size (e.g. PCM or ADPCM
+ * data). If the audio frames have a variable size (e.g. MPEG audio),
+ * then it contains one frame.
+ *
+ * pkt->pts, pkt->dts and pkt->duration are always set to correct
+ * values in AVStream.time_base units (and guessed if the format cannot
+ * provide them). pkt->pts can be AV_NOPTS_VALUE if the video format
+ * has B-frames, so it is better to rely on pkt->dts if you do not
+ * decompress the payload.
+ *
+ * @return 0 if OK, < 0 on error or end of file
+ */
+int av_read_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Seek to the keyframe at timestamp.
+ * 'timestamp' in 'stream_index'.
+ * @param stream_index If stream_index is (-1), a default
+ * stream is selected, and timestamp is automatically converted
+ * from AV_TIME_BASE units to the stream specific time_base.
+ * @param timestamp Timestamp in AVStream.time_base units
+ *        or, if no stream is specified, in AV_TIME_BASE units.
+ * @param flags flags which select direction and seeking mode
+ * @return >= 0 on success
+ */
+int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp,
+                  int flags);
+
+/**
+ * Seek to timestamp ts.
+ * Seeking will be done so that the point from which all active streams
+ * can be presented successfully will be closest to ts and within min/max_ts.
+ * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL.
+ *
+ * If flags contain AVSEEK_FLAG_BYTE, then all timestamps are in bytes and
+ * are the file position (this may not be supported by all demuxers).
+ * If flags contain AVSEEK_FLAG_FRAME, then all timestamps are in frames
+ * in the stream with stream_index (this may not be supported by all demuxers).
+ * Otherwise all timestamps are in units of the stream selected by stream_index
+ * or if stream_index is -1, in AV_TIME_BASE units.
+ * If flags contain AVSEEK_FLAG_ANY, then non-keyframes are treated as
+ * keyframes (this may not be supported by all demuxers).
+ *
+ * @param stream_index index of the stream which is used as time base reference
+ * @param min_ts smallest acceptable timestamp
+ * @param ts target timestamp
+ * @param max_ts largest acceptable timestamp
+ * @param flags flags
+ * @return >=0 on success, error code otherwise
+ *
+ * @note This is part of the new seek API which is still under construction.
+ *       Thus do not use this yet. It may change at any time, do not expect
+ *       ABI compatibility yet!
+ */
+int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags);
+
+/**
+ * Start playing a network-based stream (e.g. RTSP stream) at the
+ * current position.
+ */
+int av_read_play(AVFormatContext *s);
+
+/**
+ * Pause a network-based stream (e.g. RTSP stream).
+ *
+ * Use av_read_play() to resume it.
+ */
+int av_read_pause(AVFormatContext *s);
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * Free a AVFormatContext allocated by av_open_input_stream.
+ * @param s context to free
+ * @deprecated use av_close_input_file()
+ */
+attribute_deprecated
+void av_close_input_stream(AVFormatContext *s);
+#endif
+
+#if FF_API_CLOSE_INPUT_FILE
+/**
+ * @deprecated use avformat_close_input()
+ * Close a media file (but not its codecs).
+ *
+ * @param s media file handle
+ */
+attribute_deprecated
+void av_close_input_file(AVFormatContext *s);
+#endif
+
+/**
+ * Close an opened input AVFormatContext. Free it and all its contents
+ * and set *s to NULL.
+ */
+void avformat_close_input(AVFormatContext **s);
+/**
+ * @}
+ */
+
+#if FF_API_NEW_STREAM
+/**
+ * Add a new stream to a media file.
+ *
+ * Can only be called in the read_header() function. If the flag
+ * AVFMTCTX_NOHEADER is in the format context, then new streams
+ * can be added in read_packet too.
+ *
+ * @param s media file handle
+ * @param id file-format-dependent stream ID
+ */
+attribute_deprecated
+AVStream *av_new_stream(AVFormatContext *s, int id);
+#endif
+
+#if FF_API_SET_PTS_INFO
+/**
+ * @deprecated this function is not supposed to be called outside of lavf
+ */
+attribute_deprecated
+void av_set_pts_info(AVStream *s, int pts_wrap_bits,
+                     unsigned int pts_num, unsigned int pts_den);
+#endif
+
+#define AVSEEK_FLAG_BACKWARD 1 ///< seek backward
+#define AVSEEK_FLAG_BYTE     2 ///< seeking based on position in bytes
+#define AVSEEK_FLAG_ANY      4 ///< seek to any frame, even non-keyframes
+#define AVSEEK_FLAG_FRAME    8 ///< seeking based on frame number
+
+#if FF_API_SEEK_PUBLIC
+attribute_deprecated
+int av_seek_frame_binary(AVFormatContext *s, int stream_index,
+                         int64_t target_ts, int flags);
+attribute_deprecated
+void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp);
+attribute_deprecated
+int64_t av_gen_search(AVFormatContext *s, int stream_index,
+                      int64_t target_ts, int64_t pos_min,
+                      int64_t pos_max, int64_t pos_limit,
+                      int64_t ts_min, int64_t ts_max,
+                      int flags, int64_t *ts_ret,
+                      int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ));
+#endif
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * @deprecated pass the options to avformat_write_header directly.
+ */
+attribute_deprecated int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap);
+#endif
+
+/**
+ * @addtogroup lavf_encoding
+ * @{
+ */
+/**
+ * Allocate the stream private data and write the stream header to
+ * an output media file.
+ *
+ * @param s Media file handle, must be allocated with avformat_alloc_context().
+ *          Its oformat field must be set to the desired output format;
+ *          Its pb field must be set to an already openened AVIOContext.
+ * @param options  An AVDictionary filled with AVFormatContext and muxer-private options.
+ *                 On return this parameter will be destroyed and replaced with a dict containing
+ *                 options that were not found. May be NULL.
+ *
+ * @return 0 on success, negative AVERROR on failure.
+ *
+ * @see av_opt_find, av_dict_set, avio_open, av_oformat_next.
+ */
+int avformat_write_header(AVFormatContext *s, AVDictionary **options);
+
+#if FF_API_FORMAT_PARAMETERS
+/**
+ * Allocate the stream private data and write the stream header to an
+ * output media file.
+ * @note: this sets stream time-bases, if possible to stream->codec->time_base
+ * but for some formats it might also be some other time base
+ *
+ * @param s media file handle
+ * @return 0 if OK, AVERROR_xxx on error
+ *
+ * @deprecated use avformat_write_header.
+ */
+attribute_deprecated int av_write_header(AVFormatContext *s);
+#endif
+
+/**
+ * Write a packet to an output media file.
+ *
+ * The packet shall contain one audio or video frame.
+ * The packet must be correctly interleaved according to the container
+ * specification, if not then av_interleaved_write_frame must be used.
+ *
+ * @param s media file handle
+ * @param pkt The packet, which contains the stream_index, buf/buf_size,
+              dts/pts, ...
+ * @return < 0 on error, = 0 if OK, 1 if end of stream wanted
+ */
+int av_write_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Write a packet to an output media file ensuring correct interleaving.
+ *
+ * The packet must contain one audio or video frame.
+ * If the packets are already correctly interleaved, the application should
+ * call av_write_frame() instead as it is slightly faster. It is also important
+ * to keep in mind that completely non-interleaved input will need huge amounts
+ * of memory to interleave with this, so it is preferable to interleave at the
+ * demuxer level.
+ *
+ * @param s media file handle
+ * @param pkt The packet containing the data to be written. Libavformat takes
+ * ownership of the data and will free it when it sees fit using the packet's
+ * @ref AVPacket.destruct "destruct" field. The caller must not access the data
+ * after this function returns, as it may already be freed.
+ * Packet's @ref AVPacket.stream_index "stream_index" field must be set to the
+ * index of the corresponding stream in @ref AVFormatContext.streams
+ * "s.streams".
+ * It is very strongly recommended that timing information (@ref AVPacket.pts
+ * "pts", @ref AVPacket.dts "dts" @ref AVPacket.duration "duration") is set to
+ * correct values.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);
+
+/**
+ * Interleave a packet per dts in an output media file.
+ *
+ * Packets with pkt->destruct == av_destruct_packet will be freed inside this
+ * function, so they cannot be used after it. Note that calling av_free_packet()
+ * on them is still safe.
+ *
+ * @param s media file handle
+ * @param out the interleaved packet will be output here
+ * @param pkt the input packet
+ * @param flush 1 if no further packets are available as input and all
+ *              remaining packets should be output
+ * @return 1 if a packet was output, 0 if no packet could be output,
+ *         < 0 if an error occurred
+ */
+int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
+                                 AVPacket *pkt, int flush);
+
+/**
+ * Write the stream trailer to an output media file and free the
+ * file private data.
+ *
+ * May only be called after a successful call to av_write_header.
+ *
+ * @param s media file handle
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+int av_write_trailer(AVFormatContext *s);
+
+/**
+ * Return the output format in the list of registered output formats
+ * which best matches the provided parameters, or return NULL if
+ * there is no match.
+ *
+ * @param short_name if non-NULL checks if short_name matches with the
+ * names of the registered formats
+ * @param filename if non-NULL checks if filename terminates with the
+ * extensions of the registered formats
+ * @param mime_type if non-NULL checks if mime_type matches with the
+ * MIME type of the registered formats
+ */
+AVOutputFormat *av_guess_format(const char *short_name,
+                                const char *filename,
+                                const char *mime_type);
+
+/**
+ * Guess the codec ID based upon muxer and filename.
+ */
+enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
+                            const char *filename, const char *mime_type,
+                            enum AVMediaType type);
+
+/**
+ * @}
+ */
+
+
+/**
+ * @defgroup lavf_misc Utility functions
+ * @ingroup libavf
+ * @{
+ *
+ * Miscelaneous utility functions related to both muxing and demuxing
+ * (or neither).
+ */
+
+/**
+ * Send a nice hexadecimal dump of a buffer to the specified file stream.
+ *
+ * @param f The file stream pointer where the dump should be sent to.
+ * @param buf buffer
+ * @param size buffer size
+ *
+ * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2
+ */
+void av_hex_dump(FILE *f, uint8_t *buf, int size);
+
+/**
+ * Send a nice hexadecimal dump of a buffer to the log.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param buf buffer
+ * @param size buffer size
+ *
+ * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2
+ */
+void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size);
+
+/**
+ * Send a nice dump of a packet to the specified file stream.
+ *
+ * @param f The file stream pointer where the dump should be sent to.
+ * @param pkt packet to dump
+ * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
+ */
+void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st);
+
+
+/**
+ * Send a nice dump of a packet to the log.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param pkt packet to dump
+ * @param dump_payload True if the payload must be displayed, too.
+ * @param st AVStream that the packet belongs to
+ */
+void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
+                      AVStream *st);
+
+/**
+ * Get the CodecID for the given codec tag tag.
+ * If no codec id is found returns CODEC_ID_NONE.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
+enum CodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag);
+
+/**
+ * Get the codec tag for the given codec id id.
+ * If no codec tag is found returns 0.
+ *
+ * @param tags list of supported codec_id-codec_tag pairs, as stored
+ * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag
+ */
+unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum CodecID id);
+
+int av_find_default_stream_index(AVFormatContext *s);
+
+/**
+ * Get the index for a specific timestamp.
+ * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond
+ *                 to the timestamp which is <= the requested one, if backward
+ *                 is 0, then it will be >=
+ *              if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
+ * @return < 0 if no such timestamp could be found
+ */
+int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags);
+
+/**
+ * Add an index entry into a sorted list. Update the entry if the list
+ * already contains it.
+ *
+ * @param timestamp timestamp in the time base of the given stream
+ */
+int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
+                       int size, int distance, int flags);
+
+
+/**
+ * Split a URL string into components.
+ *
+ * The pointers to buffers for storing individual components may be null,
+ * in order to ignore that component. Buffers for components not found are
+ * set to empty strings. If the port is not found, it is set to a negative
+ * value.
+ *
+ * @param proto the buffer for the protocol
+ * @param proto_size the size of the proto buffer
+ * @param authorization the buffer for the authorization
+ * @param authorization_size the size of the authorization buffer
+ * @param hostname the buffer for the host name
+ * @param hostname_size the size of the hostname buffer
+ * @param port_ptr a pointer to store the port number in
+ * @param path the buffer for the path
+ * @param path_size the size of the path buffer
+ * @param url the URL to split
+ */
+void av_url_split(char *proto,         int proto_size,
+                  char *authorization, int authorization_size,
+                  char *hostname,      int hostname_size,
+                  int *port_ptr,
+                  char *path,          int path_size,
+                  const char *url);
+
+#if FF_API_DUMP_FORMAT
+attribute_deprecated void dump_format(AVFormatContext *ic,
+                                      int index,
+                                      const char *url,
+                                      int is_output);
+#endif
+
+void av_dump_format(AVFormatContext *ic,
+                    int index,
+                    const char *url,
+                    int is_output);
+
+#if FF_API_PARSE_DATE
+/**
+ * Parse datestr and return a corresponding number of microseconds.
+ *
+ * @param datestr String representing a date or a duration.
+ * See av_parse_time() for the syntax of the provided string.
+ * @deprecated in favor of av_parse_time()
+ */
+attribute_deprecated
+int64_t parse_date(const char *datestr, int duration);
+#endif
+
+/**
+ * Get the current time in microseconds.
+ */
+int64_t av_gettime(void);
+
+#if FF_API_FIND_INFO_TAG
+/**
+ * @deprecated use av_find_info_tag in libavutil instead.
+ */
+attribute_deprecated int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+#endif
+
+/**
+ * Return in 'buf' the path with '%d' replaced by a number.
+ *
+ * Also handles the '%0nd' format where 'n' is the total number
+ * of digits and '%%'.
+ *
+ * @param buf destination buffer
+ * @param buf_size destination buffer size
+ * @param path numbered sequence string
+ * @param number frame number
+ * @return 0 if OK, -1 on format error
+ */
+int av_get_frame_filename(char *buf, int buf_size,
+                          const char *path, int number);
+
+/**
+ * Check whether filename actually is a numbered sequence generator.
+ *
+ * @param filename possible numbered sequence string
+ * @return 1 if a valid numbered sequence string, 0 otherwise
+ */
+int av_filename_number_test(const char *filename);
+
+/**
+ * Generate an SDP for an RTP session.
+ *
+ * @param ac array of AVFormatContexts describing the RTP streams. If the
+ *           array is composed by only one context, such context can contain
+ *           multiple AVStreams (one AVStream per RTP stream). Otherwise,
+ *           all the contexts in the array (an AVCodecContext per RTP stream)
+ *           must contain only one AVStream.
+ * @param n_files number of AVCodecContexts contained in ac
+ * @param buf buffer where the SDP will be stored (must be allocated by
+ *            the caller)
+ * @param size the size of the buffer
+ * @return 0 if OK, AVERROR_xxx on error
+ */
+int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size);
+
+#if FF_API_SDP_CREATE
+attribute_deprecated int avf_sdp_create(AVFormatContext *ac[], int n_files, char *buff, int size);
+#endif
+
+/**
+ * Return a positive value if the given filename has one of the given
+ * extensions, 0 otherwise.
+ *
+ * @param extensions a comma-separated list of filename extensions
+ */
+int av_match_ext(const char *filename, const char *extensions);
+
+/**
+ * Test if the given container can store a codec.
+ *
+ * @param std_compliance standards compliance level, one of FF_COMPLIANCE_*
+ *
+ * @return 1 if codec with ID codec_id can be stored in ofmt, 0 if it cannot.
+ *         A negative number if this information is not available.
+ */
+int avformat_query_codec(AVOutputFormat *ofmt, enum CodecID codec_id, int std_compliance);
+
+/**
+ * @defgroup riff_fourcc RIFF FourCCs
+ * @{
+ * Get the tables mapping RIFF FourCCs to libavcodec CodecIDs. The tables are
+ * meant to be passed to av_codec_get_id()/av_codec_get_tag() as in the
+ * following code:
+ * @code
+ * uint32_t tag = MKTAG('H', '2', '6', '4');
+ * const struct AVCodecTag *table[] = { avformat_get_riff_video_tags(), 0 };
+ * enum CodecID id = av_codec_get_id(table, tag);
+ * @endcode
+ */
+/**
+ * @return the table mapping RIFF FourCCs for video to libavcodec CodecID.
+ */
+const struct AVCodecTag *avformat_get_riff_video_tags(void);
+/**
+ * @return the table mapping RIFF FourCCs for audio to CodecID.
+ */
+const struct AVCodecTag *avformat_get_riff_audio_tags(void);
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#endif /* AVFORMAT_AVFORMAT_H */
diff --git a/make/stub_includes/libav/libavformat/avio.h b/make/stub_includes/libav/libavformat/avio.h
new file mode 100644
index 0000000..78935d9
--- /dev/null
+++ b/make/stub_includes/libav/libavformat/avio.h
@@ -0,0 +1,688 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef AVFORMAT_AVIO_H
+#define AVFORMAT_AVIO_H
+
+/**
+ * @file
+ * @ingroup lavf_io
+ * Buffered I/O operations
+ */
+
+#include <stdint.h>
+
+#include "libavutil/common.h"
+#include "libavutil/dict.h"
+#include "libavutil/log.h"
+
+#include "libavformat/version.h"
+
+
+#define AVIO_SEEKABLE_NORMAL 0x0001 /**< Seeking works like for a local file */
+
+/**
+ * Callback for checking whether to abort blocking functions.
+ * AVERROR_EXIT is returned in this case by the interrupted
+ * function. During blocking operations, callback is called with
+ * opaque as parameter. If the callback returns 1, the
+ * blocking operation will be aborted.
+ *
+ * No members can be added to this struct without a major bump, if
+ * new elements have been added after this struct in AVFormatContext
+ * or AVIOContext.
+ */
+typedef struct {
+    int (*callback)(void*);
+    void *opaque;
+} AVIOInterruptCB;
+
+/**
+ * Bytestream IO Context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(AVIOContext) must not be used outside libav*.
+ *
+ * @note None of the function pointers in AVIOContext should be called
+ *       directly, they should only be set by the client application
+ *       when implementing custom I/O. Normally these are set to the
+ *       function pointers specified in avio_alloc_context()
+ */
+typedef struct {
+#if !FF_API_OLD_AVIO
+    /**
+     * A class for private options.
+     *
+     * If this AVIOContext is created by avio_open2(), av_class is set and
+     * passes the options down to protocols.
+     *
+     * If this AVIOContext is manually allocated, then av_class may be set by
+     * the caller.
+     *
+     * warning -- this field can be NULL, be sure to not pass this AVIOContext
+     * to any av_opt_* functions in that case.
+     */
+    AVClass *av_class;
+#endif
+    unsigned char *buffer;  /**< Start of the buffer. */
+    int buffer_size;        /**< Maximum buffer size */
+    unsigned char *buf_ptr; /**< Current position in the buffer */
+    unsigned char *buf_end; /**< End of the data, may be less than
+                                 buffer+buffer_size if the read function returned
+                                 less data than requested, e.g. for streams where
+                                 no more data has been received yet. */
+    void *opaque;           /**< A private pointer, passed to the read/write/seek/...
+                                 functions. */
+    int (*read_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int (*write_packet)(void *opaque, uint8_t *buf, int buf_size);
+    int64_t (*seek)(void *opaque, int64_t offset, int whence);
+    int64_t pos;            /**< position in the file of the current buffer */
+    int must_flush;         /**< true if the next seek should flush */
+    int eof_reached;        /**< true if eof reached */
+    int write_flag;         /**< true if open for writing */
+#if FF_API_OLD_AVIO
+    attribute_deprecated int is_streamed;
+#endif
+    int max_packet_size;
+    unsigned long checksum;
+    unsigned char *checksum_ptr;
+    unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size);
+    int error;              /**< contains the error code or 0 if no error happened */
+    /**
+     * Pause or resume playback for network streaming protocols - e.g. MMS.
+     */
+    int (*read_pause)(void *opaque, int pause);
+    /**
+     * Seek to a given timestamp in stream with the specified stream_index.
+     * Needed for some network streaming protocols which don't support seeking
+     * to byte position.
+     */
+    int64_t (*read_seek)(void *opaque, int stream_index,
+                         int64_t timestamp, int flags);
+    /**
+     * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
+     */
+    int seekable;
+} AVIOContext;
+
+/* unbuffered I/O */
+
+#if FF_API_OLD_AVIO
+/**
+ * URL Context.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * sizeof(URLContext) must not be used outside libav*.
+ * @deprecated This struct will be made private
+ */
+typedef struct URLContext {
+    const AVClass *av_class; ///< information for av_log(). Set by url_open().
+    struct URLProtocol *prot;
+    int flags;
+    int is_streamed;  /**< true if streamed (no seek possible), default = false */
+    int max_packet_size;  /**< if non zero, the stream is packetized with this max packet size */
+    void *priv_data;
+    char *filename; /**< specified URL */
+    int is_connected;
+    AVIOInterruptCB interrupt_callback;
+} URLContext;
+
+#define URL_PROTOCOL_FLAG_NESTED_SCHEME 1 /*< The protocol name can be the first part of a nested protocol scheme */
+#define URL_PROTOCOL_FLAG_NETWORK       2 /*< The protocol uses network */
+
+/**
+ * @deprecated This struct is to be made private. Use the higher-level
+ *             AVIOContext-based API instead.
+ */
+typedef struct URLProtocol {
+    const char *name;
+    int (*url_open)(URLContext *h, const char *url, int flags);
+    int (*url_read)(URLContext *h, unsigned char *buf, int size);
+    int (*url_write)(URLContext *h, const unsigned char *buf, int size);
+    int64_t (*url_seek)(URLContext *h, int64_t pos, int whence);
+    int (*url_close)(URLContext *h);
+    struct URLProtocol *next;
+    int (*url_read_pause)(URLContext *h, int pause);
+    int64_t (*url_read_seek)(URLContext *h, int stream_index,
+                             int64_t timestamp, int flags);
+    int (*url_get_file_handle)(URLContext *h);
+    int priv_data_size;
+    const AVClass *priv_data_class;
+    int flags;
+    int (*url_check)(URLContext *h, int mask);
+} URLProtocol;
+
+typedef struct URLPollEntry {
+    URLContext *handle;
+    int events;
+    int revents;
+} URLPollEntry;
+
+/* not implemented */
+attribute_deprecated int url_poll(URLPollEntry *poll_table, int n, int timeout);
+
+/**
+ * @name URL open modes
+ * The flags argument to url_open and cosins must be one of the following
+ * constants, optionally ORed with other flags.
+ * @{
+ */
+#define URL_RDONLY 1  /**< read-only */
+#define URL_WRONLY 2  /**< write-only */
+#define URL_RDWR   (URL_RDONLY|URL_WRONLY)  /**< read-write */
+/**
+ * @}
+ */
+
+/**
+ * Use non-blocking mode.
+ * If this flag is set, operations on the context will return
+ * AVERROR(EAGAIN) if they can not be performed immediately.
+ * If this flag is not set, operations on the context will never return
+ * AVERROR(EAGAIN).
+ * Note that this flag does not affect the opening/connecting of the
+ * context. Connecting a protocol will always block if necessary (e.g. on
+ * network protocols) but never hang (e.g. on busy devices).
+ * Warning: non-blocking protocols is work-in-progress; this flag may be
+ * silently ignored.
+ */
+#define URL_FLAG_NONBLOCK 8
+
+typedef int URLInterruptCB(void);
+extern URLInterruptCB *url_interrupt_cb;
+
+/**
+ * @defgroup old_url_funcs Old url_* functions
+ * The following functions are deprecated. Use the buffered API based on #AVIOContext instead.
+ * @{
+ * @ingroup lavf_io
+ */
+attribute_deprecated int url_open_protocol (URLContext **puc, struct URLProtocol *up,
+                                            const char *url, int flags);
+attribute_deprecated int url_alloc(URLContext **h, const char *url, int flags);
+attribute_deprecated int url_connect(URLContext *h);
+attribute_deprecated int url_open(URLContext **h, const char *url, int flags);
+attribute_deprecated int url_read(URLContext *h, unsigned char *buf, int size);
+attribute_deprecated int url_read_complete(URLContext *h, unsigned char *buf, int size);
+attribute_deprecated int url_write(URLContext *h, const unsigned char *buf, int size);
+attribute_deprecated int64_t url_seek(URLContext *h, int64_t pos, int whence);
+attribute_deprecated int url_close(URLContext *h);
+attribute_deprecated int64_t url_filesize(URLContext *h);
+attribute_deprecated int url_get_file_handle(URLContext *h);
+attribute_deprecated int url_get_max_packet_size(URLContext *h);
+attribute_deprecated void url_get_filename(URLContext *h, char *buf, int buf_size);
+attribute_deprecated int av_url_read_pause(URLContext *h, int pause);
+attribute_deprecated int64_t av_url_read_seek(URLContext *h, int stream_index,
+                                              int64_t timestamp, int flags);
+attribute_deprecated void url_set_interrupt_cb(int (*interrupt_cb)(void));
+/**
+ * If protocol is NULL, returns the first registered protocol,
+ * if protocol is non-NULL, returns the next registered protocol after protocol,
+ * or NULL if protocol is the last one.
+ */
+attribute_deprecated URLProtocol *av_protocol_next(URLProtocol *p);
+/**
+ * Register the URLProtocol protocol.
+ *
+ * @param size the size of the URLProtocol struct referenced
+ */
+attribute_deprecated int av_register_protocol2(URLProtocol *protocol, int size);
+/**
+ * @}
+ */
+
+
+typedef attribute_deprecated AVIOContext ByteIOContext;
+
+attribute_deprecated int init_put_byte(AVIOContext *s,
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+attribute_deprecated AVIOContext *av_alloc_put_byte(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+
+/**
+ * @defgroup old_avio_funcs Old put_/get_*() functions
+ * The following functions are deprecated. Use the "avio_"-prefixed functions instead.
+ * @{
+ * @ingroup lavf_io
+ */
+attribute_deprecated int          get_buffer(AVIOContext *s, unsigned char *buf, int size);
+attribute_deprecated int          get_partial_buffer(AVIOContext *s, unsigned char *buf, int size);
+attribute_deprecated int          get_byte(AVIOContext *s);
+attribute_deprecated unsigned int get_le16(AVIOContext *s);
+attribute_deprecated unsigned int get_le24(AVIOContext *s);
+attribute_deprecated unsigned int get_le32(AVIOContext *s);
+attribute_deprecated uint64_t     get_le64(AVIOContext *s);
+attribute_deprecated unsigned int get_be16(AVIOContext *s);
+attribute_deprecated unsigned int get_be24(AVIOContext *s);
+attribute_deprecated unsigned int get_be32(AVIOContext *s);
+attribute_deprecated uint64_t     get_be64(AVIOContext *s);
+
+attribute_deprecated void         put_byte(AVIOContext *s, int b);
+attribute_deprecated void         put_nbyte(AVIOContext *s, int b, int count);
+attribute_deprecated void         put_buffer(AVIOContext *s, const unsigned char *buf, int size);
+attribute_deprecated void         put_le64(AVIOContext *s, uint64_t val);
+attribute_deprecated void         put_be64(AVIOContext *s, uint64_t val);
+attribute_deprecated void         put_le32(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be32(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_le24(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be24(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_le16(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_be16(AVIOContext *s, unsigned int val);
+attribute_deprecated void         put_tag(AVIOContext *s, const char *tag);
+/**
+ * @}
+ */
+
+attribute_deprecated int     av_url_read_fpause(AVIOContext *h,    int pause);
+attribute_deprecated int64_t av_url_read_fseek (AVIOContext *h,    int stream_index,
+                                                int64_t timestamp, int flags);
+
+/**
+ * @defgroup old_url_f_funcs Old url_f* functions
+ * The following functions are deprecated, use the "avio_"-prefixed functions instead.
+ * @{
+ * @ingroup lavf_io
+ */
+attribute_deprecated int url_fopen( AVIOContext **s, const char *url, int flags);
+attribute_deprecated int url_fclose(AVIOContext *s);
+attribute_deprecated int64_t url_fseek(AVIOContext *s, int64_t offset, int whence);
+attribute_deprecated int url_fskip(AVIOContext *s, int64_t offset);
+attribute_deprecated int64_t url_ftell(AVIOContext *s);
+attribute_deprecated int64_t url_fsize(AVIOContext *s);
+#define URL_EOF (-1)
+attribute_deprecated int url_fgetc(AVIOContext *s);
+attribute_deprecated int url_setbufsize(AVIOContext *s, int buf_size);
+attribute_deprecated int url_fprintf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3);
+attribute_deprecated void put_flush_packet(AVIOContext *s);
+attribute_deprecated int url_open_dyn_buf(AVIOContext **s);
+attribute_deprecated int url_open_dyn_packet_buf(AVIOContext **s, int max_packet_size);
+attribute_deprecated int url_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer);
+attribute_deprecated int url_fdopen(AVIOContext **s, URLContext *h);
+/**
+ * @}
+ */
+
+/**
+ * @deprecated use AVIOContext.eof_reached
+ */
+attribute_deprecated int url_feof(AVIOContext *s);
+attribute_deprecated int url_ferror(AVIOContext *s);
+
+attribute_deprecated int udp_set_remote_url(URLContext *h, const char *uri);
+attribute_deprecated int udp_get_local_port(URLContext *h);
+
+attribute_deprecated void init_checksum(AVIOContext *s,
+                   unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len),
+                   unsigned long checksum);
+attribute_deprecated unsigned long get_checksum(AVIOContext *s);
+attribute_deprecated void put_strz(AVIOContext *s, const char *buf);
+/** @note unlike fgets, the EOL character is not returned and a whole
+    line is parsed. return NULL if first char read was EOF */
+attribute_deprecated char *url_fgets(AVIOContext *s, char *buf, int buf_size);
+/**
+ * @deprecated use avio_get_str instead
+ */
+attribute_deprecated char *get_strz(AVIOContext *s, char *buf, int maxlen);
+/**
+ * @deprecated Use AVIOContext.seekable field directly.
+ */
+attribute_deprecated static inline int url_is_streamed(AVIOContext *s)
+{
+    return !s->seekable;
+}
+attribute_deprecated URLContext *url_fileno(AVIOContext *s);
+
+/**
+ * @deprecated use AVIOContext.max_packet_size directly.
+ */
+attribute_deprecated int url_fget_max_packet_size(AVIOContext *s);
+
+attribute_deprecated int url_open_buf(AVIOContext **s, uint8_t *buf, int buf_size, int flags);
+
+/** return the written or read size */
+attribute_deprecated int url_close_buf(AVIOContext *s);
+
+/**
+ * Return a non-zero value if the resource indicated by url
+ * exists, 0 otherwise.
+ * @deprecated Use avio_check instead.
+ */
+attribute_deprecated int url_exist(const char *url);
+#endif // FF_API_OLD_AVIO
+
+/**
+ * Return AVIO_FLAG_* access flags corresponding to the access permissions
+ * of the resource in url, or a negative value corresponding to an
+ * AVERROR code in case of failure. The returned access flags are
+ * masked by the value in flags.
+ *
+ * @note This function is intrinsically unsafe, in the sense that the
+ * checked resource may change its existence or permission status from
+ * one call to another. Thus you should not trust the returned value,
+ * unless you are sure that no other processes are accessing the
+ * checked resource.
+ */
+int avio_check(const char *url, int flags);
+
+#if FF_API_OLD_INTERRUPT_CB
+/**
+ * The callback is called in blocking functions to test regulary if
+ * asynchronous interruption is needed. AVERROR_EXIT is returned
+ * in this case by the interrupted function. 'NULL' means no interrupt
+ * callback is given.
+ * @deprecated Use interrupt_callback in AVFormatContext/avio_open2
+ *             instead.
+ */
+attribute_deprecated void avio_set_interrupt_cb(int (*interrupt_cb)(void));
+#endif
+
+/**
+ * Allocate and initialize an AVIOContext for buffered I/O. It must be later
+ * freed with av_free().
+ *
+ * @param buffer Memory block for input/output operations via AVIOContext.
+ *        The buffer must be allocated with av_malloc() and friends.
+ * @param buffer_size The buffer size is very important for performance.
+ *        For protocols with fixed blocksize it should be set to this blocksize.
+ *        For others a typical size is a cache page, e.g. 4kb.
+ * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise.
+ * @param opaque An opaque pointer to user-specific data.
+ * @param read_packet  A function for refilling the buffer, may be NULL.
+ * @param write_packet A function for writing the buffer contents, may be NULL.
+ * @param seek A function for seeking to specified byte position, may be NULL.
+ *
+ * @return Allocated AVIOContext or NULL on failure.
+ */
+AVIOContext *avio_alloc_context(
+                  unsigned char *buffer,
+                  int buffer_size,
+                  int write_flag,
+                  void *opaque,
+                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
+                  int64_t (*seek)(void *opaque, int64_t offset, int whence));
+
+void avio_w8(AVIOContext *s, int b);
+void avio_write(AVIOContext *s, const unsigned char *buf, int size);
+void avio_wl64(AVIOContext *s, uint64_t val);
+void avio_wb64(AVIOContext *s, uint64_t val);
+void avio_wl32(AVIOContext *s, unsigned int val);
+void avio_wb32(AVIOContext *s, unsigned int val);
+void avio_wl24(AVIOContext *s, unsigned int val);
+void avio_wb24(AVIOContext *s, unsigned int val);
+void avio_wl16(AVIOContext *s, unsigned int val);
+void avio_wb16(AVIOContext *s, unsigned int val);
+
+/**
+ * Write a NULL-terminated string.
+ * @return number of bytes written.
+ */
+int avio_put_str(AVIOContext *s, const char *str);
+
+/**
+ * Convert an UTF-8 string to UTF-16LE and write it.
+ * @return number of bytes written.
+ */
+int avio_put_str16le(AVIOContext *s, const char *str);
+
+/**
+ * Passing this as the "whence" parameter to a seek function causes it to
+ * return the filesize without seeking anywhere. Supporting this is optional.
+ * If it is not supported then the seek function will return <0.
+ */
+#define AVSEEK_SIZE 0x10000
+
+/**
+ * Oring this flag as into the "whence" parameter to a seek function causes it to
+ * seek by any means (like reopening and linear reading) or other normally unreasonble
+ * means that can be extreemly slow.
+ * This may be ignored by the seek code.
+ */
+#define AVSEEK_FORCE 0x20000
+
+/**
+ * fseek() equivalent for AVIOContext.
+ * @return new position or AVERROR.
+ */
+int64_t avio_seek(AVIOContext *s, int64_t offset, int whence);
+
+/**
+ * Skip given number of bytes forward
+ * @return new position or AVERROR.
+ */
+static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
+{
+    return avio_seek(s, offset, SEEK_CUR);
+}
+
+/**
+ * ftell() equivalent for AVIOContext.
+ * @return position or AVERROR.
+ */
+static av_always_inline int64_t avio_tell(AVIOContext *s)
+{
+    return avio_seek(s, 0, SEEK_CUR);
+}
+
+/**
+ * Get the filesize.
+ * @return filesize or AVERROR
+ */
+int64_t avio_size(AVIOContext *s);
+
+/** @warning currently size is limited */
+int avio_printf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3);
+
+void avio_flush(AVIOContext *s);
+
+
+/**
+ * Read size bytes from AVIOContext into buf.
+ * @return number of bytes read or AVERROR
+ */
+int avio_read(AVIOContext *s, unsigned char *buf, int size);
+
+/**
+ * @name Functions for reading from AVIOContext
+ * @{
+ *
+ * @note return 0 if EOF, so you cannot use it if EOF handling is
+ *       necessary
+ */
+int          avio_r8  (AVIOContext *s);
+unsigned int avio_rl16(AVIOContext *s);
+unsigned int avio_rl24(AVIOContext *s);
+unsigned int avio_rl32(AVIOContext *s);
+uint64_t     avio_rl64(AVIOContext *s);
+unsigned int avio_rb16(AVIOContext *s);
+unsigned int avio_rb24(AVIOContext *s);
+unsigned int avio_rb32(AVIOContext *s);
+uint64_t     avio_rb64(AVIOContext *s);
+/**
+ * @}
+ */
+
+/**
+ * Read a string from pb into buf. The reading will terminate when either
+ * a NULL character was encountered, maxlen bytes have been read, or nothing
+ * more can be read from pb. The result is guaranteed to be NULL-terminated, it
+ * will be truncated if buf is too small.
+ * Note that the string is not interpreted or validated in any way, it
+ * might get truncated in the middle of a sequence for multi-byte encodings.
+ *
+ * @return number of bytes read (is always <= maxlen).
+ * If reading ends on EOF or error, the return value will be one more than
+ * bytes actually read.
+ */
+int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen);
+
+/**
+ * Read a UTF-16 string from pb and convert it to UTF-8.
+ * The reading will terminate when either a null or invalid character was
+ * encountered or maxlen bytes have been read.
+ * @return number of bytes read (is always <= maxlen)
+ */
+int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen);
+int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen);
+
+
+/**
+ * @name URL open modes
+ * The flags argument to avio_open must be one of the following
+ * constants, optionally ORed with other flags.
+ * @{
+ */
+#define AVIO_FLAG_READ  1                                      /**< read-only */
+#define AVIO_FLAG_WRITE 2                                      /**< write-only */
+#define AVIO_FLAG_READ_WRITE (AVIO_FLAG_READ|AVIO_FLAG_WRITE)  /**< read-write pseudo flag */
+/**
+ * @}
+ */
+
+/**
+ * Use non-blocking mode.
+ * If this flag is set, operations on the context will return
+ * AVERROR(EAGAIN) if they can not be performed immediately.
+ * If this flag is not set, operations on the context will never return
+ * AVERROR(EAGAIN).
+ * Note that this flag does not affect the opening/connecting of the
+ * context. Connecting a protocol will always block if necessary (e.g. on
+ * network protocols) but never hang (e.g. on busy devices).
+ * Warning: non-blocking protocols is work-in-progress; this flag may be
+ * silently ignored.
+ */
+#define AVIO_FLAG_NONBLOCK 8
+
+/**
+ * Create and initialize a AVIOContext for accessing the
+ * resource indicated by url.
+ * @note When the resource indicated by url has been opened in
+ * read+write mode, the AVIOContext can be used only for writing.
+ *
+ * @param s Used to return the pointer to the created AVIOContext.
+ * In case of failure the pointed to value is set to NULL.
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int avio_open(AVIOContext **s, const char *url, int flags);
+
+/**
+ * Create and initialize a AVIOContext for accessing the
+ * resource indicated by url.
+ * @note When the resource indicated by url has been opened in
+ * read+write mode, the AVIOContext can be used only for writing.
+ *
+ * @param s Used to return the pointer to the created AVIOContext.
+ * In case of failure the pointed to value is set to NULL.
+ * @param flags flags which control how the resource indicated by url
+ * is to be opened
+ * @param int_cb an interrupt callback to be used at the protocols level
+ * @param options  A dictionary filled with protocol-private options. On return
+ * this parameter will be destroyed and replaced with a dict containing options
+ * that were not found. May be NULL.
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code in case of failure
+ */
+int avio_open2(AVIOContext **s, const char *url, int flags,
+               const AVIOInterruptCB *int_cb, AVDictionary **options);
+
+/**
+ * Close the resource accessed by the AVIOContext s and free it.
+ * This function can only be used if s was opened by avio_open().
+ *
+ * @return 0 on success, an AVERROR < 0 on error.
+ */
+int avio_close(AVIOContext *s);
+
+/**
+ * Open a write only memory stream.
+ *
+ * @param s new IO context
+ * @return zero if no error.
+ */
+int avio_open_dyn_buf(AVIOContext **s);
+
+/**
+ * Return the written size and a pointer to the buffer. The buffer
+ * must be freed with av_free().
+ * Padding of FF_INPUT_BUFFER_PADDING_SIZE is added to the buffer.
+ *
+ * @param s IO context
+ * @param pbuffer pointer to a byte buffer
+ * @return the length of the byte buffer
+ */
+int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer);
+
+/**
+ * Iterate through names of available protocols.
+ *
+ * @param opaque A private pointer representing current protocol.
+ *        It must be a pointer to NULL on first iteration and will
+ *        be updated by successive calls to avio_enum_protocols.
+ * @param output If set to 1, iterate over output protocols,
+ *               otherwise over input protocols.
+ *
+ * @return A static string containing the name of current protocol or NULL
+ */
+const char *avio_enum_protocols(void **opaque, int output);
+
+/**
+ * Pause and resume playing - only meaningful if using a network streaming
+ * protocol (e.g. MMS).
+ * @param pause 1 for pause, 0 for resume
+ */
+int     avio_pause(AVIOContext *h, int pause);
+
+/**
+ * Seek to a given timestamp relative to some component stream.
+ * Only meaningful if using a network streaming protocol (e.g. MMS.).
+ * @param stream_index The stream index that the timestamp is relative to.
+ *        If stream_index is (-1) the timestamp should be in AV_TIME_BASE
+ *        units from the beginning of the presentation.
+ *        If a stream_index >= 0 is used and the protocol does not support
+ *        seeking based on component streams, the call will fail with ENOTSUP.
+ * @param timestamp timestamp in AVStream.time_base units
+ *        or if there is no stream specified then in AV_TIME_BASE units.
+ * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE
+ *        and AVSEEK_FLAG_ANY. The protocol may silently ignore
+ *        AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will
+ *        fail with ENOTSUP if used and not supported.
+ * @return >= 0 on success
+ * @see AVInputFormat::read_seek
+ */
+int64_t avio_seek_time(AVIOContext *h, int stream_index,
+                       int64_t timestamp, int flags);
+
+#endif /* AVFORMAT_AVIO_H */
diff --git a/make/stub_includes/libav/libavformat/version.h b/make/stub_includes/libav/libavformat/version.h
new file mode 100644
index 0000000..009a60b
--- /dev/null
+++ b/make/stub_includes/libav/libavformat/version.h
@@ -0,0 +1,126 @@
+/*
+ * Version macros.
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVFORMAT_VERSION_H
+#define AVFORMAT_VERSION_H
+
+/**
+ * @file
+ * @ingroup libavf
+ * Libavformat version macros
+ */
+
+#include "libavutil/avutil.h"
+
+#define LIBAVFORMAT_VERSION_MAJOR 53
+#define LIBAVFORMAT_VERSION_MINOR 21
+#define LIBAVFORMAT_VERSION_MICRO  0
+
+#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
+                                               LIBAVFORMAT_VERSION_MINOR, \
+                                               LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_VERSION     AV_VERSION(LIBAVFORMAT_VERSION_MAJOR,   \
+                                           LIBAVFORMAT_VERSION_MINOR,   \
+                                           LIBAVFORMAT_VERSION_MICRO)
+#define LIBAVFORMAT_BUILD       LIBAVFORMAT_VERSION_INT
+
+#define LIBAVFORMAT_IDENT       "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION)
+
+/**
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ */
+#ifndef FF_API_OLD_METADATA2
+#define FF_API_OLD_METADATA2           (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_AVIO
+#define FF_API_OLD_AVIO                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_DUMP_FORMAT
+#define FF_API_DUMP_FORMAT             (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PARSE_DATE
+#define FF_API_PARSE_DATE              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FIND_INFO_TAG
+#define FF_API_FIND_INFO_TAG           (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PKT_DUMP
+#define FF_API_PKT_DUMP                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_GUESS_IMG2_CODEC
+#define FF_API_GUESS_IMG2_CODEC        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_SDP_CREATE
+#define FF_API_SDP_CREATE              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FORMAT_PARAMETERS
+#define FF_API_FORMAT_PARAMETERS       (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FLAG_RTP_HINT
+#define FF_API_FLAG_RTP_HINT           (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_AVSTREAM_QUALITY
+#define FF_API_AVSTREAM_QUALITY        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_LOOP_INPUT
+#define FF_API_LOOP_INPUT              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_LOOP_OUTPUT
+#define FF_API_LOOP_OUTPUT             (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_TIMESTAMP
+#define FF_API_TIMESTAMP               (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_FILESIZE
+#define FF_API_FILESIZE                (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_MUXRATE
+#define FF_API_MUXRATE                 (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_RTSP_URL_OPTIONS
+#define FF_API_RTSP_URL_OPTIONS        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_NEW_STREAM
+#define FF_API_NEW_STREAM              (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_PRELOAD
+#define FF_API_PRELOAD                 (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_STREAM_COPY
+#define FF_API_STREAM_COPY             (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_SEEK_PUBLIC
+#define FF_API_SEEK_PUBLIC             (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_REORDER_PRIVATE
+#define FF_API_REORDER_PRIVATE         (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_OLD_INTERRUPT_CB
+#define FF_API_OLD_INTERRUPT_CB        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_SET_PTS_INFO
+#define FF_API_SET_PTS_INFO            (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+#ifndef FF_API_CLOSE_INPUT_FILE
+#define FF_API_CLOSE_INPUT_FILE        (LIBAVFORMAT_VERSION_MAJOR < 54)
+#endif
+
+#endif /* AVFORMAT_VERSION_H */
diff --git a/make/stub_includes/libav/libavutil/adler32.h b/make/stub_includes/libav/libavutil/adler32.h
new file mode 100644
index 0000000..a8ff6f9
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/adler32.h
@@ -0,0 +1,43 @@
+/*
+ * copyright (c) 2006 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_ADLER32_H
+#define AVUTIL_ADLER32_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+/**
+ * @ingroup lavu_crypto
+ * Calculate the Adler32 checksum of a buffer.
+ *
+ * Passing the return value to a subsequent av_adler32_update() call
+ * allows the checksum of multiple buffers to be calculated as though
+ * they were concatenated.
+ *
+ * @param adler initial checksum value
+ * @param buf   pointer to input buffer
+ * @param len   size of input buffer
+ * @return      updated checksum
+ */
+unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf,
+                                unsigned int len) av_pure;
+
+#endif /* AVUTIL_ADLER32_H */
diff --git a/make/stub_includes/libav/libavutil/aes.h b/make/stub_includes/libav/libavutil/aes.h
new file mode 100644
index 0000000..cf7b462
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/aes.h
@@ -0,0 +1,57 @@
+/*
+ * copyright (c) 2007 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AES_H
+#define AVUTIL_AES_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_aes AES
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_aes_size;
+
+struct AVAES;
+
+/**
+ * Initialize an AVAES context.
+ * @param key_bits 128, 192 or 256
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt);
+
+/**
+ * Encrypt or decrypt a buffer using a previously initialized context.
+ * @param count number of 16 byte blocks
+ * @param dst destination array, can be equal to src
+ * @param src source array, can be equal to dst
+ * @param iv initialization vector for CBC mode, if NULL then ECB will be used
+ * @param decrypt 0 for encryption, 1 for decryption
+ */
+void av_aes_crypt(struct AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AES_H */
diff --git a/make/stub_includes/libav/libavutil/attributes.h b/make/stub_includes/libav/libavutil/attributes.h
new file mode 100644
index 0000000..ef990a1
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/attributes.h
@@ -0,0 +1,136 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Macro definitions for various function/variable attributes
+ */
+
+#ifndef AVUTIL_ATTRIBUTES_H
+#define AVUTIL_ATTRIBUTES_H
+
+#ifdef __GNUC__
+#    define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y)
+#else
+#    define AV_GCC_VERSION_AT_LEAST(x,y) 0
+#endif
+
+#ifndef av_always_inline
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_always_inline __attribute__((always_inline)) inline
+#else
+#    define av_always_inline inline
+#endif
+#endif
+
+#ifndef av_noinline
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_noinline __attribute__((noinline))
+#else
+#    define av_noinline
+#endif
+#endif
+
+#ifndef av_pure
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_pure __attribute__((pure))
+#else
+#    define av_pure
+#endif
+#endif
+
+#ifndef av_const
+#if AV_GCC_VERSION_AT_LEAST(2,6)
+#    define av_const __attribute__((const))
+#else
+#    define av_const
+#endif
+#endif
+
+#ifndef av_cold
+#if AV_GCC_VERSION_AT_LEAST(4,3)
+#    define av_cold __attribute__((cold))
+#else
+#    define av_cold
+#endif
+#endif
+
+#ifndef av_flatten
+#if AV_GCC_VERSION_AT_LEAST(4,1)
+#    define av_flatten __attribute__((flatten))
+#else
+#    define av_flatten
+#endif
+#endif
+
+#ifndef attribute_deprecated
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define attribute_deprecated __attribute__((deprecated))
+#else
+#    define attribute_deprecated
+#endif
+#endif
+
+#ifndef av_unused
+#if defined(__GNUC__)
+#    define av_unused __attribute__((unused))
+#else
+#    define av_unused
+#endif
+#endif
+
+/**
+ * Mark a variable as used and prevent the compiler from optimizing it
+ * away.  This is useful for variables accessed only from inline
+ * assembler without the compiler being aware.
+ */
+#ifndef av_used
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+#    define av_used __attribute__((used))
+#else
+#    define av_used
+#endif
+#endif
+
+#ifndef av_alias
+#if AV_GCC_VERSION_AT_LEAST(3,3)
+#   define av_alias __attribute__((may_alias))
+#else
+#   define av_alias
+#endif
+#endif
+
+#ifndef av_uninit
+#if defined(__GNUC__) && !defined(__ICC)
+#    define av_uninit(x) x=x
+#else
+#    define av_uninit(x) x
+#endif
+#endif
+
+#ifdef __GNUC__
+#    define av_builtin_constant_p __builtin_constant_p
+#    define av_printf_format(fmtpos, attrpos) __attribute__((__format__(__printf__, fmtpos, attrpos)))
+#else
+#    define av_builtin_constant_p(x) 0
+#    define av_printf_format(fmtpos, attrpos)
+#endif
+
+#endif /* AVUTIL_ATTRIBUTES_H */
diff --git a/make/stub_includes/libav/libavutil/audioconvert.h b/make/stub_includes/libav/libavutil/audioconvert.h
new file mode 100644
index 0000000..00ed0ff
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/audioconvert.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ * Copyright (c) 2008 Peter Ross
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AUDIOCONVERT_H
+#define AVUTIL_AUDIOCONVERT_H
+
+#include <stdint.h>
+
+/**
+ * @file
+ * audio conversion routines
+ */
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ */
+
+/**
+ * @defgroup channel_masks Audio channel masks
+ * @{
+ */
+#define AV_CH_FRONT_LEFT             0x00000001
+#define AV_CH_FRONT_RIGHT            0x00000002
+#define AV_CH_FRONT_CENTER           0x00000004
+#define AV_CH_LOW_FREQUENCY          0x00000008
+#define AV_CH_BACK_LEFT              0x00000010
+#define AV_CH_BACK_RIGHT             0x00000020
+#define AV_CH_FRONT_LEFT_OF_CENTER   0x00000040
+#define AV_CH_FRONT_RIGHT_OF_CENTER  0x00000080
+#define AV_CH_BACK_CENTER            0x00000100
+#define AV_CH_SIDE_LEFT              0x00000200
+#define AV_CH_SIDE_RIGHT             0x00000400
+#define AV_CH_TOP_CENTER             0x00000800
+#define AV_CH_TOP_FRONT_LEFT         0x00001000
+#define AV_CH_TOP_FRONT_CENTER       0x00002000
+#define AV_CH_TOP_FRONT_RIGHT        0x00004000
+#define AV_CH_TOP_BACK_LEFT          0x00008000
+#define AV_CH_TOP_BACK_CENTER        0x00010000
+#define AV_CH_TOP_BACK_RIGHT         0x00020000
+#define AV_CH_STEREO_LEFT            0x20000000  ///< Stereo downmix.
+#define AV_CH_STEREO_RIGHT           0x40000000  ///< See AV_CH_STEREO_LEFT.
+#define AV_CH_WIDE_LEFT              0x0000000080000000ULL
+#define AV_CH_WIDE_RIGHT             0x0000000100000000ULL
+#define AV_CH_SURROUND_DIRECT_LEFT   0x0000000200000000ULL
+#define AV_CH_SURROUND_DIRECT_RIGHT  0x0000000400000000ULL
+
+/** Channel mask value used for AVCodecContext.request_channel_layout
+    to indicate that the user requests the channel order of the decoder output
+    to be the native codec channel order. */
+#define AV_CH_LAYOUT_NATIVE          0x8000000000000000ULL
+
+/**
+ * @}
+ * @defgroup channel_mask_c Audio channel convenience macros
+ * @{
+ * */
+#define AV_CH_LAYOUT_MONO              (AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_STEREO            (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT)
+#define AV_CH_LAYOUT_2POINT1           (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_1               (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_SURROUND          (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_3POINT1           (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_4POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_4POINT1           (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_2               (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_QUAD              (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT0           (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_5POINT1           (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_5POINT0_BACK      (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT1_BACK      (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_6POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT0_FRONT     (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_HEXAGONAL         (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_BACK      (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_FRONT     (AV_CH_LAYOUT_6POINT0_FRONT|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_7POINT0           (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT0_FRONT     (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1           (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT1_WIDE      (AV_CH_LAYOUT_5POINT1|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_OCTAGONAL         (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_STEREO_DOWNMIX    (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
+
+/**
+ * @}
+ */
+
+/**
+ * Return a channel layout id that matches name, 0 if no match.
+ */
+uint64_t av_get_channel_layout(const char *name);
+
+/**
+ * Return a description of a channel layout.
+ * If nb_channels is <= 0, it is guessed from the channel_layout.
+ *
+ * @param buf put here the string containing the channel layout
+ * @param buf_size size in bytes of the buffer
+ */
+void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout);
+
+/**
+ * Return the number of channels in the channel layout.
+ */
+int av_get_channel_layout_nb_channels(uint64_t channel_layout);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AUDIOCONVERT_H */
diff --git a/make/stub_includes/libav/libavutil/avassert.h b/make/stub_includes/libav/libavutil/avassert.h
new file mode 100644
index 0000000..b223d26
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/avassert.h
@@ -0,0 +1,66 @@
+/*
+ * copyright (c) 2010 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple assert() macros that are a bit more flexible than ISO C assert().
+ * @author Michael Niedermayer <michaelni at gmx.at>
+ */
+
+#ifndef AVUTIL_AVASSERT_H
+#define AVUTIL_AVASSERT_H
+
+#include <stdlib.h>
+#include "avutil.h"
+#include "log.h"
+
+/**
+ * assert() equivalent, that is always enabled.
+ */
+#define av_assert0(cond) do {                                           \
+    if (!(cond)) {                                                      \
+        av_log(NULL, AV_LOG_FATAL, "Assertion %s failed at %s:%d\n",    \
+               AV_STRINGIFY(cond), __FILE__, __LINE__);                 \
+        abort();                                                        \
+    }                                                                   \
+} while (0)
+
+
+/**
+ * assert() equivalent, that does not lie in speed critical code.
+ * These asserts() thus can be enabled without fearing speedloss.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0
+#define av_assert1(cond) av_assert0(cond)
+#else
+#define av_assert1(cond) ((void)0)
+#endif
+
+
+/**
+ * assert() equivalent, that does lie in speed critical code.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 1
+#define av_assert2(cond) av_assert0(cond)
+#else
+#define av_assert2(cond) ((void)0)
+#endif
+
+#endif /* AVUTIL_AVASSERT_H */
diff --git a/make/stub_includes/libav/libavutil/avconfig.h b/make/stub_includes/libav/libavutil/avconfig.h
new file mode 100644
index 0000000..f10aa61
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/avconfig.h
@@ -0,0 +1,6 @@
+/* Generated by ffconf */
+#ifndef AVUTIL_AVCONFIG_H
+#define AVUTIL_AVCONFIG_H
+#define AV_HAVE_BIGENDIAN 0
+#define AV_HAVE_FAST_UNALIGNED 1
+#endif /* AVUTIL_AVCONFIG_H */
diff --git a/make/stub_includes/libav/libavutil/avstring.h b/make/stub_includes/libav/libavutil/avstring.h
new file mode 100644
index 0000000..ed4e465
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/avstring.h
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2007 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AVSTRING_H
+#define AVUTIL_AVSTRING_H
+
+#include <stddef.h>
+#include "attributes.h"
+
+/**
+ * @addtogroup lavu_string
+ * @{
+ */
+
+/**
+ * Return non-zero if pfx is a prefix of str. If it is, *ptr is set to
+ * the address of the first character in str after the prefix.
+ *
+ * @param str input string
+ * @param pfx prefix to test
+ * @param ptr updated if the prefix is matched inside str
+ * @return non-zero if the prefix matches, zero otherwise
+ */
+int av_strstart(const char *str, const char *pfx, const char **ptr);
+
+/**
+ * Return non-zero if pfx is a prefix of str independent of case. If
+ * it is, *ptr is set to the address of the first character in str
+ * after the prefix.
+ *
+ * @param str input string
+ * @param pfx prefix to test
+ * @param ptr updated if the prefix is matched inside str
+ * @return non-zero if the prefix matches, zero otherwise
+ */
+int av_stristart(const char *str, const char *pfx, const char **ptr);
+
+/**
+ * Locate the first case-independent occurrence in the string haystack
+ * of the string needle.  A zero-length string needle is considered to
+ * match at the start of haystack.
+ *
+ * This function is a case-insensitive version of the standard strstr().
+ *
+ * @param haystack string to search in
+ * @param needle   string to search for
+ * @return         pointer to the located match within haystack
+ *                 or a null pointer if no match
+ */
+char *av_stristr(const char *haystack, const char *needle);
+
+/**
+ * Copy the string src to dst, but no more than size - 1 bytes, and
+ * null-terminate dst.
+ *
+ * This function is the same as BSD strlcpy().
+ *
+ * @param dst destination buffer
+ * @param src source string
+ * @param size size of destination buffer
+ * @return the length of src
+ *
+ * @warning since the return value is the length of src, src absolutely
+ * _must_ be a properly 0-terminated string, otherwise this will read beyond
+ * the end of the buffer and possibly crash.
+ */
+size_t av_strlcpy(char *dst, const char *src, size_t size);
+
+/**
+ * Append the string src to the string dst, but to a total length of
+ * no more than size - 1 bytes, and null-terminate dst.
+ *
+ * This function is similar to BSD strlcat(), but differs when
+ * size <= strlen(dst).
+ *
+ * @param dst destination buffer
+ * @param src source string
+ * @param size size of destination buffer
+ * @return the total length of src and dst
+ *
+ * @warning since the return value use the length of src and dst, these
+ * absolutely _must_ be a properly 0-terminated strings, otherwise this
+ * will read beyond the end of the buffer and possibly crash.
+ */
+size_t av_strlcat(char *dst, const char *src, size_t size);
+
+/**
+ * Append output to a string, according to a format. Never write out of
+ * the destination buffer, and always put a terminating 0 within
+ * the buffer.
+ * @param dst destination buffer (string to which the output is
+ *  appended)
+ * @param size total size of the destination buffer
+ * @param fmt printf-compatible format string, specifying how the
+ *  following parameters are used
+ * @return the length of the string that would have been generated
+ *  if enough space had been available
+ */
+size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) av_printf_format(3, 4);
+
+/**
+ * Convert a number to a av_malloced string.
+ */
+char *av_d2str(double d);
+
+/**
+ * Unescape the given string until a non escaped terminating char,
+ * and return the token corresponding to the unescaped string.
+ *
+ * The normal \ and ' escaping is supported. Leading and trailing
+ * whitespaces are removed, unless they are escaped with '\' or are
+ * enclosed between ''.
+ *
+ * @param buf the buffer to parse, buf will be updated to point to the
+ * terminating char
+ * @param term a 0-terminated list of terminating chars
+ * @return the malloced unescaped string, which must be av_freed by
+ * the user, NULL in case of allocation failure
+ */
+char *av_get_token(const char **buf, const char *term);
+
+/**
+ * Locale-independent conversion of ASCII characters to uppercase.
+ */
+static inline int av_toupper(int c)
+{
+    if (c >= 'a' && c <= 'z')
+        c ^= 0x20;
+    return c;
+}
+
+/**
+ * Locale-independent conversion of ASCII characters to lowercase.
+ */
+static inline int av_tolower(int c)
+{
+    if (c >= 'A' && c <= 'Z')
+        c ^= 0x20;
+    return c;
+}
+
+/*
+ * Locale-independent case-insensitive compare.
+ * @note This means only ASCII-range characters are case-insensitive
+ */
+int av_strcasecmp(const char *a, const char *b);
+
+/**
+ * Locale-independent case-insensitive compare.
+ * @note This means only ASCII-range characters are case-insensitive
+ */
+int av_strncasecmp(const char *a, const char *b, size_t n);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_AVSTRING_H */
diff --git a/make/stub_includes/libav/libavutil/avutil.h b/make/stub_includes/libav/libavutil/avutil.h
new file mode 100644
index 0000000..05e9248
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/avutil.h
@@ -0,0 +1,326 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AVUTIL_H
+#define AVUTIL_AVUTIL_H
+
+/**
+ * @file
+ * external API header
+ */
+
+/**
+ * @mainpage
+ *
+ * @section libav_intro Introduction
+ *
+ * This document describe the usage of the different libraries
+ * provided by Libav.
+ *
+ * @li @ref libavc "libavcodec" encoding/decoding library
+ * @li @subpage libavfilter graph based frame editing library
+ * @li @ref libavf "libavformat" I/O and muxing/demuxing library
+ * @li @ref lavd "libavdevice" special devices muxing/demuxing library
+ * @li @ref lavu "libavutil" common utility library
+ * @li @subpage libpostproc post processing library
+ * @li @subpage libswscale  color conversion and scaling library
+ *
+ */
+
+/**
+ * @defgroup lavu Common utility functions
+ *
+ * @brief
+ * libavutil contains the code shared across all the other Libav
+ * libraries
+ *
+ * @note In order to use the functions provided by avutil you must include
+ * the specific header.
+ *
+ * @{
+ *
+ * @defgroup lavu_crypto Crypto and Hashing
+ *
+ * @{
+ * @}
+ *
+ * @defgroup lavu_math Maths
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_string String Manipulation
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_mem Memory Management
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_data Data Structures
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_audio Audio related
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_error Error Codes
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_misc Other
+ *
+ * @{
+ *
+ * @defgroup lavu_internal Internal
+ *
+ * Not exported functions, for internal usage only
+ *
+ * @{
+ *
+ * @}
+ */
+
+
+/**
+ * @defgroup preproc_misc Preprocessor String Macros
+ *
+ * String manipulation macros
+ *
+ * @{
+ */
+
+#define AV_STRINGIFY(s)         AV_TOSTRING(s)
+#define AV_TOSTRING(s) #s
+
+#define AV_GLUE(a, b) a ## b
+#define AV_JOIN(a, b) AV_GLUE(a, b)
+
+#define AV_PRAGMA(s) _Pragma(#s)
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup version_utils Library Version Macros
+ *
+ * Useful to check and match library version in order to maintain
+ * backward compatibility.
+ *
+ * @{
+ */
+
+#define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
+#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
+#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
+
+/**
+ * @}
+ *
+ * @defgroup lavu_ver Version and Build diagnostics
+ *
+ * Macros and function useful to check at compiletime and at runtime
+ * which version of libavutil is in use.
+ *
+ * @{
+ */
+
+#define LIBAVUTIL_VERSION_MAJOR 51
+#define LIBAVUTIL_VERSION_MINOR 22
+#define LIBAVUTIL_VERSION_MICRO  1
+
+#define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
+                                               LIBAVUTIL_VERSION_MINOR, \
+                                               LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_VERSION       AV_VERSION(LIBAVUTIL_VERSION_MAJOR,     \
+                                           LIBAVUTIL_VERSION_MINOR,     \
+                                           LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_BUILD         LIBAVUTIL_VERSION_INT
+
+#define LIBAVUTIL_IDENT         "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION)
+
+/**
+ * @}
+ *
+ * @defgroup depr_guards Deprecation guards
+ * Those FF_API_* defines are not part of public API.
+ * They may change, break or disappear at any time.
+ *
+ * They are used mostly internally to mark code that will be removed
+ * on the next major version.
+ *
+ * @{
+ */
+#ifndef FF_API_GET_BITS_PER_SAMPLE_FMT
+#define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 52)
+#endif
+#ifndef FF_API_FIND_OPT
+#define FF_API_FIND_OPT                 (LIBAVUTIL_VERSION_MAJOR < 52)
+#endif
+#ifndef FF_API_AV_FIFO_PEEK
+#define FF_API_AV_FIFO_PEEK             (LIBAVUTIL_VERSION_MAJOR < 52)
+#endif
+#ifndef FF_API_OLD_AVOPTIONS
+#define FF_API_OLD_AVOPTIONS            (LIBAVUTIL_VERSION_MAJOR < 52)
+#endif
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavu_ver
+ * @{
+ */
+
+/**
+ * Return the LIBAVUTIL_VERSION_INT constant.
+ */
+unsigned avutil_version(void);
+
+/**
+ * Return the libavutil build-time configuration.
+ */
+const char *avutil_configuration(void);
+
+/**
+ * Return the libavutil license.
+ */
+const char *avutil_license(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavu_media Media Type
+ * @brief Media Type
+ */
+
+enum AVMediaType {
+    AVMEDIA_TYPE_UNKNOWN = -1,  ///< Usually treated as AVMEDIA_TYPE_DATA
+    AVMEDIA_TYPE_VIDEO,
+    AVMEDIA_TYPE_AUDIO,
+    AVMEDIA_TYPE_DATA,          ///< Opaque data information usually continuous
+    AVMEDIA_TYPE_SUBTITLE,
+    AVMEDIA_TYPE_ATTACHMENT,    ///< Opaque data information usually sparse
+    AVMEDIA_TYPE_NB
+};
+
+/**
+ * @defgroup lavu_const Constants
+ * @{
+ *
+ * @defgroup lavu_enc Encoding specific
+ *
+ * @note those definition should move to avcodec
+ * @{
+ */
+
+#define FF_LAMBDA_SHIFT 7
+#define FF_LAMBDA_SCALE (1<<FF_LAMBDA_SHIFT)
+#define FF_QP2LAMBDA 118 ///< factor to convert from H.263 QP to lambda
+#define FF_LAMBDA_MAX (256*128-1)
+
+#define FF_QUALITY_SCALE FF_LAMBDA_SCALE //FIXME maybe remove
+
+/**
+ * @}
+ * @defgroup lavu_time Timestamp specific
+ *
+ * Libav internal timebase and timestamp definitions
+ *
+ * @{
+ */
+
+/**
+ * @brief Undefined timestamp value
+ *
+ * Usually reported by demuxer that work on containers that do not provide
+ * either pts or dts.
+ */
+
+#define AV_NOPTS_VALUE          INT64_C(0x8000000000000000)
+
+/**
+ * Internal time base represented as integer
+ */
+
+#define AV_TIME_BASE            1000000
+
+/**
+ * Internal time base represented as fractional value
+ */
+
+#define AV_TIME_BASE_Q          (AVRational){1, AV_TIME_BASE}
+
+/**
+ * @}
+ * @}
+ * @defgroup lavu_picture Image related
+ *
+ * AVPicture types, pixel formats and basic image planes manipulation.
+ *
+ * @{
+ */
+
+enum AVPictureType {
+    AV_PICTURE_TYPE_I = 1, ///< Intra
+    AV_PICTURE_TYPE_P,     ///< Predicted
+    AV_PICTURE_TYPE_B,     ///< Bi-dir predicted
+    AV_PICTURE_TYPE_S,     ///< S(GMC)-VOP MPEG4
+    AV_PICTURE_TYPE_SI,    ///< Switching Intra
+    AV_PICTURE_TYPE_SP,    ///< Switching Predicted
+    AV_PICTURE_TYPE_BI,    ///< BI type
+};
+
+/**
+ * Return a single letter to describe the given picture type
+ * pict_type.
+ *
+ * @param[in] pict_type the picture type @return a single character
+ * representing the picture type, '?' if pict_type is unknown
+ */
+char av_get_picture_type_char(enum AVPictureType pict_type);
+
+/**
+ * @}
+ */
+
+#include "common.h"
+#include "error.h"
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_AVUTIL_H */
diff --git a/make/stub_includes/libav/libavutil/base64.h b/make/stub_includes/libav/libavutil/base64.h
new file mode 100644
index 0000000..4750cf5
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/base64.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2006 Ryan Martell. (rdm4 at martellventures.com)
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_BASE64_H
+#define AVUTIL_BASE64_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_base64 Base64
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+
+/**
+ * Decode a base64-encoded string.
+ *
+ * @param out      buffer for decoded data
+ * @param in       null-terminated input string
+ * @param out_size size in bytes of the out buffer, must be at
+ *                 least 3/4 of the length of in
+ * @return         number of bytes written, or a negative value in case of
+ *                 invalid input
+ */
+int av_base64_decode(uint8_t *out, const char *in, int out_size);
+
+/**
+ * Encode data to base64 and null-terminate.
+ *
+ * @param out      buffer for encoded data
+ * @param out_size size in bytes of the output buffer, must be at
+ *                 least AV_BASE64_SIZE(in_size)
+ * @param in_size  size in bytes of the 'in' buffer
+ * @return         'out' or NULL in case of error
+ */
+char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size);
+
+/**
+ * Calculate the output size needed to base64-encode x bytes.
+ */
+#define AV_BASE64_SIZE(x)  (((x)+2) / 3 * 4 + 1)
+
+ /**
+  * @}
+  */
+
+#endif /* AVUTIL_BASE64_H */
diff --git a/make/stub_includes/libav/libavutil/bswap.h b/make/stub_includes/libav/libavutil/bswap.h
new file mode 100644
index 0000000..8a350e1
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/bswap.h
@@ -0,0 +1,109 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * byte swapping routines
+ */
+
+#ifndef AVUTIL_BSWAP_H
+#define AVUTIL_BSWAP_H
+
+#include <stdint.h>
+#include "libavutil/avconfig.h"
+#include "attributes.h"
+
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
+#if   ARCH_ARM
+#   include "arm/bswap.h"
+#elif ARCH_AVR32
+#   include "avr32/bswap.h"
+#elif ARCH_BFIN
+#   include "bfin/bswap.h"
+#elif ARCH_SH4
+#   include "sh4/bswap.h"
+#elif ARCH_X86
+#   include "x86/bswap.h"
+#endif
+
+#endif /* HAVE_AV_CONFIG_H */
+
+#define AV_BSWAP16C(x) (((x) << 8 & 0xff00)  | ((x) >> 8 & 0x00ff))
+#define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16))
+#define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32))
+
+#define AV_BSWAPC(s, x) AV_BSWAP##s##C(x)
+
+#ifndef av_bswap16
+static av_always_inline av_const uint16_t av_bswap16(uint16_t x)
+{
+    x= (x>>8) | (x<<8);
+    return x;
+}
+#endif
+
+#ifndef av_bswap32
+static av_always_inline av_const uint32_t av_bswap32(uint32_t x)
+{
+    return AV_BSWAP32C(x);
+}
+#endif
+
+#ifndef av_bswap64
+static inline uint64_t av_const av_bswap64(uint64_t x)
+{
+    return (uint64_t)av_bswap32(x) << 32 | av_bswap32(x >> 32);
+}
+#endif
+
+// be2ne ... big-endian to native-endian
+// le2ne ... little-endian to native-endian
+
+#if AV_HAVE_BIGENDIAN
+#define av_be2ne16(x) (x)
+#define av_be2ne32(x) (x)
+#define av_be2ne64(x) (x)
+#define av_le2ne16(x) av_bswap16(x)
+#define av_le2ne32(x) av_bswap32(x)
+#define av_le2ne64(x) av_bswap64(x)
+#define AV_BE2NEC(s, x) (x)
+#define AV_LE2NEC(s, x) AV_BSWAPC(s, x)
+#else
+#define av_be2ne16(x) av_bswap16(x)
+#define av_be2ne32(x) av_bswap32(x)
+#define av_be2ne64(x) av_bswap64(x)
+#define av_le2ne16(x) (x)
+#define av_le2ne32(x) (x)
+#define av_le2ne64(x) (x)
+#define AV_BE2NEC(s, x) AV_BSWAPC(s, x)
+#define AV_LE2NEC(s, x) (x)
+#endif
+
+#define AV_BE2NE16C(x) AV_BE2NEC(16, x)
+#define AV_BE2NE32C(x) AV_BE2NEC(32, x)
+#define AV_BE2NE64C(x) AV_BE2NEC(64, x)
+#define AV_LE2NE16C(x) AV_LE2NEC(16, x)
+#define AV_LE2NE32C(x) AV_LE2NEC(32, x)
+#define AV_LE2NE64C(x) AV_LE2NEC(64, x)
+
+#endif /* AVUTIL_BSWAP_H */
diff --git a/make/stub_includes/libav/libavutil/common.h b/make/stub_includes/libav/libavutil/common.h
new file mode 100644
index 0000000..c99d858
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/common.h
@@ -0,0 +1,398 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * common internal and external API header
+ */
+
+#ifndef AVUTIL_COMMON_H
+#define AVUTIL_COMMON_H
+
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "attributes.h"
+#include "libavutil/avconfig.h"
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_NE(be, le) (be)
+#else
+#   define AV_NE(be, le) (le)
+#endif
+
+//rounded division & shift
+#define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b))
+/* assume b>0 */
+#define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b))
+#define FFABS(a) ((a) >= 0 ? (a) : (-(a)))
+#define FFSIGN(a) ((a) > 0 ? 1 : -1)
+
+#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
+#define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c)
+#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
+#define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c)
+
+#define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0)
+#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
+#define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1))
+
+/* misc math functions */
+extern const uint8_t ff_log2_tab[256];
+
+extern const uint8_t av_reverse[256];
+
+static av_always_inline av_const int av_log2_c(unsigned int v)
+{
+    int n = 0;
+    if (v & 0xffff0000) {
+        v >>= 16;
+        n += 16;
+    }
+    if (v & 0xff00) {
+        v >>= 8;
+        n += 8;
+    }
+    n += ff_log2_tab[v];
+
+    return n;
+}
+
+static av_always_inline av_const int av_log2_16bit_c(unsigned int v)
+{
+    int n = 0;
+    if (v & 0xff00) {
+        v >>= 8;
+        n += 8;
+    }
+    n += ff_log2_tab[v];
+
+    return n;
+}
+
+#ifdef HAVE_AV_CONFIG_H
+#   include "config.h"
+#   include "intmath.h"
+#endif
+
+/* Pull in unguarded fallback defines at the end of this file. */
+#include "common.h"
+
+/**
+ * Clip a signed integer value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const int av_clip_c(int a, int amin, int amax)
+{
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-255 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint8_t av_clip_uint8_c(int a)
+{
+    if (a&(~0xFF)) return (-a)>>31;
+    else           return a;
+}
+
+/**
+ * Clip a signed integer value into the -128,127 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int8_t av_clip_int8_c(int a)
+{
+    if ((a+0x80) & ~0xFF) return (a>>31) ^ 0x7F;
+    else                  return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-65535 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint16_t av_clip_uint16_c(int a)
+{
+    if (a&(~0xFFFF)) return (-a)>>31;
+    else             return a;
+}
+
+/**
+ * Clip a signed integer value into the -32768,32767 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int16_t av_clip_int16_c(int a)
+{
+    if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
+    else                      return a;
+}
+
+/**
+ * Clip a signed 64-bit integer value into the -2147483648,2147483647 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a)
+{
+    if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (a>>63) ^ 0x7FFFFFFF;
+    else                                         return a;
+}
+
+/**
+ * Clip a signed integer to an unsigned power of two range.
+ * @param  a value to clip
+ * @param  p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p)
+{
+    if (a & ~((1<<p) - 1)) return -a >> 31 & ((1<<p) - 1);
+    else                   return  a;
+}
+
+/**
+ * Clip a float value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const float av_clipf_c(float a, float amin, float amax)
+{
+    if      (a < amin) return amin;
+    else if (a > amax) return amax;
+    else               return a;
+}
+
+/** Compute ceil(log2(x)).
+ * @param x value used to compute ceil(log2(x))
+ * @return computed ceiling of log2(x)
+ */
+static av_always_inline av_const int av_ceil_log2_c(int x)
+{
+    return av_log2((x - 1) << 1);
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount_c(uint32_t x)
+{
+    x -= (x >> 1) & 0x55555555;
+    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+    x = (x + (x >> 4)) & 0x0F0F0F0F;
+    x += x >> 8;
+    return (x + (x >> 16)) & 0x3F;
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount64_c(uint64_t x)
+{
+    return av_popcount(x) + av_popcount(x >> 32);
+}
+
+#define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24))
+#define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24))
+
+/**
+ * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val      Output value, must be an lvalue of type uint32_t.
+ * @param GET_BYTE Expression reading one byte from the input.
+ *                 Evaluated up to 7 times (4 for the currently
+ *                 assigned Unicode range).  With a memory buffer
+ *                 input, this could be *ptr++.
+ * @param ERROR    Expression to be evaluated on invalid input,
+ *                 typically a goto statement.
+ */
+#define GET_UTF8(val, GET_BYTE, ERROR)\
+    val= GET_BYTE;\
+    {\
+        int ones= 7 - av_log2(val ^ 255);\
+        if(ones==1)\
+            ERROR\
+        val&= 127>>ones;\
+        while(--ones > 0){\
+            int tmp= GET_BYTE - 128;\
+            if(tmp>>6)\
+                ERROR\
+            val= (val<<6) + tmp;\
+        }\
+    }
+
+/**
+ * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val       Output value, must be an lvalue of type uint32_t.
+ * @param GET_16BIT Expression returning two bytes of UTF-16 data converted
+ *                  to native byte order.  Evaluated one or two times.
+ * @param ERROR     Expression to be evaluated on invalid input,
+ *                  typically a goto statement.
+ */
+#define GET_UTF16(val, GET_16BIT, ERROR)\
+    val = GET_16BIT;\
+    {\
+        unsigned int hi = val - 0xD800;\
+        if (hi < 0x800) {\
+            val = GET_16BIT - 0xDC00;\
+            if (val > 0x3FFU || hi > 0x3FFU)\
+                ERROR\
+            val += (hi<<10) + 0x10000;\
+        }\
+    }\
+
+/**
+ * @def PUT_UTF8(val, tmp, PUT_BYTE)
+ * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint8_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_BYTE.
+ * @param PUT_BYTE writes the converted UTF-8 bytes to any proper destination.
+ * It could be a function or a statement, and uses tmp as the input byte.
+ * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be
+ * executed up to 4 times for values in the valid UTF-8 range and up to
+ * 7 times in the general case, depending on the length of the converted
+ * Unicode character.
+ */
+#define PUT_UTF8(val, tmp, PUT_BYTE)\
+    {\
+        int bytes, shift;\
+        uint32_t in = val;\
+        if (in < 0x80) {\
+            tmp = in;\
+            PUT_BYTE\
+        } else {\
+            bytes = (av_log2(in) + 4) / 5;\
+            shift = (bytes - 1) * 6;\
+            tmp = (256 - (256 >> bytes)) | (in >> shift);\
+            PUT_BYTE\
+            while (shift >= 6) {\
+                shift -= 6;\
+                tmp = 0x80 | ((in >> shift) & 0x3f);\
+                PUT_BYTE\
+            }\
+        }\
+    }
+
+/**
+ * @def PUT_UTF16(val, tmp, PUT_16BIT)
+ * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint16_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_16BIT.
+ * @param PUT_16BIT writes the converted UTF-16 data to any proper destination
+ * in desired endianness. It could be a function or a statement, and uses tmp
+ * as the input byte.  For example, PUT_BYTE could be "*output++ = tmp;"
+ * PUT_BYTE will be executed 1 or 2 times depending on input character.
+ */
+#define PUT_UTF16(val, tmp, PUT_16BIT)\
+    {\
+        uint32_t in = val;\
+        if (in < 0x10000) {\
+            tmp = in;\
+            PUT_16BIT\
+        } else {\
+            tmp = 0xD800 | ((in - 0x10000) >> 10);\
+            PUT_16BIT\
+            tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\
+            PUT_16BIT\
+        }\
+    }\
+
+
+
+#include "mem.h"
+
+#ifdef HAVE_AV_CONFIG_H
+#    include "internal.h"
+#endif /* HAVE_AV_CONFIG_H */
+
+#endif /* AVUTIL_COMMON_H */
+
+/*
+ * The following definitions are outside the multiple inclusion guard
+ * to ensure they are immediately available in intmath.h.
+ */
+
+#ifndef av_log2
+#   define av_log2       av_log2_c
+#endif
+#ifndef av_log2_16bit
+#   define av_log2_16bit av_log2_16bit_c
+#endif
+#ifndef av_ceil_log2
+#   define av_ceil_log2     av_ceil_log2_c
+#endif
+#ifndef av_clip
+#   define av_clip          av_clip_c
+#endif
+#ifndef av_clip_uint8
+#   define av_clip_uint8    av_clip_uint8_c
+#endif
+#ifndef av_clip_int8
+#   define av_clip_int8     av_clip_int8_c
+#endif
+#ifndef av_clip_uint16
+#   define av_clip_uint16   av_clip_uint16_c
+#endif
+#ifndef av_clip_int16
+#   define av_clip_int16    av_clip_int16_c
+#endif
+#ifndef av_clipl_int32
+#   define av_clipl_int32   av_clipl_int32_c
+#endif
+#ifndef av_clip_uintp2
+#   define av_clip_uintp2   av_clip_uintp2_c
+#endif
+#ifndef av_clipf
+#   define av_clipf         av_clipf_c
+#endif
+#ifndef av_popcount
+#   define av_popcount      av_popcount_c
+#endif
+#ifndef av_popcount64
+#   define av_popcount64    av_popcount64_c
+#endif
diff --git a/make/stub_includes/libav/libavutil/cpu.h b/make/stub_includes/libav/libavutil/cpu.h
new file mode 100644
index 0000000..df7bf44
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/cpu.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CPU_H
+#define AVUTIL_CPU_H
+
+#define AV_CPU_FLAG_FORCE    0x80000000 /* force usage of selected flags (OR) */
+
+    /* lower 16 bits - CPU features */
+#define AV_CPU_FLAG_MMX          0x0001 ///< standard MMX
+#define AV_CPU_FLAG_MMX2         0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_3DNOW        0x0004 ///< AMD 3DNOW
+#define AV_CPU_FLAG_SSE          0x0008 ///< SSE functions
+#define AV_CPU_FLAG_SSE2         0x0010 ///< PIV SSE2 functions
+#define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster
+#define AV_CPU_FLAG_3DNOWEXT     0x0020 ///< AMD 3DNowExt
+#define AV_CPU_FLAG_SSE3         0x0040 ///< Prescott SSE3 functions
+#define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster
+#define AV_CPU_FLAG_SSSE3        0x0080 ///< Conroe SSSE3 functions
+#define AV_CPU_FLAG_ATOM     0x10000000 ///< Atom processor, some SSSE3 instructions are slower
+#define AV_CPU_FLAG_SSE4         0x0100 ///< Penryn SSE4.1 functions
+#define AV_CPU_FLAG_SSE42        0x0200 ///< Nehalem SSE4.2 functions
+#define AV_CPU_FLAG_AVX          0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used
+#define AV_CPU_FLAG_XOP          0x0400 ///< Bulldozer XOP functions
+#define AV_CPU_FLAG_FMA4         0x0800 ///< Bulldozer FMA4 functions
+#define AV_CPU_FLAG_IWMMXT       0x0100 ///< XScale IWMMXT
+#define AV_CPU_FLAG_ALTIVEC      0x0001 ///< standard
+
+/**
+ * Return the flags which specify extensions supported by the CPU.
+ */
+int av_get_cpu_flags(void);
+
+/* The following CPU-specific functions shall not be called directly. */
+int ff_get_cpu_flags_arm(void);
+int ff_get_cpu_flags_ppc(void);
+int ff_get_cpu_flags_x86(void);
+
+#endif /* AVUTIL_CPU_H */
diff --git a/make/stub_includes/libav/libavutil/crc.h b/make/stub_includes/libav/libavutil/crc.h
new file mode 100644
index 0000000..a934119
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/crc.h
@@ -0,0 +1,44 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CRC_H
+#define AVUTIL_CRC_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include "attributes.h"
+
+typedef uint32_t AVCRC;
+
+typedef enum {
+    AV_CRC_8_ATM,
+    AV_CRC_16_ANSI,
+    AV_CRC_16_CCITT,
+    AV_CRC_32_IEEE,
+    AV_CRC_32_IEEE_LE,  /*< reversed bitorder version of AV_CRC_32_IEEE */
+    AV_CRC_MAX,         /*< Not part of public API! Do not use outside libavutil. */
+}AVCRCId;
+
+int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size);
+const AVCRC *av_crc_get_table(AVCRCId crc_id);
+uint32_t av_crc(const AVCRC *ctx, uint32_t start_crc, const uint8_t *buffer, size_t length) av_pure;
+
+#endif /* AVUTIL_CRC_H */
+
diff --git a/make/stub_includes/libav/libavutil/dict.h b/make/stub_includes/libav/libavutil/dict.h
new file mode 100644
index 0000000..6e28b61
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/dict.h
@@ -0,0 +1,121 @@
+/*
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Public dictionary API.
+ */
+
+#ifndef AVUTIL_DICT_H
+#define AVUTIL_DICT_H
+
+/**
+ * @addtogroup lavu_dict AVDictionary
+ * @ingroup lavu_data
+ *
+ * @brief Simple key:value store
+ *
+ * @{
+ * Dictionaries are used for storing key:value pairs. To create
+ * an AVDictionary, simply pass an address of a NULL pointer to
+ * av_dict_set(). NULL can be used as an empty dictionary wherever
+ * a pointer to an AVDictionary is required.
+ * Use av_dict_get() to retrieve an entry or iterate over all
+ * entries and finally av_dict_free() to free the dictionary
+ * and all its contents.
+ *
+ * @code
+ * AVDictionary *d = NULL;                // "create" an empty dictionary
+ * av_dict_set(&d, "foo", "bar", 0);      // add an entry
+ *
+ * char *k = av_strdup("key");            // if your strings are already allocated,
+ * char *v = av_strdup("value");          // you can avoid copying them like this
+ * av_dict_set(&d, k, v, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
+ *
+ * AVDictionaryEntry *t = NULL;
+ * while (t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX)) {
+ *     <....>                             // iterate over all entries in d
+ * }
+ *
+ * av_dict_free(&d);
+ * @endcode
+ *
+ */
+
+#define AV_DICT_MATCH_CASE      1
+#define AV_DICT_IGNORE_SUFFIX   2
+#define AV_DICT_DONT_STRDUP_KEY 4   /**< Take ownership of a key that's been
+                                         allocated with av_malloc() and children. */
+#define AV_DICT_DONT_STRDUP_VAL 8   /**< Take ownership of a value that's been
+                                         allocated with av_malloc() and chilren. */
+#define AV_DICT_DONT_OVERWRITE 16   ///< Don't overwrite existing entries.
+#define AV_DICT_APPEND         32   /**< If the entry already exists, append to it.  Note that no
+                                      delimiter is added, the strings are simply concatenated. */
+
+typedef struct {
+    char *key;
+    char *value;
+} AVDictionaryEntry;
+
+typedef struct AVDictionary AVDictionary;
+
+/**
+ * Get a dictionary entry with matching key.
+ *
+ * @param prev Set to the previous matching element to find the next.
+ *             If set to NULL the first matching element is returned.
+ * @param flags Allows case as well as suffix-insensitive comparisons.
+ * @return Found entry or NULL, changing key or value leads to undefined behavior.
+ */
+AVDictionaryEntry *
+av_dict_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags);
+
+/**
+ * Set the given entry in *pm, overwriting an existing entry.
+ *
+ * @param pm pointer to a pointer to a dictionary struct. If *pm is NULL
+ * a dictionary struct is allocated and put in *pm.
+ * @param key entry key to add to *pm (will be av_strduped depending on flags)
+ * @param value entry value to add to *pm (will be av_strduped depending on flags).
+ *        Passing a NULL value will cause an existing tag to be deleted.
+ * @return >= 0 on success otherwise an error code <0
+ */
+int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags);
+
+/**
+ * Copy entries from one AVDictionary struct into another.
+ * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL,
+ *            this function will allocate a struct for you and put it in *dst
+ * @param src pointer to source AVDictionary struct
+ * @param flags flags to use when setting entries in *dst
+ * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag
+ */
+void av_dict_copy(AVDictionary **dst, AVDictionary *src, int flags);
+
+/**
+ * Free all the memory allocated for an AVDictionary struct
+ * and all keys and values.
+ */
+void av_dict_free(AVDictionary **m);
+
+/**
+ * @}
+ */
+
+#endif // AVUTIL_DICT_H
diff --git a/make/stub_includes/libav/libavutil/error.h b/make/stub_includes/libav/libavutil/error.h
new file mode 100644
index 0000000..11bcc5c
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/error.h
@@ -0,0 +1,81 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * error code definitions
+ */
+
+#ifndef AVUTIL_ERROR_H
+#define AVUTIL_ERROR_H
+
+#include <errno.h>
+#include "avutil.h"
+
+/**
+ * @addtogroup lavu_error
+ *
+ * @{
+ */
+
+
+/* error handling */
+#if EDOM > 0
+#define AVERROR(e) (-(e))   ///< Returns a negative error code from a POSIX error code, to return from library functions.
+#define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value.
+#else
+/* Some platforms have E* and errno already negated. */
+#define AVERROR(e) (e)
+#define AVUNERROR(e) (e)
+#endif
+
+#define AVERROR_BSF_NOT_FOUND      (-MKTAG(0xF8,'B','S','F')) ///< Bitstream filter not found
+#define AVERROR_DECODER_NOT_FOUND  (-MKTAG(0xF8,'D','E','C')) ///< Decoder not found
+#define AVERROR_DEMUXER_NOT_FOUND  (-MKTAG(0xF8,'D','E','M')) ///< Demuxer not found
+#define AVERROR_ENCODER_NOT_FOUND  (-MKTAG(0xF8,'E','N','C')) ///< Encoder not found
+#define AVERROR_EOF                (-MKTAG( 'E','O','F',' ')) ///< End of file
+#define AVERROR_EXIT               (-MKTAG( 'E','X','I','T')) ///< Immediate exit was requested; the called function should not be restarted
+#define AVERROR_FILTER_NOT_FOUND   (-MKTAG(0xF8,'F','I','L')) ///< Filter not found
+#define AVERROR_INVALIDDATA        (-MKTAG( 'I','N','D','A')) ///< Invalid data found when processing input
+#define AVERROR_MUXER_NOT_FOUND    (-MKTAG(0xF8,'M','U','X')) ///< Muxer not found
+#define AVERROR_OPTION_NOT_FOUND   (-MKTAG(0xF8,'O','P','T')) ///< Option not found
+#define AVERROR_PATCHWELCOME       (-MKTAG( 'P','A','W','E')) ///< Not yet implemented in Libav, patches welcome
+#define AVERROR_PROTOCOL_NOT_FOUND (-MKTAG(0xF8,'P','R','O')) ///< Protocol not found
+#define AVERROR_STREAM_NOT_FOUND   (-MKTAG(0xF8,'S','T','R')) ///< Stream not found
+#define AVERROR_BUG                (-MKTAG( 'B','U','G',' ')) ///< Bug detected, please report the issue
+#define AVERROR_UNKNOWN            (-MKTAG( 'U','N','K','N')) ///< Unknown error, typically from an external library
+
+/**
+ * Put a description of the AVERROR code errnum in errbuf.
+ * In case of failure the global variable errno is set to indicate the
+ * error. Even in case of failure av_strerror() will print a generic
+ * error message indicating the errnum provided to errbuf.
+ *
+ * @param errnum      error code to describe
+ * @param errbuf      buffer to which description is written
+ * @param errbuf_size the size in bytes of errbuf
+ * @return 0 on success, a negative value if a description for errnum
+ * cannot be found
+ */
+int av_strerror(int errnum, char *errbuf, size_t errbuf_size);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_ERROR_H */
diff --git a/make/stub_includes/libav/libavutil/eval.h b/make/stub_includes/libav/libavutil/eval.h
new file mode 100644
index 0000000..ccb29e7
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/eval.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2002 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * simple arithmetic expression evaluator
+ */
+
+#ifndef AVUTIL_EVAL_H
+#define AVUTIL_EVAL_H
+
+#include "avutil.h"
+
+typedef struct AVExpr AVExpr;
+
+/**
+ * Parse and evaluate an expression.
+ * Note, this is significantly slower than av_expr_eval().
+ *
+ * @param res a pointer to a double where is put the result value of
+ * the expression, or NAN in case of error
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param const_values a zero terminated array of values for the identifiers from const_names
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse_and_eval(double *res, const char *s,
+                           const char * const *const_names, const double *const_values,
+                           const char * const *func1_names, double (* const *funcs1)(void *, double),
+                           const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                           void *opaque, int log_offset, void *log_ctx);
+
+/**
+ * Parse an expression.
+ *
+ * @param expr a pointer where is put an AVExpr containing the parsed
+ * value in case of successful parsing, or NULL otherwise.
+ * The pointed to AVExpr must be freed with av_expr_free() by the user
+ * when it is not needed anymore.
+ * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)"
+ * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0}
+ * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers
+ * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument
+ * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers
+ * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments
+ * @param log_ctx parent logging context
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_expr_parse(AVExpr **expr, const char *s,
+                  const char * const *const_names,
+                  const char * const *func1_names, double (* const *funcs1)(void *, double),
+                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),
+                  int log_offset, void *log_ctx);
+
+/**
+ * Evaluate a previously parsed expression.
+ *
+ * @param const_values a zero terminated array of values for the identifiers from av_expr_parse() const_names
+ * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2
+ * @return the value of the expression
+ */
+double av_expr_eval(AVExpr *e, const double *const_values, void *opaque);
+
+/**
+ * Free a parsed expression previously created with av_expr_parse().
+ */
+void av_expr_free(AVExpr *e);
+
+/**
+ * Parse the string in numstr and return its value as a double. If
+ * the string is empty, contains only whitespaces, or does not contain
+ * an initial substring that has the expected syntax for a
+ * floating-point number, no conversion is performed. In this case,
+ * returns a value of zero and the value returned in tail is the value
+ * of numstr.
+ *
+ * @param numstr a string representing a number, may contain one of
+ * the International System number postfixes, for example 'K', 'M',
+ * 'G'. If 'i' is appended after the postfix, powers of 2 are used
+ * instead of powers of 10. The 'B' postfix multiplies the value for
+ * 8, and can be appended after another postfix or used alone. This
+ * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix.
+ * @param tail if non-NULL puts here the pointer to the char next
+ * after the last parsed character
+ */
+double av_strtod(const char *numstr, char **tail);
+
+#endif /* AVUTIL_EVAL_H */
diff --git a/make/stub_includes/libav/libavutil/fifo.h b/make/stub_includes/libav/libavutil/fifo.h
new file mode 100644
index 0000000..f106239
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/fifo.h
@@ -0,0 +1,141 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * a very simple circular buffer FIFO implementation
+ */
+
+#ifndef AVUTIL_FIFO_H
+#define AVUTIL_FIFO_H
+
+#include <stdint.h>
+#include "avutil.h"
+
+typedef struct AVFifoBuffer {
+    uint8_t *buffer;
+    uint8_t *rptr, *wptr, *end;
+    uint32_t rndx, wndx;
+} AVFifoBuffer;
+
+/**
+ * Initialize an AVFifoBuffer.
+ * @param size of FIFO
+ * @return AVFifoBuffer or NULL in case of memory allocation failure
+ */
+AVFifoBuffer *av_fifo_alloc(unsigned int size);
+
+/**
+ * Free an AVFifoBuffer.
+ * @param f AVFifoBuffer to free
+ */
+void av_fifo_free(AVFifoBuffer *f);
+
+/**
+ * Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
+ * @param f AVFifoBuffer to reset
+ */
+void av_fifo_reset(AVFifoBuffer *f);
+
+/**
+ * Return the amount of data in bytes in the AVFifoBuffer, that is the
+ * amount of data you can read from it.
+ * @param f AVFifoBuffer to read from
+ * @return size
+ */
+int av_fifo_size(AVFifoBuffer *f);
+
+/**
+ * Return the amount of space in bytes in the AVFifoBuffer, that is the
+ * amount of data you can write into it.
+ * @param f AVFifoBuffer to write into
+ * @return size
+ */
+int av_fifo_space(AVFifoBuffer *f);
+
+/**
+ * Feed data from an AVFifoBuffer to a user-supplied callback.
+ * @param f AVFifoBuffer to read from
+ * @param buf_size number of bytes to read
+ * @param func generic read function
+ * @param dest data destination
+ */
+int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int));
+
+/**
+ * Feed data from a user-supplied callback to an AVFifoBuffer.
+ * @param f AVFifoBuffer to write to
+ * @param src data source; non-const since it may be used as a
+ * modifiable context by the function defined in func
+ * @param size number of bytes to write
+ * @param func generic write function; the first parameter is src,
+ * the second is dest_buf, the third is dest_buf_size.
+ * func must return the number of bytes written to dest_buf, or <= 0 to
+ * indicate no more data available to write.
+ * If func is NULL, src is interpreted as a simple byte array for source data.
+ * @return the number of bytes written to the FIFO
+ */
+int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int));
+
+/**
+ * Resize an AVFifoBuffer.
+ * @param f AVFifoBuffer to resize
+ * @param size new AVFifoBuffer size in bytes
+ * @return <0 for failure, >=0 otherwise
+ */
+int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size);
+
+/**
+ * Read and discard the specified amount of data from an AVFifoBuffer.
+ * @param f AVFifoBuffer to read from
+ * @param size amount of data to read in bytes
+ */
+void av_fifo_drain(AVFifoBuffer *f, int size);
+
+/**
+ * Return a pointer to the data stored in a FIFO buffer at a certain offset.
+ * The FIFO buffer is not modified.
+ *
+ * @param f    AVFifoBuffer to peek at, f must be non-NULL
+ * @param offs an offset in bytes, its absolute value must be less
+ *             than the used buffer size or the returned pointer will
+ *             point outside to the buffer data.
+ *             The used buffer size can be checked with av_fifo_size().
+ */
+static inline uint8_t *av_fifo_peek2(const AVFifoBuffer *f, int offs)
+{
+    uint8_t *ptr = f->rptr + offs;
+    if (ptr >= f->end)
+        ptr = f->buffer + (ptr - f->end);
+    else if (ptr < f->buffer)
+        ptr = f->end - (f->buffer - ptr);
+    return ptr;
+}
+
+#if FF_API_AV_FIFO_PEEK
+/**
+ * @deprecated Use av_fifo_peek2() instead.
+ */
+attribute_deprecated
+static inline uint8_t av_fifo_peek(AVFifoBuffer *f, int offs)
+{
+    return *av_fifo_peek2(f, offs);
+}
+#endif
+
+#endif /* AVUTIL_FIFO_H */
diff --git a/make/stub_includes/libav/libavutil/file.h b/make/stub_includes/libav/libavutil/file.h
new file mode 100644
index 0000000..c481c37
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/file.h
@@ -0,0 +1,52 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_FILE_H
+#define AVUTIL_FILE_H
+
+#include "avutil.h"
+
+/**
+ * @file
+ * Misc file utilities.
+ */
+
+/**
+ * Read the file with name filename, and put its content in a newly
+ * allocated buffer or map it with mmap() when available.
+ * In case of success set *bufptr to the read or mmapped buffer, and
+ * *size to the size in bytes of the buffer in *bufptr.
+ * The returned buffer must be released with av_file_unmap().
+ *
+ * @param log_offset loglevel offset used for logging
+ * @param log_ctx context used for logging
+ * @return a non negative number in case of success, a negative value
+ * corresponding to an AVERROR error code in case of failure
+ */
+int av_file_map(const char *filename, uint8_t **bufptr, size_t *size,
+                int log_offset, void *log_ctx);
+
+/**
+ * Unmap or free the buffer bufptr created by av_file_map().
+ *
+ * @param size size in bytes of bufptr, must be the same as returned
+ * by av_file_map()
+ */
+void av_file_unmap(uint8_t *bufptr, size_t size);
+
+#endif /* AVUTIL_FILE_H */
diff --git a/make/stub_includes/libav/libavutil/imgutils.h b/make/stub_includes/libav/libavutil/imgutils.h
new file mode 100644
index 0000000..3815a49
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/imgutils.h
@@ -0,0 +1,138 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_IMGUTILS_H
+#define AVUTIL_IMGUTILS_H
+
+/**
+ * @file
+ * misc image utilities
+ *
+ * @addtogroup lavu_picture
+ * @{
+ */
+
+#include "avutil.h"
+#include "pixdesc.h"
+
+/**
+ * Compute the max pixel step for each plane of an image with a
+ * format described by pixdesc.
+ *
+ * The pixel step is the distance in bytes between the first byte of
+ * the group of bytes which describe a pixel component and the first
+ * byte of the successive group in the same plane for the same
+ * component.
+ *
+ * @param max_pixsteps an array which is filled with the max pixel step
+ * for each plane. Since a plane may contain different pixel
+ * components, the computed max_pixsteps[plane] is relative to the
+ * component in the plane with the max pixel step.
+ * @param max_pixstep_comps an array which is filled with the component
+ * for each plane which has the max pixel step. May be NULL.
+ */
+void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4],
+                                const AVPixFmtDescriptor *pixdesc);
+
+/**
+ * Compute the size of an image line with format pix_fmt and width
+ * width for the plane plane.
+ *
+ * @return the computed size in bytes
+ */
+int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane);
+
+/**
+ * Fill plane linesizes for an image with pixel format pix_fmt and
+ * width width.
+ *
+ * @param linesizes array to be filled with the linesize for each plane
+ * @return >= 0 in case of success, a negative error code otherwise
+ */
+int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width);
+
+/**
+ * Fill plane data pointers for an image with pixel format pix_fmt and
+ * height height.
+ *
+ * @param data pointers array to be filled with the pointer for each image plane
+ * @param ptr the pointer to a buffer which will contain the image
+ * @param linesizes the array containing the linesize for each
+ * plane, should be filled by av_image_fill_linesizes()
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_fill_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,
+                           uint8_t *ptr, const int linesizes[4]);
+
+/**
+ * Allocate an image with size w and h and pixel format pix_fmt, and
+ * fill pointers and linesizes accordingly.
+ * The allocated image buffer has to be freed by using
+ * av_freep(&pointers[0]).
+ *
+ * @param align the value to use for buffer size alignment
+ * @return the size in bytes required for the image buffer, a negative
+ * error code in case of failure
+ */
+int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
+                   int w, int h, enum PixelFormat pix_fmt, int align);
+
+/**
+ * Copy image plane from src to dst.
+ * That is, copy "height" number of lines of "bytewidth" bytes each.
+ * The first byte of each successive line is separated by *_linesize
+ * bytes.
+ *
+ * @param dst_linesize linesize for the image plane in dst
+ * @param src_linesize linesize for the image plane in src
+ */
+void av_image_copy_plane(uint8_t       *dst, int dst_linesize,
+                         const uint8_t *src, int src_linesize,
+                         int bytewidth, int height);
+
+/**
+ * Copy image in src_data to dst_data.
+ *
+ * @param dst_linesizes linesizes for the image in dst_data
+ * @param src_linesizes linesizes for the image in src_data
+ */
+void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
+                   const uint8_t *src_data[4], const int src_linesizes[4],
+                   enum PixelFormat pix_fmt, int width, int height);
+
+/**
+ * Check if the given dimension of an image is valid, meaning that all
+ * bytes of the image can be addressed with a signed int.
+ *
+ * @param w the width of the picture
+ * @param h the height of the picture
+ * @param log_offset the offset to sum to the log level for logging with log_ctx
+ * @param log_ctx the parent logging context, it may be NULL
+ * @return >= 0 if valid, a negative error code otherwise
+ */
+int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);
+
+int ff_set_systematic_pal2(uint32_t pal[256], enum PixelFormat pix_fmt);
+
+/**
+ * @}
+ */
+
+
+#endif /* AVUTIL_IMGUTILS_H */
diff --git a/make/stub_includes/libav/libavutil/intfloat.h b/make/stub_includes/libav/libavutil/intfloat.h
new file mode 100644
index 0000000..9db624a
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/intfloat.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTFLOAT_H
+#define AVUTIL_INTFLOAT_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+union av_intfloat32 {
+    uint32_t i;
+    float    f;
+};
+
+union av_intfloat64 {
+    uint64_t i;
+    double   f;
+};
+
+/**
+ * Reinterpret a 32-bit integer as a float.
+ */
+static av_always_inline float av_int2float(uint32_t i)
+{
+    union av_intfloat32 v = { .i = i };
+    return v.f;
+}
+
+/**
+ * Reinterpret a float as a 32-bit integer.
+ */
+static av_always_inline uint32_t av_float2int(float f)
+{
+    union av_intfloat32 v = { .f = f };
+    return v.i;
+}
+
+/**
+ * Reinterpret a 64-bit integer as a double.
+ */
+static av_always_inline double av_int2double(uint64_t i)
+{
+    union av_intfloat64 v = { .i = i };
+    return v.f;
+}
+
+/**
+ * Reinterpret a double as a 64-bit integer.
+ */
+static av_always_inline uint64_t av_double2int(double f)
+{
+    union av_intfloat64 v = { .f = f };
+    return v.i;
+}
+
+#endif /* AVUTIL_INTFLOAT_H */
diff --git a/make/stub_includes/libav/libavutil/intfloat_readwrite.h b/make/stub_includes/libav/libavutil/intfloat_readwrite.h
new file mode 100644
index 0000000..f093b92
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/intfloat_readwrite.h
@@ -0,0 +1,40 @@
+/*
+ * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTFLOAT_READWRITE_H
+#define AVUTIL_INTFLOAT_READWRITE_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+/* IEEE 80 bits extended float */
+typedef struct AVExtFloat  {
+    uint8_t exponent[2];
+    uint8_t mantissa[8];
+} AVExtFloat;
+
+attribute_deprecated double av_int2dbl(int64_t v) av_const;
+attribute_deprecated float av_int2flt(int32_t v) av_const;
+attribute_deprecated double av_ext2dbl(const AVExtFloat ext) av_const;
+attribute_deprecated int64_t av_dbl2int(double d) av_const;
+attribute_deprecated int32_t av_flt2int(float d) av_const;
+attribute_deprecated AVExtFloat av_dbl2ext(double d) av_const;
+
+#endif /* AVUTIL_INTFLOAT_READWRITE_H */
diff --git a/make/stub_includes/libav/libavutil/intreadwrite.h b/make/stub_includes/libav/libavutil/intreadwrite.h
new file mode 100644
index 0000000..01eb278
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/intreadwrite.h
@@ -0,0 +1,522 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTREADWRITE_H
+#define AVUTIL_INTREADWRITE_H
+
+#include <stdint.h>
+#include "libavutil/avconfig.h"
+#include "attributes.h"
+#include "bswap.h"
+
+typedef union {
+    uint64_t u64;
+    uint32_t u32[2];
+    uint16_t u16[4];
+    uint8_t  u8 [8];
+    double   f64;
+    float    f32[2];
+} av_alias av_alias64;
+
+typedef union {
+    uint32_t u32;
+    uint16_t u16[2];
+    uint8_t  u8 [4];
+    float    f32;
+} av_alias av_alias32;
+
+typedef union {
+    uint16_t u16;
+    uint8_t  u8 [2];
+} av_alias av_alias16;
+
+/*
+ * Arch-specific headers can provide any combination of
+ * AV_[RW][BLN](16|24|32|64) and AV_(COPY|SWAP|ZERO)(64|128) macros.
+ * Preprocessor symbols must be defined, even if these are implemented
+ * as inline functions.
+ */
+
+#ifdef HAVE_AV_CONFIG_H
+
+#include "config.h"
+
+#if   ARCH_ARM
+#   include "arm/intreadwrite.h"
+#elif ARCH_AVR32
+#   include "avr32/intreadwrite.h"
+#elif ARCH_MIPS
+#   include "mips/intreadwrite.h"
+#elif ARCH_PPC
+#   include "ppc/intreadwrite.h"
+#elif ARCH_TOMI
+#   include "tomi/intreadwrite.h"
+#elif ARCH_X86
+#   include "x86/intreadwrite.h"
+#endif
+
+#endif /* HAVE_AV_CONFIG_H */
+
+/*
+ * Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers.
+ */
+
+#if AV_HAVE_BIGENDIAN
+
+#   if    defined(AV_RN16) && !defined(AV_RB16)
+#       define AV_RB16(p) AV_RN16(p)
+#   elif !defined(AV_RN16) &&  defined(AV_RB16)
+#       define AV_RN16(p) AV_RB16(p)
+#   endif
+
+#   if    defined(AV_WN16) && !defined(AV_WB16)
+#       define AV_WB16(p, v) AV_WN16(p, v)
+#   elif !defined(AV_WN16) &&  defined(AV_WB16)
+#       define AV_WN16(p, v) AV_WB16(p, v)
+#   endif
+
+#   if    defined(AV_RN24) && !defined(AV_RB24)
+#       define AV_RB24(p) AV_RN24(p)
+#   elif !defined(AV_RN24) &&  defined(AV_RB24)
+#       define AV_RN24(p) AV_RB24(p)
+#   endif
+
+#   if    defined(AV_WN24) && !defined(AV_WB24)
+#       define AV_WB24(p, v) AV_WN24(p, v)
+#   elif !defined(AV_WN24) &&  defined(AV_WB24)
+#       define AV_WN24(p, v) AV_WB24(p, v)
+#   endif
+
+#   if    defined(AV_RN32) && !defined(AV_RB32)
+#       define AV_RB32(p) AV_RN32(p)
+#   elif !defined(AV_RN32) &&  defined(AV_RB32)
+#       define AV_RN32(p) AV_RB32(p)
+#   endif
+
+#   if    defined(AV_WN32) && !defined(AV_WB32)
+#       define AV_WB32(p, v) AV_WN32(p, v)
+#   elif !defined(AV_WN32) &&  defined(AV_WB32)
+#       define AV_WN32(p, v) AV_WB32(p, v)
+#   endif
+
+#   if    defined(AV_RN64) && !defined(AV_RB64)
+#       define AV_RB64(p) AV_RN64(p)
+#   elif !defined(AV_RN64) &&  defined(AV_RB64)
+#       define AV_RN64(p) AV_RB64(p)
+#   endif
+
+#   if    defined(AV_WN64) && !defined(AV_WB64)
+#       define AV_WB64(p, v) AV_WN64(p, v)
+#   elif !defined(AV_WN64) &&  defined(AV_WB64)
+#       define AV_WN64(p, v) AV_WB64(p, v)
+#   endif
+
+#else /* AV_HAVE_BIGENDIAN */
+
+#   if    defined(AV_RN16) && !defined(AV_RL16)
+#       define AV_RL16(p) AV_RN16(p)
+#   elif !defined(AV_RN16) &&  defined(AV_RL16)
+#       define AV_RN16(p) AV_RL16(p)
+#   endif
+
+#   if    defined(AV_WN16) && !defined(AV_WL16)
+#       define AV_WL16(p, v) AV_WN16(p, v)
+#   elif !defined(AV_WN16) &&  defined(AV_WL16)
+#       define AV_WN16(p, v) AV_WL16(p, v)
+#   endif
+
+#   if    defined(AV_RN24) && !defined(AV_RL24)
+#       define AV_RL24(p) AV_RN24(p)
+#   elif !defined(AV_RN24) &&  defined(AV_RL24)
+#       define AV_RN24(p) AV_RL24(p)
+#   endif
+
+#   if    defined(AV_WN24) && !defined(AV_WL24)
+#       define AV_WL24(p, v) AV_WN24(p, v)
+#   elif !defined(AV_WN24) &&  defined(AV_WL24)
+#       define AV_WN24(p, v) AV_WL24(p, v)
+#   endif
+
+#   if    defined(AV_RN32) && !defined(AV_RL32)
+#       define AV_RL32(p) AV_RN32(p)
+#   elif !defined(AV_RN32) &&  defined(AV_RL32)
+#       define AV_RN32(p) AV_RL32(p)
+#   endif
+
+#   if    defined(AV_WN32) && !defined(AV_WL32)
+#       define AV_WL32(p, v) AV_WN32(p, v)
+#   elif !defined(AV_WN32) &&  defined(AV_WL32)
+#       define AV_WN32(p, v) AV_WL32(p, v)
+#   endif
+
+#   if    defined(AV_RN64) && !defined(AV_RL64)
+#       define AV_RL64(p) AV_RN64(p)
+#   elif !defined(AV_RN64) &&  defined(AV_RL64)
+#       define AV_RN64(p) AV_RL64(p)
+#   endif
+
+#   if    defined(AV_WN64) && !defined(AV_WL64)
+#       define AV_WL64(p, v) AV_WN64(p, v)
+#   elif !defined(AV_WN64) &&  defined(AV_WL64)
+#       define AV_WN64(p, v) AV_WL64(p, v)
+#   endif
+
+#endif /* !AV_HAVE_BIGENDIAN */
+
+/*
+ * Define AV_[RW]N helper macros to simplify definitions not provided
+ * by per-arch headers.
+ */
+
+#if defined(__GNUC__) && !defined(__TI_COMPILER_VERSION__)
+
+union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias;
+union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias;
+union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
+
+#   define AV_RN(s, p) (((const union unaligned_##s *) (p))->l)
+#   define AV_WN(s, p, v) ((((union unaligned_##s *) (p))->l) = (v))
+
+#elif defined(__DECC)
+
+#   define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
+#   define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
+
+#elif AV_HAVE_FAST_UNALIGNED
+
+#   define AV_RN(s, p) (((const av_alias##s*)(p))->u##s)
+#   define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v))
+
+#else
+
+#ifndef AV_RB16
+#   define AV_RB16(x)                           \
+    ((((const uint8_t*)(x))[0] << 8) |          \
+      ((const uint8_t*)(x))[1])
+#endif
+#ifndef AV_WB16
+#   define AV_WB16(p, d) do {                   \
+        ((uint8_t*)(p))[1] = (d);               \
+        ((uint8_t*)(p))[0] = (d)>>8;            \
+    } while(0)
+#endif
+
+#ifndef AV_RL16
+#   define AV_RL16(x)                           \
+    ((((const uint8_t*)(x))[1] << 8) |          \
+      ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL16
+#   define AV_WL16(p, d) do {                   \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+    } while(0)
+#endif
+
+#ifndef AV_RB32
+#   define AV_RB32(x)                                \
+    (((uint32_t)((const uint8_t*)(x))[0] << 24) |    \
+               (((const uint8_t*)(x))[1] << 16) |    \
+               (((const uint8_t*)(x))[2] <<  8) |    \
+                ((const uint8_t*)(x))[3])
+#endif
+#ifndef AV_WB32
+#   define AV_WB32(p, d) do {                   \
+        ((uint8_t*)(p))[3] = (d);               \
+        ((uint8_t*)(p))[2] = (d)>>8;            \
+        ((uint8_t*)(p))[1] = (d)>>16;           \
+        ((uint8_t*)(p))[0] = (d)>>24;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL32
+#   define AV_RL32(x)                                \
+    (((uint32_t)((const uint8_t*)(x))[3] << 24) |    \
+               (((const uint8_t*)(x))[2] << 16) |    \
+               (((const uint8_t*)(x))[1] <<  8) |    \
+                ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL32
+#   define AV_WL32(p, d) do {                   \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+        ((uint8_t*)(p))[3] = (d)>>24;           \
+    } while(0)
+#endif
+
+#ifndef AV_RB64
+#   define AV_RB64(x)                                   \
+    (((uint64_t)((const uint8_t*)(x))[0] << 56) |       \
+     ((uint64_t)((const uint8_t*)(x))[1] << 48) |       \
+     ((uint64_t)((const uint8_t*)(x))[2] << 40) |       \
+     ((uint64_t)((const uint8_t*)(x))[3] << 32) |       \
+     ((uint64_t)((const uint8_t*)(x))[4] << 24) |       \
+     ((uint64_t)((const uint8_t*)(x))[5] << 16) |       \
+     ((uint64_t)((const uint8_t*)(x))[6] <<  8) |       \
+      (uint64_t)((const uint8_t*)(x))[7])
+#endif
+#ifndef AV_WB64
+#   define AV_WB64(p, d) do {                   \
+        ((uint8_t*)(p))[7] = (d);               \
+        ((uint8_t*)(p))[6] = (d)>>8;            \
+        ((uint8_t*)(p))[5] = (d)>>16;           \
+        ((uint8_t*)(p))[4] = (d)>>24;           \
+        ((uint8_t*)(p))[3] = (d)>>32;           \
+        ((uint8_t*)(p))[2] = (d)>>40;           \
+        ((uint8_t*)(p))[1] = (d)>>48;           \
+        ((uint8_t*)(p))[0] = (d)>>56;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL64
+#   define AV_RL64(x)                                   \
+    (((uint64_t)((const uint8_t*)(x))[7] << 56) |       \
+     ((uint64_t)((const uint8_t*)(x))[6] << 48) |       \
+     ((uint64_t)((const uint8_t*)(x))[5] << 40) |       \
+     ((uint64_t)((const uint8_t*)(x))[4] << 32) |       \
+     ((uint64_t)((const uint8_t*)(x))[3] << 24) |       \
+     ((uint64_t)((const uint8_t*)(x))[2] << 16) |       \
+     ((uint64_t)((const uint8_t*)(x))[1] <<  8) |       \
+      (uint64_t)((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL64
+#   define AV_WL64(p, d) do {                   \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+        ((uint8_t*)(p))[3] = (d)>>24;           \
+        ((uint8_t*)(p))[4] = (d)>>32;           \
+        ((uint8_t*)(p))[5] = (d)>>40;           \
+        ((uint8_t*)(p))[6] = (d)>>48;           \
+        ((uint8_t*)(p))[7] = (d)>>56;           \
+    } while(0)
+#endif
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_RN(s, p)    AV_RB##s(p)
+#   define AV_WN(s, p, v) AV_WB##s(p, v)
+#else
+#   define AV_RN(s, p)    AV_RL##s(p)
+#   define AV_WN(s, p, v) AV_WL##s(p, v)
+#endif
+
+#endif /* HAVE_FAST_UNALIGNED */
+
+#ifndef AV_RN16
+#   define AV_RN16(p) AV_RN(16, p)
+#endif
+
+#ifndef AV_RN32
+#   define AV_RN32(p) AV_RN(32, p)
+#endif
+
+#ifndef AV_RN64
+#   define AV_RN64(p) AV_RN(64, p)
+#endif
+
+#ifndef AV_WN16
+#   define AV_WN16(p, v) AV_WN(16, p, v)
+#endif
+
+#ifndef AV_WN32
+#   define AV_WN32(p, v) AV_WN(32, p, v)
+#endif
+
+#ifndef AV_WN64
+#   define AV_WN64(p, v) AV_WN(64, p, v)
+#endif
+
+#if AV_HAVE_BIGENDIAN
+#   define AV_RB(s, p)    AV_RN##s(p)
+#   define AV_WB(s, p, v) AV_WN##s(p, v)
+#   define AV_RL(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WL(s, p, v) AV_WN##s(p, av_bswap##s(v))
+#else
+#   define AV_RB(s, p)    av_bswap##s(AV_RN##s(p))
+#   define AV_WB(s, p, v) AV_WN##s(p, av_bswap##s(v))
+#   define AV_RL(s, p)    AV_RN##s(p)
+#   define AV_WL(s, p, v) AV_WN##s(p, v)
+#endif
+
+#define AV_RB8(x)     (((const uint8_t*)(x))[0])
+#define AV_WB8(p, d)  do { ((uint8_t*)(p))[0] = (d); } while(0)
+
+#define AV_RL8(x)     AV_RB8(x)
+#define AV_WL8(p, d)  AV_WB8(p, d)
+
+#ifndef AV_RB16
+#   define AV_RB16(p)    AV_RB(16, p)
+#endif
+#ifndef AV_WB16
+#   define AV_WB16(p, v) AV_WB(16, p, v)
+#endif
+
+#ifndef AV_RL16
+#   define AV_RL16(p)    AV_RL(16, p)
+#endif
+#ifndef AV_WL16
+#   define AV_WL16(p, v) AV_WL(16, p, v)
+#endif
+
+#ifndef AV_RB32
+#   define AV_RB32(p)    AV_RB(32, p)
+#endif
+#ifndef AV_WB32
+#   define AV_WB32(p, v) AV_WB(32, p, v)
+#endif
+
+#ifndef AV_RL32
+#   define AV_RL32(p)    AV_RL(32, p)
+#endif
+#ifndef AV_WL32
+#   define AV_WL32(p, v) AV_WL(32, p, v)
+#endif
+
+#ifndef AV_RB64
+#   define AV_RB64(p)    AV_RB(64, p)
+#endif
+#ifndef AV_WB64
+#   define AV_WB64(p, v) AV_WB(64, p, v)
+#endif
+
+#ifndef AV_RL64
+#   define AV_RL64(p)    AV_RL(64, p)
+#endif
+#ifndef AV_WL64
+#   define AV_WL64(p, v) AV_WL(64, p, v)
+#endif
+
+#ifndef AV_RB24
+#   define AV_RB24(x)                           \
+    ((((const uint8_t*)(x))[0] << 16) |         \
+     (((const uint8_t*)(x))[1] <<  8) |         \
+      ((const uint8_t*)(x))[2])
+#endif
+#ifndef AV_WB24
+#   define AV_WB24(p, d) do {                   \
+        ((uint8_t*)(p))[2] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[0] = (d)>>16;           \
+    } while(0)
+#endif
+
+#ifndef AV_RL24
+#   define AV_RL24(x)                           \
+    ((((const uint8_t*)(x))[2] << 16) |         \
+     (((const uint8_t*)(x))[1] <<  8) |         \
+      ((const uint8_t*)(x))[0])
+#endif
+#ifndef AV_WL24
+#   define AV_WL24(p, d) do {                   \
+        ((uint8_t*)(p))[0] = (d);               \
+        ((uint8_t*)(p))[1] = (d)>>8;            \
+        ((uint8_t*)(p))[2] = (d)>>16;           \
+    } while(0)
+#endif
+
+/*
+ * The AV_[RW]NA macros access naturally aligned data
+ * in a type-safe way.
+ */
+
+#define AV_RNA(s, p)    (((const av_alias##s*)(p))->u##s)
+#define AV_WNA(s, p, v) (((av_alias##s*)(p))->u##s = (v))
+
+#ifndef AV_RN16A
+#   define AV_RN16A(p) AV_RNA(16, p)
+#endif
+
+#ifndef AV_RN32A
+#   define AV_RN32A(p) AV_RNA(32, p)
+#endif
+
+#ifndef AV_RN64A
+#   define AV_RN64A(p) AV_RNA(64, p)
+#endif
+
+#ifndef AV_WN16A
+#   define AV_WN16A(p, v) AV_WNA(16, p, v)
+#endif
+
+#ifndef AV_WN32A
+#   define AV_WN32A(p, v) AV_WNA(32, p, v)
+#endif
+
+#ifndef AV_WN64A
+#   define AV_WN64A(p, v) AV_WNA(64, p, v)
+#endif
+
+/* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be
+ * naturally aligned. They may be implemented using MMX,
+ * so emms_c() must be called before using any float code
+ * afterwards.
+ */
+
+#define AV_COPY(n, d, s) \
+    (((av_alias##n*)(d))->u##n = ((const av_alias##n*)(s))->u##n)
+
+#ifndef AV_COPY16
+#   define AV_COPY16(d, s) AV_COPY(16, d, s)
+#endif
+
+#ifndef AV_COPY32
+#   define AV_COPY32(d, s) AV_COPY(32, d, s)
+#endif
+
+#ifndef AV_COPY64
+#   define AV_COPY64(d, s) AV_COPY(64, d, s)
+#endif
+
+#ifndef AV_COPY128
+#   define AV_COPY128(d, s)                    \
+    do {                                       \
+        AV_COPY64(d, s);                       \
+        AV_COPY64((char*)(d)+8, (char*)(s)+8); \
+    } while(0)
+#endif
+
+#define AV_SWAP(n, a, b) FFSWAP(av_alias##n, *(av_alias##n*)(a), *(av_alias##n*)(b))
+
+#ifndef AV_SWAP64
+#   define AV_SWAP64(a, b) AV_SWAP(64, a, b)
+#endif
+
+#define AV_ZERO(n, d) (((av_alias##n*)(d))->u##n = 0)
+
+#ifndef AV_ZERO16
+#   define AV_ZERO16(d) AV_ZERO(16, d)
+#endif
+
+#ifndef AV_ZERO32
+#   define AV_ZERO32(d) AV_ZERO(32, d)
+#endif
+
+#ifndef AV_ZERO64
+#   define AV_ZERO64(d) AV_ZERO(64, d)
+#endif
+
+#ifndef AV_ZERO128
+#   define AV_ZERO128(d)         \
+    do {                         \
+        AV_ZERO64(d);            \
+        AV_ZERO64((char*)(d)+8); \
+    } while(0)
+#endif
+
+#endif /* AVUTIL_INTREADWRITE_H */
diff --git a/make/stub_includes/libav/libavutil/lfg.h b/make/stub_includes/libav/libavutil/lfg.h
new file mode 100644
index 0000000..904d00a
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/lfg.h
@@ -0,0 +1,62 @@
+/*
+ * Lagged Fibonacci PRNG
+ * Copyright (c) 2008 Michael Niedermayer
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LFG_H
+#define AVUTIL_LFG_H
+
+typedef struct {
+    unsigned int state[64];
+    int index;
+} AVLFG;
+
+void av_lfg_init(AVLFG *c, unsigned int seed);
+
+/**
+ * Get the next random unsigned 32-bit number using an ALFG.
+ *
+ * Please also consider a simple LCG like state= state*1664525+1013904223,
+ * it may be good enough and faster for your specific use case.
+ */
+static inline unsigned int av_lfg_get(AVLFG *c){
+    c->state[c->index & 63] = c->state[(c->index-24) & 63] + c->state[(c->index-55) & 63];
+    return c->state[c->index++ & 63];
+}
+
+/**
+ * Get the next random unsigned 32-bit number using a MLFG.
+ *
+ * Please also consider av_lfg_get() above, it is faster.
+ */
+static inline unsigned int av_mlfg_get(AVLFG *c){
+    unsigned int a= c->state[(c->index-55) & 63];
+    unsigned int b= c->state[(c->index-24) & 63];
+    return c->state[c->index++ & 63] = 2*a*b+a+b;
+}
+
+/**
+ * Get the next two numbers generated by a Box-Muller Gaussian
+ * generator using the random numbers issued by lfg.
+ *
+ * @param out array where the two generated numbers are placed
+ */
+void av_bmg_get(AVLFG *lfg, double out[2]);
+
+#endif /* AVUTIL_LFG_H */
diff --git a/make/stub_includes/libav/libavutil/log.h b/make/stub_includes/libav/libavutil/log.h
new file mode 100644
index 0000000..0678e1a
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/log.h
@@ -0,0 +1,172 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LOG_H
+#define AVUTIL_LOG_H
+
+#include <stdarg.h>
+#include "avutil.h"
+#include "attributes.h"
+
+/**
+ * Describe the class of an AVClass context structure. That is an
+ * arbitrary struct of which the first field is a pointer to an
+ * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.).
+ */
+typedef struct AVClass {
+    /**
+     * The name of the class; usually it is the same name as the
+     * context structure type to which the AVClass is associated.
+     */
+    const char* class_name;
+
+    /**
+     * A pointer to a function which returns the name of a context
+     * instance ctx associated with the class.
+     */
+    const char* (*item_name)(void* ctx);
+
+    /**
+     * a pointer to the first option specified in the class if any or NULL
+     *
+     * @see av_set_default_options()
+     */
+    const struct AVOption *option;
+
+    /**
+     * LIBAVUTIL_VERSION with which this structure was created.
+     * This is used to allow fields to be added without requiring major
+     * version bumps everywhere.
+     */
+
+    int version;
+
+    /**
+     * Offset in the structure where log_level_offset is stored.
+     * 0 means there is no such variable
+     */
+    int log_level_offset_offset;
+
+    /**
+     * Offset in the structure where a pointer to the parent context for loging is stored.
+     * for example a decoder that uses eval.c could pass its AVCodecContext to eval as such
+     * parent context. And a av_log() implementation could then display the parent context
+     * can be NULL of course
+     */
+    int parent_log_context_offset;
+
+    /**
+     * Return next AVOptions-enabled child or NULL
+     */
+    void* (*child_next)(void *obj, void *prev);
+
+    /**
+     * Return an AVClass corresponding to next potential
+     * AVOptions-enabled child.
+     *
+     * The difference between child_next and this is that
+     * child_next iterates over _already existing_ objects, while
+     * child_class_next iterates over _all possible_ children.
+     */
+    const struct AVClass* (*child_class_next)(const struct AVClass *prev);
+} AVClass;
+
+/* av_log API */
+
+#define AV_LOG_QUIET    -8
+
+/**
+ * Something went really wrong and we will crash now.
+ */
+#define AV_LOG_PANIC     0
+
+/**
+ * Something went wrong and recovery is not possible.
+ * For example, no header was found for a format which depends
+ * on headers or an illegal combination of parameters is used.
+ */
+#define AV_LOG_FATAL     8
+
+/**
+ * Something went wrong and cannot losslessly be recovered.
+ * However, not all future data is affected.
+ */
+#define AV_LOG_ERROR    16
+
+/**
+ * Something somehow does not look correct. This may or may not
+ * lead to problems. An example would be the use of '-vstrict -2'.
+ */
+#define AV_LOG_WARNING  24
+
+#define AV_LOG_INFO     32
+#define AV_LOG_VERBOSE  40
+
+/**
+ * Stuff which is only useful for libav* developers.
+ */
+#define AV_LOG_DEBUG    48
+
+/**
+ * Send the specified message to the log if the level is less than or equal
+ * to the current av_log_level. By default, all logging messages are sent to
+ * stderr. This behavior can be altered by setting a different av_vlog callback
+ * function.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message, lower values signifying
+ * higher importance.
+ * @param fmt The format string (printf-compatible) that specifies how
+ * subsequent arguments are converted to output.
+ * @see av_vlog
+ */
+void av_log(void *avcl, int level, const char *fmt, ...) av_printf_format(3, 4);
+
+void av_vlog(void *avcl, int level, const char *fmt, va_list);
+int av_log_get_level(void);
+void av_log_set_level(int);
+void av_log_set_callback(void (*)(void*, int, const char*, va_list));
+void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl);
+const char* av_default_item_name(void* ctx);
+
+/**
+ * av_dlog macros
+ * Useful to print debug messages that shouldn't get compiled in normally.
+ */
+
+#ifdef DEBUG
+#    define av_dlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
+#else
+#    define av_dlog(pctx, ...)
+#endif
+
+/**
+ * Skip repeated messages, this requires the user app to use av_log() instead of
+ * (f)printf as the 2 would otherwise interfere and lead to
+ * "Last message repeated x times" messages below (f)printf messages with some
+ * bad luck.
+ * Also to receive the last, "last repeated" line if any, the user app must
+ * call av_log(NULL, AV_LOG_QUIET, ""); at the end
+ */
+#define AV_LOG_SKIP_REPEATED 1
+void av_log_set_flags(int arg);
+
+#endif /* AVUTIL_LOG_H */
diff --git a/make/stub_includes/libav/libavutil/lzo.h b/make/stub_includes/libav/libavutil/lzo.h
new file mode 100644
index 0000000..1b774a5
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/lzo.h
@@ -0,0 +1,77 @@
+/*
+ * LZO 1x decompression
+ * copyright (c) 2006 Reimar Doeffinger
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LZO_H
+#define AVUTIL_LZO_H
+
+/**
+ * @defgroup lavu_lzo LZO
+ * @ingroup lavu_crypto
+ *
+ * @{
+ */
+
+#include <stdint.h>
+
+/** @name Error flags returned by av_lzo1x_decode
+  * @{ */
+/// end of the input buffer reached before decoding finished
+#define AV_LZO_INPUT_DEPLETED 1
+/// decoded data did not fit into output buffer
+#define AV_LZO_OUTPUT_FULL 2
+/// a reference to previously decoded data was wrong
+#define AV_LZO_INVALID_BACKPTR 4
+/// a non-specific error in the compressed bitstream
+#define AV_LZO_ERROR 8
+/** @} */
+
+#define AV_LZO_INPUT_PADDING 8
+#define AV_LZO_OUTPUT_PADDING 12
+
+/**
+ * @brief Decodes LZO 1x compressed data.
+ * @param out output buffer
+ * @param outlen size of output buffer, number of bytes left are returned here
+ * @param in input buffer
+ * @param inlen size of input buffer, number of bytes left are returned here
+ * @return 0 on success, otherwise a combination of the error flags above
+ *
+ * Make sure all buffers are appropriately padded, in must provide
+ * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes.
+ */
+int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen);
+
+/**
+ * @brief deliberately overlapping memcpy implementation
+ * @param dst destination buffer; must be padded with 12 additional bytes
+ * @param back how many bytes back we start (the initial size of the overlapping window)
+ * @param cnt number of bytes to copy, must be >= 0
+ *
+ * cnt > back is valid, this will copy the bytes we just copied,
+ * thus creating a repeating pattern with a period length of back.
+ */
+void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_LZO_H */
diff --git a/make/stub_includes/libav/libavutil/mathematics.h b/make/stub_includes/libav/libavutil/mathematics.h
new file mode 100644
index 0000000..0b072eb
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/mathematics.h
@@ -0,0 +1,122 @@
+/*
+ * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_MATHEMATICS_H
+#define AVUTIL_MATHEMATICS_H
+
+#include <stdint.h>
+#include <math.h>
+#include "attributes.h"
+#include "rational.h"
+
+#ifndef M_E
+#define M_E            2.7182818284590452354   /* e */
+#endif
+#ifndef M_LN2
+#define M_LN2          0.69314718055994530942  /* log_e 2 */
+#endif
+#ifndef M_LN10
+#define M_LN10         2.30258509299404568402  /* log_e 10 */
+#endif
+#ifndef M_LOG2_10
+#define M_LOG2_10      3.32192809488736234787  /* log_2 10 */
+#endif
+#ifndef M_PHI
+#define M_PHI          1.61803398874989484820   /* phi / golden ratio */
+#endif
+#ifndef M_PI
+#define M_PI           3.14159265358979323846  /* pi */
+#endif
+#ifndef M_SQRT1_2
+#define M_SQRT1_2      0.70710678118654752440  /* 1/sqrt(2) */
+#endif
+#ifndef M_SQRT2
+#define M_SQRT2        1.41421356237309504880  /* sqrt(2) */
+#endif
+#ifndef NAN
+#define NAN            (0.0/0.0)
+#endif
+#ifndef INFINITY
+#define INFINITY       (1.0/0.0)
+#endif
+
+/**
+ * @addtogroup lavu_math
+ * @{
+ */
+
+
+enum AVRounding {
+    AV_ROUND_ZERO     = 0, ///< Round toward zero.
+    AV_ROUND_INF      = 1, ///< Round away from zero.
+    AV_ROUND_DOWN     = 2, ///< Round toward -infinity.
+    AV_ROUND_UP       = 3, ///< Round toward +infinity.
+    AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero.
+};
+
+/**
+ * Return the greatest common divisor of a and b.
+ * If both a and b are 0 or either or both are <0 then behavior is
+ * undefined.
+ */
+int64_t av_const av_gcd(int64_t a, int64_t b);
+
+/**
+ * Rescale a 64-bit integer with rounding to nearest.
+ * A simple a*b/c isn't possible as it can overflow.
+ */
+int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const;
+
+/**
+ * Rescale a 64-bit integer with specified rounding.
+ * A simple a*b/c isn't possible as it can overflow.
+ */
+int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const;
+
+/**
+ * Rescale a 64-bit integer by 2 rational numbers.
+ */
+int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;
+
+/**
+ * Compare 2 timestamps each in its own timebases.
+ * The result of the function is undefined if one of the timestamps
+ * is outside the int64_t range when represented in the others timebase.
+ * @return -1 if ts_a is before ts_b, 1 if ts_a is after ts_b or 0 if they represent the same position
+ */
+int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b);
+
+/**
+ * Compare 2 integers modulo mod.
+ * That is we compare integers a and b for which only the least
+ * significant log2(mod) bits are known.
+ *
+ * @param mod must be a power of 2
+ * @return a negative value if a is smaller than b
+ *         a positive value if a is greater than b
+ *         0                if a equals          b
+ */
+int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MATHEMATICS_H */
diff --git a/make/stub_includes/libav/libavutil/md5.h b/make/stub_includes/libav/libavutil/md5.h
new file mode 100644
index 0000000..1412ee2
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/md5.h
@@ -0,0 +1,46 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_MD5_H
+#define AVUTIL_MD5_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_md5 MD5
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_md5_size;
+
+struct AVMD5;
+
+void av_md5_init(struct AVMD5 *ctx);
+void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, const int len);
+void av_md5_final(struct AVMD5 *ctx, uint8_t *dst);
+void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MD5_H */
+
diff --git a/make/stub_includes/libav/libavutil/mem.h b/make/stub_includes/libav/libavutil/mem.h
new file mode 100644
index 0000000..cd8490b
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/mem.h
@@ -0,0 +1,136 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * memory handling functions
+ */
+
+#ifndef AVUTIL_MEM_H
+#define AVUTIL_MEM_H
+
+#include "attributes.h"
+#include "avutil.h"
+
+/**
+ * @addtogroup lavu_mem
+ * @{
+ */
+
+
+#if defined(__ICC) && _ICC < 1200 || defined(__SUNPRO_C)
+    #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
+    #define DECLARE_ASM_CONST(n,t,v)    const t __attribute__ ((aligned (n))) v
+#elif defined(__TI_COMPILER_VERSION__)
+    #define DECLARE_ALIGNED(n,t,v)                      \
+        AV_PRAGMA(DATA_ALIGN(v,n))                      \
+        t __attribute__((aligned(n))) v
+    #define DECLARE_ASM_CONST(n,t,v)                    \
+        AV_PRAGMA(DATA_ALIGN(v,n))                      \
+        static const t __attribute__((aligned(n))) v
+#elif defined(__GNUC__)
+    #define DECLARE_ALIGNED(n,t,v)      t __attribute__ ((aligned (n))) v
+    #define DECLARE_ASM_CONST(n,t,v)    static const t av_used __attribute__ ((aligned (n))) v
+#elif defined(_MSC_VER)
+    #define DECLARE_ALIGNED(n,t,v)      __declspec(align(n)) t v
+    #define DECLARE_ASM_CONST(n,t,v)    __declspec(align(n)) static const t v
+#else
+    #define DECLARE_ALIGNED(n,t,v)      t v
+    #define DECLARE_ASM_CONST(n,t,v)    static const t v
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+    #define av_malloc_attrib __attribute__((__malloc__))
+#else
+    #define av_malloc_attrib
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,3)
+    #define av_alloc_size(n) __attribute__((alloc_size(n)))
+#else
+    #define av_alloc_size(n)
+#endif
+
+/**
+ * Allocate a block of size bytes with alignment suitable for all
+ * memory accesses (including vectors if available on the CPU).
+ * @param size Size in bytes for the memory block to be allocated.
+ * @return Pointer to the allocated block, NULL if the block cannot
+ * be allocated.
+ * @see av_mallocz()
+ */
+void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Allocate or reallocate a block of memory.
+ * If ptr is NULL and size > 0, allocate a new block. If
+ * size is zero, free the memory block pointed to by ptr.
+ * @param ptr Pointer to a memory block already allocated with
+ * av_malloc(z)() or av_realloc() or NULL.
+ * @param size Size in bytes for the memory block to be allocated or
+ * reallocated.
+ * @return Pointer to a newly reallocated block or NULL if the block
+ * cannot be reallocated or the function is used to free the memory block.
+ * @see av_fast_realloc()
+ */
+void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
+
+/**
+ * Free a memory block which has been allocated with av_malloc(z)() or
+ * av_realloc().
+ * @param ptr Pointer to the memory block which should be freed.
+ * @note ptr = NULL is explicitly allowed.
+ * @note It is recommended that you use av_freep() instead.
+ * @see av_freep()
+ */
+void av_free(void *ptr);
+
+/**
+ * Allocate a block of size bytes with alignment suitable for all
+ * memory accesses (including vectors if available on the CPU) and
+ * zero all the bytes of the block.
+ * @param size Size in bytes for the memory block to be allocated.
+ * @return Pointer to the allocated block, NULL if it cannot be allocated.
+ * @see av_malloc()
+ */
+void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Duplicate the string s.
+ * @param s string to be duplicated
+ * @return Pointer to a newly allocated string containing a
+ * copy of s or NULL if the string cannot be allocated.
+ */
+char *av_strdup(const char *s) av_malloc_attrib;
+
+/**
+ * Free a memory block which has been allocated with av_malloc(z)() or
+ * av_realloc() and set the pointer pointing to it to NULL.
+ * @param ptr Pointer to the pointer to the memory block which should
+ * be freed.
+ * @see av_free()
+ */
+void av_freep(void *ptr);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MEM_H */
diff --git a/make/stub_includes/libav/libavutil/opt.h b/make/stub_includes/libav/libavutil/opt.h
new file mode 100644
index 0000000..1954940
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/opt.h
@@ -0,0 +1,591 @@
+/*
+ * AVOptions
+ * copyright (c) 2005 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_OPT_H
+#define AVUTIL_OPT_H
+
+/**
+ * @file
+ * AVOptions
+ */
+
+#include "rational.h"
+#include "avutil.h"
+#include "dict.h"
+#include "log.h"
+
+/**
+ * @defgroup avoptions AVOptions
+ * @ingroup lavu_data
+ * @{
+ * AVOptions provide a generic system to declare options on arbitrary structs
+ * ("objects"). An option can have a help text, a type and a range of possible
+ * values. Options may then be enumerated, read and written to.
+ *
+ * @section avoptions_implement Implementing AVOptions
+ * This section describes how to add AVOptions capabilities to a struct.
+ *
+ * All AVOptions-related information is stored in an AVClass. Therefore
+ * the first member of the struct must be a pointer to an AVClass describing it.
+ * The option field of the AVClass must be set to a NULL-terminated static array
+ * of AVOptions. Each AVOption must have a non-empty name, a type, a default
+ * value and for number-type AVOptions also a range of allowed values. It must
+ * also declare an offset in bytes from the start of the struct, where the field
+ * associated with this AVOption is located. Other fields in the AVOption struct
+ * should also be set when applicable, but are not required.
+ *
+ * The following example illustrates an AVOptions-enabled struct:
+ * @code
+ * typedef struct test_struct {
+ *     AVClass *class;
+ *     int      int_opt;
+ *     char    *str_opt;
+ *     uint8_t *bin_opt;
+ *     int      bin_len;
+ * } test_struct;
+ *
+ * static const AVOption options[] = {
+ *   { "test_int", "This is a test option of int type.", offsetof(test_struct, int_opt),
+ *     AV_OPT_TYPE_INT, { -1 }, INT_MIN, INT_MAX },
+ *   { "test_str", "This is a test option of string type.", offsetof(test_struct, str_opt),
+ *     AV_OPT_TYPE_STRING },
+ *   { "test_bin", "This is a test option of binary type.", offsetof(test_struct, bin_opt),
+ *     AV_OPT_TYPE_BINARY },
+ *   { NULL },
+ * };
+ *
+ * static const AVClass test_class = {
+ *     .class_name = "test class",
+ *     .item_name  = av_default_item_name,
+ *     .option     = options,
+ *     .version    = LIBAVUTIL_VERSION_INT,
+ * };
+ * @endcode
+ *
+ * Next, when allocating your struct, you must ensure that the AVClass pointer
+ * is set to the correct value. Then, av_opt_set_defaults() must be called to
+ * initialize defaults. After that the struct is ready to be used with the
+ * AVOptions API.
+ *
+ * When cleaning up, you may use the av_opt_free() function to automatically
+ * free all the allocated string and binary options.
+ *
+ * Continuing with the above example:
+ *
+ * @code
+ * test_struct *alloc_test_struct(void)
+ * {
+ *     test_struct *ret = av_malloc(sizeof(*ret));
+ *     ret->class = &test_class;
+ *     av_opt_set_defaults(ret);
+ *     return ret;
+ * }
+ * void free_test_struct(test_struct **foo)
+ * {
+ *     av_opt_free(*foo);
+ *     av_freep(foo);
+ * }
+ * @endcode
+ *
+ * @subsection avoptions_implement_nesting Nesting
+ *      It may happen that an AVOptions-enabled struct contains another
+ *      AVOptions-enabled struct as a member (e.g. AVCodecContext in
+ *      libavcodec exports generic options, while its priv_data field exports
+ *      codec-specific options). In such a case, it is possible to set up the
+ *      parent struct to export a child's options. To do that, simply
+ *      implement AVClass.child_next() and AVClass.child_class_next() in the
+ *      parent struct's AVClass.
+ *      Assuming that the test_struct from above now also contains a
+ *      child_struct field:
+ *
+ *      @code
+ *      typedef struct child_struct {
+ *          AVClass *class;
+ *          int flags_opt;
+ *      } child_struct;
+ *      static const AVOption child_opts[] = {
+ *          { "test_flags", "This is a test option of flags type.",
+ *            offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { 0 }, INT_MIN, INT_MAX },
+ *          { NULL },
+ *      };
+ *      static const AVClass child_class = {
+ *          .class_name = "child class",
+ *          .item_name  = av_default_item_name,
+ *          .option     = child_opts,
+ *          .version    = LIBAVUTIL_VERSION_INT,
+ *      };
+ *
+ *      void *child_next(void *obj, void *prev)
+ *      {
+ *          test_struct *t = obj;
+ *          if (!prev && t->child_struct)
+ *              return t->child_struct;
+ *          return NULL
+ *      }
+ *      const AVClass child_class_next(const AVClass *prev)
+ *      {
+ *          return prev ? NULL : &child_class;
+ *      }
+ *      @endcode
+ *      Putting child_next() and child_class_next() as defined above into
+ *      test_class will now make child_struct's options accessible through
+ *      test_struct (again, proper setup as described above needs to be done on
+ *      child_struct right after it is created).
+ *
+ *      From the above example it might not be clear why both child_next()
+ *      and child_class_next() are needed. The distinction is that child_next()
+ *      iterates over actually existing objects, while child_class_next()
+ *      iterates over all possible child classes. E.g. if an AVCodecContext
+ *      was initialized to use a codec which has private options, then its
+ *      child_next() will return AVCodecContext.priv_data and finish
+ *      iterating. OTOH child_class_next() on AVCodecContext.av_class will
+ *      iterate over all available codecs with private options.
+ *
+ * @subsection avoptions_implement_named_constants Named constants
+ *      It is possible to create named constants for options. Simply set the unit
+ *      field of the option the constants should apply to to a string and
+ *      create the constants themselves as options of type AV_OPT_TYPE_CONST
+ *      with their unit field set to the same string.
+ *      Their default_val field should contain the value of the named
+ *      constant.
+ *      For example, to add some named constants for the test_flags option
+ *      above, put the following into the child_opts array:
+ *      @code
+ *      { "test_flags", "This is a test option of flags type.",
+ *        offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { 0 }, INT_MIN, INT_MAX, "test_unit" },
+ *      { "flag1", "This is a flag with value 16", 0, AV_OPT_TYPE_CONST, { 16 }, 0, 0, "test_unit" },
+ *      @endcode
+ *
+ * @section avoptions_use Using AVOptions
+ * This section deals with accessing options in an AVOptions-enabled struct.
+ * Such structs in Libav are e.g. AVCodecContext in libavcodec or
+ * AVFormatContext in libavformat.
+ *
+ * @subsection avoptions_use_examine Examining AVOptions
+ * The basic functions for examining options are av_opt_next(), which iterates
+ * over all options defined for one object, and av_opt_find(), which searches
+ * for an option with the given name.
+ *
+ * The situation is more complicated with nesting. An AVOptions-enabled struct
+ * may have AVOptions-enabled children. Passing the AV_OPT_SEARCH_CHILDREN flag
+ * to av_opt_find() will make the function search children recursively.
+ *
+ * For enumerating there are basically two cases. The first is when you want to
+ * get all options that may potentially exist on the struct and its children
+ * (e.g.  when constructing documentation). In that case you should call
+ * av_opt_child_class_next() recursively on the parent struct's AVClass.  The
+ * second case is when you have an already initialized struct with all its
+ * children and you want to get all options that can be actually written or read
+ * from it. In that case you should call av_opt_child_next() recursively (and
+ * av_opt_next() on each result).
+ *
+ * @subsection avoptions_use_get_set Reading and writing AVOptions
+ * When setting options, you often have a string read directly from the
+ * user. In such a case, simply passing it to av_opt_set() is enough. For
+ * non-string type options, av_opt_set() will parse the string according to the
+ * option type.
+ *
+ * Similarly av_opt_get() will read any option type and convert it to a string
+ * which will be returned. Do not forget that the string is allocated, so you
+ * have to free it with av_free().
+ *
+ * In some cases it may be more convenient to put all options into an
+ * AVDictionary and call av_opt_set_dict() on it. A specific case of this
+ * are the format/codec open functions in lavf/lavc which take a dictionary
+ * filled with option as a parameter. This allows to set some options
+ * that cannot be set otherwise, since e.g. the input file format is not known
+ * before the file is actually opened.
+ */
+
+enum AVOptionType{
+    AV_OPT_TYPE_FLAGS,
+    AV_OPT_TYPE_INT,
+    AV_OPT_TYPE_INT64,
+    AV_OPT_TYPE_DOUBLE,
+    AV_OPT_TYPE_FLOAT,
+    AV_OPT_TYPE_STRING,
+    AV_OPT_TYPE_RATIONAL,
+    AV_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
+    AV_OPT_TYPE_CONST = 128,
+#if FF_API_OLD_AVOPTIONS
+    FF_OPT_TYPE_FLAGS = 0,
+    FF_OPT_TYPE_INT,
+    FF_OPT_TYPE_INT64,
+    FF_OPT_TYPE_DOUBLE,
+    FF_OPT_TYPE_FLOAT,
+    FF_OPT_TYPE_STRING,
+    FF_OPT_TYPE_RATIONAL,
+    FF_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
+    FF_OPT_TYPE_CONST=128,
+#endif
+};
+
+/**
+ * AVOption
+ */
+typedef struct AVOption {
+    const char *name;
+
+    /**
+     * short English help text
+     * @todo What about other languages?
+     */
+    const char *help;
+
+    /**
+     * The offset relative to the context structure where the option
+     * value is stored. It should be 0 for named constants.
+     */
+    int offset;
+    enum AVOptionType type;
+
+    /**
+     * the default value for scalar options
+     */
+    union {
+        double dbl;
+        const char *str;
+        /* TODO those are unused now */
+        int64_t i64;
+        AVRational q;
+    } default_val;
+    double min;                 ///< minimum valid value for the option
+    double max;                 ///< maximum valid value for the option
+
+    int flags;
+#define AV_OPT_FLAG_ENCODING_PARAM  1   ///< a generic parameter which can be set by the user for muxing or encoding
+#define AV_OPT_FLAG_DECODING_PARAM  2   ///< a generic parameter which can be set by the user for demuxing or decoding
+#define AV_OPT_FLAG_METADATA        4   ///< some data extracted or inserted into the file like title, comment, ...
+#define AV_OPT_FLAG_AUDIO_PARAM     8
+#define AV_OPT_FLAG_VIDEO_PARAM     16
+#define AV_OPT_FLAG_SUBTITLE_PARAM  32
+//FIXME think about enc-audio, ... style flags
+
+    /**
+     * The logical unit to which the option belongs. Non-constant
+     * options and corresponding named constants share the same
+     * unit. May be NULL.
+     */
+    const char *unit;
+} AVOption;
+
+#if FF_API_FIND_OPT
+/**
+ * Look for an option in obj. Look only for the options which
+ * have the flags set as specified in mask and flags (that is,
+ * for which it is the case that opt->flags & mask == flags).
+ *
+ * @param[in] obj a pointer to a struct whose first element is a
+ * pointer to an AVClass
+ * @param[in] name the name of the option to look for
+ * @param[in] unit the unit of the option to look for, or any if NULL
+ * @return a pointer to the option found, or NULL if no option
+ * has been found
+ *
+ * @deprecated use av_opt_find.
+ */
+attribute_deprecated
+const AVOption *av_find_opt(void *obj, const char *name, const char *unit, int mask, int flags);
+#endif
+
+#if FF_API_OLD_AVOPTIONS
+/**
+ * Set the field of obj with the given name to value.
+ *
+ * @param[in] obj A struct whose first element is a pointer to an
+ * AVClass.
+ * @param[in] name the name of the field to set
+ * @param[in] val The value to set. If the field is not of a string
+ * type, then the given string is parsed.
+ * SI postfixes and some named scalars are supported.
+ * If the field is of a numeric type, it has to be a numeric or named
+ * scalar. Behavior with more than one scalar and +- infix operators
+ * is undefined.
+ * If the field is of a flags type, it has to be a sequence of numeric
+ * scalars or named flags separated by '+' or '-'. Prefixing a flag
+ * with '+' causes it to be set without affecting the other flags;
+ * similarly, '-' unsets a flag.
+ * @param[out] o_out if non-NULL put here a pointer to the AVOption
+ * found
+ * @param alloc this parameter is currently ignored
+ * @return 0 if the value has been set, or an AVERROR code in case of
+ * error:
+ * AVERROR_OPTION_NOT_FOUND if no matching option exists
+ * AVERROR(ERANGE) if the value is out of range
+ * AVERROR(EINVAL) if the value is not valid
+ * @deprecated use av_opt_set()
+ */
+attribute_deprecated
+int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out);
+
+attribute_deprecated const AVOption *av_set_double(void *obj, const char *name, double n);
+attribute_deprecated const AVOption *av_set_q(void *obj, const char *name, AVRational n);
+attribute_deprecated const AVOption *av_set_int(void *obj, const char *name, int64_t n);
+
+attribute_deprecated double av_get_double(void *obj, const char *name, const AVOption **o_out);
+attribute_deprecated AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
+attribute_deprecated int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
+attribute_deprecated const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len);
+attribute_deprecated const AVOption *av_next_option(void *obj, const AVOption *last);
+#endif
+
+/**
+ * Show the obj options.
+ *
+ * @param req_flags requested flags for the options to show. Show only the
+ * options for which it is opt->flags & req_flags.
+ * @param rej_flags rejected flags for the options to show. Show only the
+ * options for which it is !(opt->flags & req_flags).
+ * @param av_log_obj log context to use for showing the options
+ */
+int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags);
+
+/**
+ * Set the values of all AVOption fields to their default values.
+ *
+ * @param s an AVOption-enabled struct (its first member must be a pointer to AVClass)
+ */
+void av_opt_set_defaults(void *s);
+
+#if FF_API_OLD_AVOPTIONS
+attribute_deprecated
+void av_opt_set_defaults2(void *s, int mask, int flags);
+#endif
+
+/**
+ * Parse the key/value pairs list in opts. For each key/value pair
+ * found, stores the value in the field in ctx that is named like the
+ * key. ctx must be an AVClass context, storing is done using
+ * AVOptions.
+ *
+ * @param key_val_sep a 0-terminated list of characters used to
+ * separate key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @return the number of successfully set key/value pairs, or a negative
+ * value corresponding to an AVERROR code in case of error:
+ * AVERROR(EINVAL) if opts cannot be parsed,
+ * the error code issued by av_set_string3() if a key/value pair
+ * cannot be set
+ */
+int av_set_options_string(void *ctx, const char *opts,
+                          const char *key_val_sep, const char *pairs_sep);
+
+/**
+ * Free all string and binary options in obj.
+ */
+void av_opt_free(void *obj);
+
+/**
+ * Check whether a particular flag is set in a flags field.
+ *
+ * @param field_name the name of the flag field option
+ * @param flag_name the name of the flag to check
+ * @return non-zero if the flag is set, zero if the flag isn't set,
+ *         isn't of the right type, or the flags field doesn't exist.
+ */
+int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name);
+
+/*
+ * Set all the options from a given dictionary on an object.
+ *
+ * @param obj a struct whose first element is a pointer to AVClass
+ * @param options options to process. This dictionary will be freed and replaced
+ *                by a new one containing all options not found in obj.
+ *                Of course this new dictionary needs to be freed by caller
+ *                with av_dict_free().
+ *
+ * @return 0 on success, a negative AVERROR if some option was found in obj,
+ *         but could not be set.
+ *
+ * @see av_dict_copy()
+ */
+int av_opt_set_dict(void *obj, struct AVDictionary **options);
+
+/**
+ * @defgroup opt_eval_funcs Evaluating option strings
+ * @{
+ * This group of functions can be used to evaluate option strings
+ * and get numbers out of them. They do the same thing as av_opt_set(),
+ * except the result is written into the caller-supplied pointer.
+ *
+ * @param obj a struct whose first element is a pointer to AVClass.
+ * @param o an option for which the string is to be evaluated.
+ * @param val string to be evaluated.
+ * @param *_out value of the string will be written here.
+ *
+ * @return 0 on success, a negative number on failure.
+ */
+int av_opt_eval_flags (void *obj, const AVOption *o, const char *val, int        *flags_out);
+int av_opt_eval_int   (void *obj, const AVOption *o, const char *val, int        *int_out);
+int av_opt_eval_int64 (void *obj, const AVOption *o, const char *val, int64_t    *int64_out);
+int av_opt_eval_float (void *obj, const AVOption *o, const char *val, float      *float_out);
+int av_opt_eval_double(void *obj, const AVOption *o, const char *val, double     *double_out);
+int av_opt_eval_q     (void *obj, const AVOption *o, const char *val, AVRational *q_out);
+/**
+ * @}
+ */
+
+#define AV_OPT_SEARCH_CHILDREN   0x0001 /**< Search in possible children of the
+                                             given object first. */
+/**
+ *  The obj passed to av_opt_find() is fake -- only a double pointer to AVClass
+ *  instead of a required pointer to a struct containing AVClass. This is
+ *  useful for searching for options without needing to allocate the corresponding
+ *  object.
+ */
+#define AV_OPT_SEARCH_FAKE_OBJ   0x0002
+
+/**
+ * Look for an option in an object. Consider only options which
+ * have all the specified flags set.
+ *
+ * @param[in] obj A pointer to a struct whose first element is a
+ *                pointer to an AVClass.
+ *                Alternatively a double pointer to an AVClass, if
+ *                AV_OPT_SEARCH_FAKE_OBJ search flag is set.
+ * @param[in] name The name of the option to look for.
+ * @param[in] unit When searching for named constants, name of the unit
+ *                 it belongs to.
+ * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG).
+ * @param search_flags A combination of AV_OPT_SEARCH_*.
+ *
+ * @return A pointer to the option found, or NULL if no option
+ *         was found.
+ *
+ * @note Options found with AV_OPT_SEARCH_CHILDREN flag may not be settable
+ * directly with av_set_string3(). Use special calls which take an options
+ * AVDictionary (e.g. avformat_open_input()) to set options found with this
+ * flag.
+ */
+const AVOption *av_opt_find(void *obj, const char *name, const char *unit,
+                            int opt_flags, int search_flags);
+
+/**
+ * Look for an option in an object. Consider only options which
+ * have all the specified flags set.
+ *
+ * @param[in] obj A pointer to a struct whose first element is a
+ *                pointer to an AVClass.
+ *                Alternatively a double pointer to an AVClass, if
+ *                AV_OPT_SEARCH_FAKE_OBJ search flag is set.
+ * @param[in] name The name of the option to look for.
+ * @param[in] unit When searching for named constants, name of the unit
+ *                 it belongs to.
+ * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG).
+ * @param search_flags A combination of AV_OPT_SEARCH_*.
+ * @param[out] target_obj if non-NULL, an object to which the option belongs will be
+ * written here. It may be different from obj if AV_OPT_SEARCH_CHILDREN is present
+ * in search_flags. This parameter is ignored if search_flags contain
+ * AV_OPT_SEARCH_FAKE_OBJ.
+ *
+ * @return A pointer to the option found, or NULL if no option
+ *         was found.
+ */
+const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
+                             int opt_flags, int search_flags, void **target_obj);
+
+/**
+ * Iterate over all AVOptions belonging to obj.
+ *
+ * @param obj an AVOptions-enabled struct or a double pointer to an
+ *            AVClass describing it.
+ * @param prev result of the previous call to av_opt_next() on this object
+ *             or NULL
+ * @return next AVOption or NULL
+ */
+const AVOption *av_opt_next(void *obj, const AVOption *prev);
+
+/**
+ * Iterate over AVOptions-enabled children of obj.
+ *
+ * @param prev result of a previous call to this function or NULL
+ * @return next AVOptions-enabled child or NULL
+ */
+void *av_opt_child_next(void *obj, void *prev);
+
+/**
+ * Iterate over potential AVOptions-enabled children of parent.
+ *
+ * @param prev result of a previous call to this function or NULL
+ * @return AVClass corresponding to next potential child or NULL
+ */
+const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev);
+
+/**
+ * @defgroup opt_set_funcs Option setting functions
+ * @{
+ * Those functions set the field of obj with the given name to value.
+ *
+ * @param[in] obj A struct whose first element is a pointer to an AVClass.
+ * @param[in] name the name of the field to set
+ * @param[in] val The value to set. In case of av_opt_set() if the field is not
+ * of a string type, then the given string is parsed.
+ * SI postfixes and some named scalars are supported.
+ * If the field is of a numeric type, it has to be a numeric or named
+ * scalar. Behavior with more than one scalar and +- infix operators
+ * is undefined.
+ * If the field is of a flags type, it has to be a sequence of numeric
+ * scalars or named flags separated by '+' or '-'. Prefixing a flag
+ * with '+' causes it to be set without affecting the other flags;
+ * similarly, '-' unsets a flag.
+ * @param search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN
+ * is passed here, then the option may be set on a child of obj.
+ *
+ * @return 0 if the value has been set, or an AVERROR code in case of
+ * error:
+ * AVERROR_OPTION_NOT_FOUND if no matching option exists
+ * AVERROR(ERANGE) if the value is out of range
+ * AVERROR(EINVAL) if the value is not valid
+ */
+int av_opt_set       (void *obj, const char *name, const char *val, int search_flags);
+int av_opt_set_int   (void *obj, const char *name, int64_t     val, int search_flags);
+int av_opt_set_double(void *obj, const char *name, double      val, int search_flags);
+int av_opt_set_q     (void *obj, const char *name, AVRational  val, int search_flags);
+/**
+ * @}
+ */
+
+/**
+ * @defgroup opt_get_funcs Option getting functions
+ * @{
+ * Those functions get a value of the option with the given name from an object.
+ *
+ * @param[in] obj a struct whose first element is a pointer to an AVClass.
+ * @param[in] name name of the option to get.
+ * @param[in] search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN
+ * is passed here, then the option may be found in a child of obj.
+ * @param[out] out_val value of the option will be written here
+ * @return 0 on success, a negative error code otherwise
+ */
+/**
+ * @note the returned string will av_malloc()ed and must be av_free()ed by the caller
+ */
+int av_opt_get       (void *obj, const char *name, int search_flags, uint8_t   **out_val);
+int av_opt_get_int   (void *obj, const char *name, int search_flags, int64_t    *out_val);
+int av_opt_get_double(void *obj, const char *name, int search_flags, double     *out_val);
+int av_opt_get_q     (void *obj, const char *name, int search_flags, AVRational *out_val);
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_OPT_H */
diff --git a/make/stub_includes/libav/libavutil/parseutils.h b/make/stub_includes/libav/libavutil/parseutils.h
new file mode 100644
index 0000000..0844abb
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/parseutils.h
@@ -0,0 +1,124 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PARSEUTILS_H
+#define AVUTIL_PARSEUTILS_H
+
+#include <time.h>
+
+#include "rational.h"
+
+/**
+ * @file
+ * misc parsing utilities
+ */
+
+/**
+ * Parse str and put in width_ptr and height_ptr the detected values.
+ *
+ * @param[in,out] width_ptr pointer to the variable which will contain the detected
+ * width value
+ * @param[in,out] height_ptr pointer to the variable which will contain the detected
+ * height value
+ * @param[in] str the string to parse: it has to be a string in the format
+ * width x height or a valid video size abbreviation.
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str);
+
+/**
+ * Parse str and store the detected values in *rate.
+ *
+ * @param[in,out] rate pointer to the AVRational which will contain the detected
+ * frame rate
+ * @param[in] str the string to parse: it has to be a string in the format
+ * rate_num / rate_den, a float number or a valid video rate abbreviation
+ * @return >= 0 on success, a negative error code otherwise
+ */
+int av_parse_video_rate(AVRational *rate, const char *str);
+
+/**
+ * Put the RGBA values that correspond to color_string in rgba_color.
+ *
+ * @param color_string a string specifying a color. It can be the name of
+ * a color (case insensitive match) or a [0x|#]RRGGBB[AA] sequence,
+ * possibly followed by "@" and a string representing the alpha
+ * component.
+ * The alpha component may be a string composed by "0x" followed by an
+ * hexadecimal number or a decimal number between 0.0 and 1.0, which
+ * represents the opacity value (0x00/0.0 means completely transparent,
+ * 0xff/1.0 completely opaque).
+ * If the alpha component is not specified then 0xff is assumed.
+ * The string "random" will result in a random color.
+ * @param slen length of the initial part of color_string containing the
+ * color. It can be set to -1 if color_string is a null terminated string
+ * containing nothing else than the color.
+ * @return >= 0 in case of success, a negative value in case of
+ * failure (for example if color_string cannot be parsed).
+ */
+int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen,
+                   void *log_ctx);
+
+/**
+ * Parse timestr and return in *time a corresponding number of
+ * microseconds.
+ *
+ * @param timeval puts here the number of microseconds corresponding
+ * to the string in timestr. If the string represents a duration, it
+ * is the number of microseconds contained in the time interval.  If
+ * the string is a date, is the number of microseconds since 1st of
+ * January, 1970 up to the time of the parsed date.  If timestr cannot
+ * be successfully parsed, set *time to INT64_MIN.
+
+ * @param timestr a string representing a date or a duration.
+ * - If a date the syntax is:
+ * @code
+ * [{YYYY-MM-DD|YYYYMMDD}[T|t| ]]{{HH[:MM[:SS[.m...]]]}|{HH[MM[SS[.m...]]]}}[Z]
+ * now
+ * @endcode
+ * If the value is "now" it takes the current time.
+ * Time is local time unless Z is appended, in which case it is
+ * interpreted as UTC.
+ * If the year-month-day part is not specified it takes the current
+ * year-month-day.
+ * - If a duration the syntax is:
+ * @code
+ * [-]HH[:MM[:SS[.m...]]]
+ * [-]S+[.m...]
+ * @endcode
+ * @param duration flag which tells how to interpret timestr, if not
+ * zero timestr is interpreted as a duration, otherwise as a date
+ * @return 0 in case of success, a negative value corresponding to an
+ * AVERROR code otherwise
+ */
+int av_parse_time(int64_t *timeval, const char *timestr, int duration);
+
+/**
+ * Attempt to find a specific tag in a URL.
+ *
+ * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
+ * Return 1 if found.
+ */
+int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info);
+
+/**
+ * Convert the decomposed UTC time in tm to a time_t value.
+ */
+time_t av_timegm(struct tm *tm);
+
+#endif /* AVUTIL_PARSEUTILS_H */
diff --git a/make/stub_includes/libav/libavutil/pixdesc.h b/make/stub_includes/libav/libavutil/pixdesc.h
new file mode 100644
index 0000000..b5972c7
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/pixdesc.h
@@ -0,0 +1,177 @@
+/*
+ * pixel format descriptor
+ * Copyright (c) 2009 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PIXDESC_H
+#define AVUTIL_PIXDESC_H
+
+#include <inttypes.h>
+#include "pixfmt.h"
+
+typedef struct AVComponentDescriptor{
+    uint16_t plane        :2;            ///< which of the 4 planes contains the component
+
+    /**
+     * Number of elements between 2 horizontally consecutive pixels minus 1.
+     * Elements are bits for bitstream formats, bytes otherwise.
+     */
+    uint16_t step_minus1  :3;
+
+    /**
+     * Number of elements before the component of the first pixel plus 1.
+     * Elements are bits for bitstream formats, bytes otherwise.
+     */
+    uint16_t offset_plus1 :3;
+    uint16_t shift        :3;            ///< number of least significant bits that must be shifted away to get the value
+    uint16_t depth_minus1 :4;            ///< number of bits in the component minus 1
+}AVComponentDescriptor;
+
+/**
+ * Descriptor that unambiguously describes how the bits of a pixel are
+ * stored in the up to 4 data planes of an image. It also stores the
+ * subsampling factors and number of components.
+ *
+ * @note This is separate of the colorspace (RGB, YCbCr, YPbPr, JPEG-style YUV
+ *       and all the YUV variants) AVPixFmtDescriptor just stores how values
+ *       are stored not what these values represent.
+ */
+typedef struct AVPixFmtDescriptor{
+    const char *name;
+    uint8_t nb_components;      ///< The number of components each pixel has, (1-4)
+
+    /**
+     * Amount to shift the luma width right to find the chroma width.
+     * For YV12 this is 1 for example.
+     * chroma_width = -((-luma_width) >> log2_chroma_w)
+     * The note above is needed to ensure rounding up.
+     * This value only refers to the chroma components.
+     */
+    uint8_t log2_chroma_w;      ///< chroma_width = -((-luma_width )>>log2_chroma_w)
+
+    /**
+     * Amount to shift the luma height right to find the chroma height.
+     * For YV12 this is 1 for example.
+     * chroma_height= -((-luma_height) >> log2_chroma_h)
+     * The note above is needed to ensure rounding up.
+     * This value only refers to the chroma components.
+     */
+    uint8_t log2_chroma_h;
+    uint8_t flags;
+
+    /**
+     * Parameters that describe how pixels are packed. If the format
+     * has chroma components, they must be stored in comp[1] and
+     * comp[2].
+     */
+    AVComponentDescriptor comp[4];
+}AVPixFmtDescriptor;
+
+#define PIX_FMT_BE        1 ///< Pixel format is big-endian.
+#define PIX_FMT_PAL       2 ///< Pixel format has a palette in data[1], values are indexes in this palette.
+#define PIX_FMT_BITSTREAM 4 ///< All values of a component are bit-wise packed end to end.
+#define PIX_FMT_HWACCEL   8 ///< Pixel format is an HW accelerated format.
+#define PIX_FMT_PLANAR   16 ///< At least one pixel component is not in the first data plane
+#define PIX_FMT_RGB      32 ///< The pixel format contains RGB-like data (as opposed to YUV/grayscale)
+
+/**
+ * The array of all the pixel format descriptors.
+ */
+extern const AVPixFmtDescriptor av_pix_fmt_descriptors[];
+
+/**
+ * Read a line from an image, and write the values of the
+ * pixel format component c to dst.
+ *
+ * @param data the array containing the pointers to the planes of the image
+ * @param linesize the array containing the linesizes of the image
+ * @param desc the pixel format descriptor for the image
+ * @param x the horizontal coordinate of the first pixel to read
+ * @param y the vertical coordinate of the first pixel to read
+ * @param w the width of the line to read, that is the number of
+ * values to write to dst
+ * @param read_pal_component if not zero and the format is a paletted
+ * format writes the values corresponding to the palette
+ * component c in data[1] to dst, rather than the palette indexes in
+ * data[0]. The behavior is undefined if the format is not paletted.
+ */
+void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],
+                        const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component);
+
+/**
+ * Write the values from src to the pixel format component c of an
+ * image line.
+ *
+ * @param src array containing the values to write
+ * @param data the array containing the pointers to the planes of the
+ * image to write into. It is supposed to be zeroed.
+ * @param linesize the array containing the linesizes of the image
+ * @param desc the pixel format descriptor for the image
+ * @param x the horizontal coordinate of the first pixel to write
+ * @param y the vertical coordinate of the first pixel to write
+ * @param w the width of the line to write, that is the number of
+ * values to write to the image line
+ */
+void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4],
+                         const AVPixFmtDescriptor *desc, int x, int y, int c, int w);
+
+/**
+ * Return the pixel format corresponding to name.
+ *
+ * If there is no pixel format with name name, then looks for a
+ * pixel format with the name corresponding to the native endian
+ * format of name.
+ * For example in a little-endian system, first looks for "gray16",
+ * then for "gray16le".
+ *
+ * Finally if no pixel format has been found, returns PIX_FMT_NONE.
+ */
+enum PixelFormat av_get_pix_fmt(const char *name);
+
+/**
+ * Return the short name for a pixel format, NULL in case pix_fmt is
+ * unknown.
+ *
+ * @see av_get_pix_fmt(), av_get_pix_fmt_string()
+ */
+const char *av_get_pix_fmt_name(enum PixelFormat pix_fmt);
+
+/**
+ * Print in buf the string corresponding to the pixel format with
+ * number pix_fmt, or an header if pix_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param pix_fmt the number of the pixel format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ */
+char *av_get_pix_fmt_string (char *buf, int buf_size, enum PixelFormat pix_fmt);
+
+/**
+ * Return the number of bits per pixel used by the pixel format
+ * described by pixdesc.
+ *
+ * The returned number of bits refers to the number of bits actually
+ * used for storing the pixel information, that is padding bits are
+ * not counted.
+ */
+int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc);
+
+#endif /* AVUTIL_PIXDESC_H */
diff --git a/make/stub_includes/libav/libavutil/pixfmt.h b/make/stub_includes/libav/libavutil/pixfmt.h
new file mode 100644
index 0000000..bd898bd
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/pixfmt.h
@@ -0,0 +1,198 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PIXFMT_H
+#define AVUTIL_PIXFMT_H
+
+/**
+ * @file
+ * pixel format definitions
+ *
+ */
+
+#include "libavutil/avconfig.h"
+
+/**
+ * Pixel format.
+ *
+ * @note
+ * PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA
+ * color is put together as:
+ *  (A << 24) | (R << 16) | (G << 8) | B
+ * This is stored as BGRA on little-endian CPU architectures and ARGB on
+ * big-endian CPUs.
+ *
+ * @par
+ * When the pixel format is palettized RGB (PIX_FMT_PAL8), the palettized
+ * image data is stored in AVFrame.data[0]. The palette is transported in
+ * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is
+ * formatted the same as in PIX_FMT_RGB32 described above (i.e., it is
+ * also endian-specific). Note also that the individual RGB palette
+ * components stored in AVFrame.data[1] should be in the range 0..255.
+ * This is important as many custom PAL8 video codecs that were designed
+ * to run on the IBM VGA graphics adapter use 6-bit palette components.
+ *
+ * @par
+ * For all the 8bit per pixel formats, an RGB32 palette is in data[1] like
+ * for pal8. This palette is filled in automatically by the function
+ * allocating the picture.
+ *
+ * @note
+ * make sure that all newly added big endian formats have pix_fmt&1==1
+ * and that all newly added little endian formats have pix_fmt&1==0
+ * this allows simpler detection of big vs little endian.
+ */
+enum PixelFormat {
+    PIX_FMT_NONE= -1,
+    PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+    PIX_FMT_YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+    PIX_FMT_RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+    PIX_FMT_BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+    PIX_FMT_YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+    PIX_FMT_YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+    PIX_FMT_YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+    PIX_FMT_YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+    PIX_FMT_GRAY8,     ///<        Y        ,  8bpp
+    PIX_FMT_MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+    PIX_FMT_MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+    PIX_FMT_PAL8,      ///< 8 bit with PIX_FMT_RGB32 palette
+    PIX_FMT_YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV420P and setting color_range
+    PIX_FMT_YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV422P and setting color_range
+    PIX_FMT_YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of PIX_FMT_YUV444P and setting color_range
+    PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
+    PIX_FMT_XVMC_MPEG2_IDCT,
+    PIX_FMT_UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+    PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+    PIX_FMT_BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+    PIX_FMT_BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+    PIX_FMT_RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+    PIX_FMT_RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+    PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+    PIX_FMT_NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+    PIX_FMT_NV21,      ///< as above, but U and V bytes are swapped
+
+    PIX_FMT_ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+    PIX_FMT_RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+    PIX_FMT_ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+    PIX_FMT_BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+    PIX_FMT_GRAY16BE,  ///<        Y        , 16bpp, big-endian
+    PIX_FMT_GRAY16LE,  ///<        Y        , 16bpp, little-endian
+    PIX_FMT_YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+    PIX_FMT_YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of PIX_FMT_YUV440P and setting color_range
+    PIX_FMT_YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+    PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+    PIX_FMT_RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+    PIX_FMT_RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+    PIX_FMT_RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+    PIX_FMT_RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+
+    PIX_FMT_BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+    PIX_FMT_BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+    PIX_FMT_BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+    PIX_FMT_BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+
+    PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+    PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+    PIX_FMT_VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+
+    PIX_FMT_YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_VDPAU_MPEG4,  ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+    PIX_FMT_DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+    PIX_FMT_RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+    PIX_FMT_RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+    PIX_FMT_BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+    PIX_FMT_BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+    PIX_FMT_Y400A,     ///< 8bit gray, 8bit alpha
+    PIX_FMT_BGR48BE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+    PIX_FMT_BGR48LE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
+    PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+    PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+    PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+    PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+    PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+    PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+    PIX_FMT_VDA_VLD,    ///< hardware decoding through VDA
+    PIX_FMT_GBRP,      ///< planar GBR 4:4:4 24bpp
+    PIX_FMT_GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
+    PIX_FMT_GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
+    PIX_FMT_GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
+    PIX_FMT_GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
+    PIX_FMT_GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
+    PIX_FMT_GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+    PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
+};
+
+#if AV_HAVE_BIGENDIAN
+#   define PIX_FMT_NE(be, le) PIX_FMT_##be
+#else
+#   define PIX_FMT_NE(be, le) PIX_FMT_##le
+#endif
+
+#define PIX_FMT_RGB32   PIX_FMT_NE(ARGB, BGRA)
+#define PIX_FMT_RGB32_1 PIX_FMT_NE(RGBA, ABGR)
+#define PIX_FMT_BGR32   PIX_FMT_NE(ABGR, RGBA)
+#define PIX_FMT_BGR32_1 PIX_FMT_NE(BGRA, ARGB)
+
+#define PIX_FMT_GRAY16 PIX_FMT_NE(GRAY16BE, GRAY16LE)
+#define PIX_FMT_RGB48  PIX_FMT_NE(RGB48BE,  RGB48LE)
+#define PIX_FMT_RGB565 PIX_FMT_NE(RGB565BE, RGB565LE)
+#define PIX_FMT_RGB555 PIX_FMT_NE(RGB555BE, RGB555LE)
+#define PIX_FMT_RGB444 PIX_FMT_NE(RGB444BE, RGB444LE)
+#define PIX_FMT_BGR48  PIX_FMT_NE(BGR48BE,  BGR48LE)
+#define PIX_FMT_BGR565 PIX_FMT_NE(BGR565BE, BGR565LE)
+#define PIX_FMT_BGR555 PIX_FMT_NE(BGR555BE, BGR555LE)
+#define PIX_FMT_BGR444 PIX_FMT_NE(BGR444BE, BGR444LE)
+
+#define PIX_FMT_YUV420P9  PIX_FMT_NE(YUV420P9BE , YUV420P9LE)
+#define PIX_FMT_YUV422P9  PIX_FMT_NE(YUV422P9BE , YUV422P9LE)
+#define PIX_FMT_YUV444P9  PIX_FMT_NE(YUV444P9BE , YUV444P9LE)
+#define PIX_FMT_YUV420P10 PIX_FMT_NE(YUV420P10BE, YUV420P10LE)
+#define PIX_FMT_YUV422P10 PIX_FMT_NE(YUV422P10BE, YUV422P10LE)
+#define PIX_FMT_YUV444P10 PIX_FMT_NE(YUV444P10BE, YUV444P10LE)
+#define PIX_FMT_YUV420P16 PIX_FMT_NE(YUV420P16BE, YUV420P16LE)
+#define PIX_FMT_YUV422P16 PIX_FMT_NE(YUV422P16BE, YUV422P16LE)
+#define PIX_FMT_YUV444P16 PIX_FMT_NE(YUV444P16BE, YUV444P16LE)
+
+#define PIX_FMT_GBRP9     PIX_FMT_NE(GBRP9BE ,    GBRP9LE)
+#define PIX_FMT_GBRP10    PIX_FMT_NE(GBRP10BE,    GBRP10LE)
+#define PIX_FMT_GBRP16    PIX_FMT_NE(GBRP16BE,    GBRP16LE)
+
+#endif /* AVUTIL_PIXFMT_H */
diff --git a/make/stub_includes/libav/libavutil/random_seed.h b/make/stub_includes/libav/libavutil/random_seed.h
new file mode 100644
index 0000000..b1fad13
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/random_seed.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier at gmail.com>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_RANDOM_SEED_H
+#define AVUTIL_RANDOM_SEED_H
+
+#include <stdint.h>
+/**
+ * @addtogroup lavu_crypto
+ * @{
+ */
+
+/**
+ * Get random data.
+ *
+ * This function can be called repeatedly to generate more random bits
+ * as needed. It is generally quite slow, and usually used to seed a
+ * PRNG.  As it uses /dev/urandom and /dev/random, the quality of the
+ * returned random data depends on the platform.
+ */
+uint32_t av_get_random_seed(void);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_RANDOM_SEED_H */
diff --git a/make/stub_includes/libav/libavutil/rational.h b/make/stub_includes/libav/libavutil/rational.h
new file mode 100644
index 0000000..0ec18ec
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/rational.h
@@ -0,0 +1,144 @@
+/*
+ * rational numbers
+ * Copyright (c) 2003 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * rational numbers
+ * @author Michael Niedermayer <michaelni at gmx.at>
+ */
+
+#ifndef AVUTIL_RATIONAL_H
+#define AVUTIL_RATIONAL_H
+
+#include <stdint.h>
+#include <limits.h>
+#include "attributes.h"
+
+/**
+ * @addtogroup lavu_math
+ * @{
+ */
+
+/**
+ * rational number numerator/denominator
+ */
+typedef struct AVRational{
+    int num; ///< numerator
+    int den; ///< denominator
+} AVRational;
+
+/**
+ * Compare two rationals.
+ * @param a first rational
+ * @param b second rational
+ * @return 0 if a==b, 1 if a>b, -1 if a<b, and INT_MIN if one of the
+ * values is of the form 0/0
+ */
+static inline int av_cmp_q(AVRational a, AVRational b){
+    const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den;
+
+    if(tmp) return ((tmp ^ a.den ^ b.den)>>63)|1;
+    else if(b.den && a.den) return 0;
+    else if(a.num && b.num) return (a.num>>31) - (b.num>>31);
+    else                    return INT_MIN;
+}
+
+/**
+ * Convert rational to double.
+ * @param a rational to convert
+ * @return (double) a
+ */
+static inline double av_q2d(AVRational a){
+    return a.num / (double) a.den;
+}
+
+/**
+ * Reduce a fraction.
+ * This is useful for framerate calculations.
+ * @param dst_num destination numerator
+ * @param dst_den destination denominator
+ * @param num source numerator
+ * @param den source denominator
+ * @param max the maximum allowed for dst_num & dst_den
+ * @return 1 if exact, 0 otherwise
+ */
+int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max);
+
+/**
+ * Multiply two rationals.
+ * @param b first rational
+ * @param c second rational
+ * @return b*c
+ */
+AVRational av_mul_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Divide one rational by another.
+ * @param b first rational
+ * @param c second rational
+ * @return b/c
+ */
+AVRational av_div_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Add two rationals.
+ * @param b first rational
+ * @param c second rational
+ * @return b+c
+ */
+AVRational av_add_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Subtract one rational from another.
+ * @param b first rational
+ * @param c second rational
+ * @return b-c
+ */
+AVRational av_sub_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Convert a double precision floating point number to a rational.
+ * inf is expressed as {1,0} or {-1,0} depending on the sign.
+ *
+ * @param d double to convert
+ * @param max the maximum allowed numerator and denominator
+ * @return (AVRational) d
+ */
+AVRational av_d2q(double d, int max) av_const;
+
+/**
+ * @return 1 if q1 is nearer to q than q2, -1 if q2 is nearer
+ * than q1, 0 if they have the same distance.
+ */
+int av_nearer_q(AVRational q, AVRational q1, AVRational q2);
+
+/**
+ * Find the nearest value in q_list to q.
+ * @param q_list an array of rationals terminated by {0, 0}
+ * @return the index of the nearest value found in the array
+ */
+int av_find_nearest_q_idx(AVRational q, const AVRational* q_list);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_RATIONAL_H */
diff --git a/make/stub_includes/libav/libavutil/samplefmt.h b/make/stub_includes/libav/libavutil/samplefmt.h
new file mode 100644
index 0000000..b671556
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/samplefmt.h
@@ -0,0 +1,148 @@
+/*
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SAMPLEFMT_H
+#define AVUTIL_SAMPLEFMT_H
+
+#include "avutil.h"
+
+/**
+ * all in native-endian format
+ */
+enum AVSampleFormat {
+    AV_SAMPLE_FMT_NONE = -1,
+    AV_SAMPLE_FMT_U8,          ///< unsigned 8 bits
+    AV_SAMPLE_FMT_S16,         ///< signed 16 bits
+    AV_SAMPLE_FMT_S32,         ///< signed 32 bits
+    AV_SAMPLE_FMT_FLT,         ///< float
+    AV_SAMPLE_FMT_DBL,         ///< double
+
+    AV_SAMPLE_FMT_U8P,         ///< unsigned 8 bits, planar
+    AV_SAMPLE_FMT_S16P,        ///< signed 16 bits, planar
+    AV_SAMPLE_FMT_S32P,        ///< signed 32 bits, planar
+    AV_SAMPLE_FMT_FLTP,        ///< float, planar
+    AV_SAMPLE_FMT_DBLP,        ///< double, planar
+
+    AV_SAMPLE_FMT_NB           ///< Number of sample formats. DO NOT USE if linking dynamically
+};
+
+/**
+ * Return the name of sample_fmt, or NULL if sample_fmt is not
+ * recognized.
+ */
+const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt);
+
+/**
+ * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE
+ * on error.
+ */
+enum AVSampleFormat av_get_sample_fmt(const char *name);
+
+/**
+ * Generate a string corresponding to the sample format with
+ * sample_fmt, or a header if sample_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param sample_fmt the number of the sample format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ * @return the pointer to the filled buffer or NULL if sample_fmt is
+ * unknown or in case of other errors
+ */
+char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt);
+
+#if FF_API_GET_BITS_PER_SAMPLE_FMT
+/**
+ * @deprecated Use av_get_bytes_per_sample() instead.
+ */
+attribute_deprecated
+int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt);
+#endif
+
+/**
+ * Return number of bytes per sample.
+ *
+ * @param sample_fmt the sample format
+ * @return number of bytes per sample or zero if unknown for the given
+ * sample format
+ */
+int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt);
+
+/**
+ * Check if the sample format is planar.
+ *
+ * @param sample_fmt the sample format to inspect
+ * @return 1 if the sample format is planar, 0 if it is interleaved
+ */
+int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt);
+
+/**
+ * Get the required buffer size for the given audio parameters.
+ *
+ * @param[out] linesize calculated linesize, may be NULL
+ * @param nb_channels   the number of channels
+ * @param nb_samples    the number of samples in a single channel
+ * @param sample_fmt    the sample format
+ * @return              required buffer size, or negative error code on failure
+ */
+int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples,
+                               enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Fill channel data pointers and linesize for samples with sample
+ * format sample_fmt.
+ *
+ * The pointers array is filled with the pointers to the samples data:
+ * for planar, set the start point of each channel's data within the buffer,
+ * for packed, set the start point of the entire buffer only.
+ *
+ * The linesize array is filled with the aligned size of each channel's data
+ * buffer for planar layout, or the aligned size of the buffer for all channels
+ * for packed layout.
+ *
+ * @param[out] audio_data  array to be filled with the pointer for each channel
+ * @param[out] linesize    calculated linesize
+ * @param buf              the pointer to a buffer containing the samples
+ * @param nb_channels      the number of channels
+ * @param nb_samples       the number of samples in a single channel
+ * @param sample_fmt       the sample format
+ * @param align            buffer size alignment (1 = no alignment required)
+ * @return                 0 on success or a negative error code on failure
+ */
+int av_samples_fill_arrays(uint8_t **audio_data, int *linesize, uint8_t *buf,
+                           int nb_channels, int nb_samples,
+                           enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Allocate a samples buffer for nb_samples samples, and fill data pointers and
+ * linesize accordingly.
+ * The allocated samples buffer can be freed by using av_freep(&audio_data[0])
+ *
+ * @param[out] audio_data  array to be filled with the pointer for each channel
+ * @param[out] linesize    aligned size for audio buffer(s)
+ * @param nb_channels      number of audio channels
+ * @param nb_samples       number of samples per channel
+ * @param align            buffer size alignment (1 = no alignment required)
+ * @return                 0 on success or a negative error code on failure
+ * @see av_samples_fill_arrays()
+ */
+int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
+                     int nb_samples, enum AVSampleFormat sample_fmt, int align);
+
+#endif /* AVUTIL_SAMPLEFMT_H */
diff --git a/make/stub_includes/libav/libavutil/sha.h b/make/stub_includes/libav/libavutil/sha.h
new file mode 100644
index 0000000..8350954
--- /dev/null
+++ b/make/stub_includes/libav/libavutil/sha.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2007 Michael Niedermayer <michaelni at gmx.at>
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SHA_H
+#define AVUTIL_SHA_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_sha SHA
+ * @ingroup lavu_crypto
+ * @{
+ */
+
+extern const int av_sha_size;
+
+struct AVSHA;
+
+/**
+ * Initialize SHA-1 or SHA-2 hashing.
+ *
+ * @param context pointer to the function context (of size av_sha_size)
+ * @param bits    number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits)
+ * @return        zero if initialization succeeded, -1 otherwise
+ */
+int av_sha_init(struct AVSHA* context, int bits);
+
+/**
+ * Update hash value.
+ *
+ * @param context hash function context
+ * @param data    input data to update hash with
+ * @param len     input data length
+ */
+void av_sha_update(struct AVSHA* context, const uint8_t* data, unsigned int len);
+
+/**
+ * Finish hashing and output digest value.
+ *
+ * @param context hash function context
+ * @param digest  buffer where output digest value is stored
+ */
+void av_sha_final(struct AVSHA* context, uint8_t *digest);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_SHA_H */
diff --git a/make/stub_includes/opengl/GL/glext.h b/make/stub_includes/opengl/GL/glext.h
index 8463940..e5de746 100644
--- a/make/stub_includes/opengl/GL/glext.h
+++ b/make/stub_includes/opengl/GL/glext.h
@@ -6,7 +6,7 @@ extern "C" {
 #endif
 
 /*
-** Copyright (c) 2007-2010 The Khronos Group Inc.
+** Copyright (c) 2007-2012 The Khronos Group Inc.
 ** 
 ** Permission is hereby granted, free of charge, to any person obtaining a
 ** copy of this software and/or associated documentation files (the
@@ -29,9 +29,9 @@ extern "C" {
 */
 
 /* Header file version number, required by OpenGL ABI for Linux */
-/* glext.h last updated $Date: 2010-08-03 01:30:25 -0700 (Tue, 03 Aug 2010) $ */
+/* glext.h last updated $Date: 2012-01-26 02:44:56 -0800 (Thu, 26 Jan 2012) $ */
 /* Current version at http://www.opengl.org/registry/ */
-#define GL_GLEXT_VERSION 64
+#define GL_GLEXT_VERSION 75
 /* Function declaration macros - to move into glplatform.h */
 
 #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
@@ -516,8 +516,8 @@ extern "C" {
 #define GL_MINOR_VERSION                  0x821C
 #define GL_NUM_EXTENSIONS                 0x821D
 #define GL_CONTEXT_FLAGS                  0x821E
-#define GL_DEPTH_BUFFER                   0x8223
-#define GL_STENCIL_BUFFER                 0x8224
+#define GL_DEPTH_BUFFER                   0x8223  // n/a in spec, but other header files
+#define GL_STENCIL_BUFFER                 0x8224  // n/a in spec, but other header files
 #define GL_COMPRESSED_RED                 0x8225
 #define GL_COMPRESSED_RG                  0x8226
 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001
@@ -740,6 +740,8 @@ extern "C" {
 #endif
 
 #ifndef GL_VERSION_3_1
+/* #define GL_SAMPLER_2D_RECT             0x8B63 - we use subsumed GL_ARB_texture_rectangle */
+/* #define GL_SAMPLER_2D_RECT_SHADOW      0x8B64 - we use subsumed GL_ARB_texture_rectangle */
 #define GL_SAMPLER_BUFFER                 0x8DC2
 #define GL_INT_SAMPLER_2D_RECT            0x8DCD
 #define GL_INT_SAMPLER_BUFFER             0x8DD0
@@ -1018,6 +1020,124 @@ extern "C" {
 /* reuse GL_UNDEFINED_VERTEX */
 #endif
 
+#ifndef GL_VERSION_4_2
+/* Reuse tokens from ARB_base_instance (none) */
+/* Reuse tokens from ARB_shading_language_420pack (none) */
+/* Reuse tokens from ARB_transform_feedback_instanced (none) */
+/* Reuse tokens from ARB_compressed_texture_pixel_storage */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_WIDTH */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_HEIGHT */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_DEPTH */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_SIZE */
+/* reuse GL_PACK_COMPRESSED_BLOCK_WIDTH */
+/* reuse GL_PACK_COMPRESSED_BLOCK_HEIGHT */
+/* reuse GL_PACK_COMPRESSED_BLOCK_DEPTH */
+/* reuse GL_PACK_COMPRESSED_BLOCK_SIZE */
+/* Reuse tokens from ARB_conservative_depth (none) */
+/* Reuse tokens from ARB_internalformat_query */
+/* reuse GL_NUM_SAMPLE_COUNTS */
+/* Reuse tokens from ARB_map_buffer_alignment */
+/* reuse GL_MIN_MAP_BUFFER_ALIGNMENT */
+/* Reuse tokens from ARB_shader_atomic_counters */
+/* reuse GL_ATOMIC_COUNTER_BUFFER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_BINDING */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_START */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_SIZE */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER */
+/* reuse GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_VERTEX_ATOMIC_COUNTERS */
+/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS */
+/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS */
+/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTERS */
+/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTERS */
+/* reuse GL_MAX_COMBINED_ATOMIC_COUNTERS */
+/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE */
+/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS */
+/* reuse GL_ACTIVE_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX */
+/* reuse GL_UNSIGNED_INT_ATOMIC_COUNTER */
+/* Reuse tokens from ARB_shader_image_load_store */
+/* reuse GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT */
+/* reuse GL_ELEMENT_ARRAY_BARRIER_BIT */
+/* reuse GL_UNIFORM_BARRIER_BIT */
+/* reuse GL_TEXTURE_FETCH_BARRIER_BIT */
+/* reuse GL_SHADER_IMAGE_ACCESS_BARRIER_BIT */
+/* reuse GL_COMMAND_BARRIER_BIT */
+/* reuse GL_PIXEL_BUFFER_BARRIER_BIT */
+/* reuse GL_TEXTURE_UPDATE_BARRIER_BIT */
+/* reuse GL_BUFFER_UPDATE_BARRIER_BIT */
+/* reuse GL_FRAMEBUFFER_BARRIER_BIT */
+/* reuse GL_TRANSFORM_FEEDBACK_BARRIER_BIT */
+/* reuse GL_ATOMIC_COUNTER_BARRIER_BIT */
+/* reuse GL_ALL_BARRIER_BITS */
+/* reuse GL_MAX_IMAGE_UNITS */
+/* reuse GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS */
+/* reuse GL_IMAGE_BINDING_NAME */
+/* reuse GL_IMAGE_BINDING_LEVEL */
+/* reuse GL_IMAGE_BINDING_LAYERED */
+/* reuse GL_IMAGE_BINDING_LAYER */
+/* reuse GL_IMAGE_BINDING_ACCESS */
+/* reuse GL_IMAGE_1D */
+/* reuse GL_IMAGE_2D */
+/* reuse GL_IMAGE_3D */
+/* reuse GL_IMAGE_2D_RECT */
+/* reuse GL_IMAGE_CUBE */
+/* reuse GL_IMAGE_BUFFER */
+/* reuse GL_IMAGE_1D_ARRAY */
+/* reuse GL_IMAGE_2D_ARRAY */
+/* reuse GL_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_INT_IMAGE_1D */
+/* reuse GL_INT_IMAGE_2D */
+/* reuse GL_INT_IMAGE_3D */
+/* reuse GL_INT_IMAGE_2D_RECT */
+/* reuse GL_INT_IMAGE_CUBE */
+/* reuse GL_INT_IMAGE_BUFFER */
+/* reuse GL_INT_IMAGE_1D_ARRAY */
+/* reuse GL_INT_IMAGE_2D_ARRAY */
+/* reuse GL_INT_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_INT_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_1D */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D */
+/* reuse GL_UNSIGNED_INT_IMAGE_3D */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_RECT */
+/* reuse GL_UNSIGNED_INT_IMAGE_CUBE */
+/* reuse GL_UNSIGNED_INT_IMAGE_BUFFER */
+/* reuse GL_UNSIGNED_INT_IMAGE_1D_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_MAX_IMAGE_SAMPLES */
+/* reuse GL_IMAGE_BINDING_FORMAT */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_TYPE */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS */
+/* reuse GL_MAX_VERTEX_IMAGE_UNIFORMS */
+/* reuse GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS */
+/* reuse GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS */
+/* reuse GL_MAX_GEOMETRY_IMAGE_UNIFORMS */
+/* reuse GL_MAX_FRAGMENT_IMAGE_UNIFORMS */
+/* reuse GL_MAX_COMBINED_IMAGE_UNIFORMS */
+/* Reuse tokens from ARB_shading_language_packing (none) */
+/* Reuse tokens from ARB_texture_storage */
+/* reuse GL_TEXTURE_IMMUTABLE_FORMAT */
+#endif
+
 #ifndef GL_ARB_multitexture
 #define GL_TEXTURE0_ARB                   0x84C0
 #define GL_TEXTURE1_ARB                   0x84C1
@@ -1633,12 +1753,8 @@ extern "C" {
 #define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF
 #define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0
 #define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1
-#ifndef GL_MAX_VARYING_COMPONENTS
-#define GL_MAX_VARYING_COMPONENTS         0x8B4B
-#endif
-#ifndef GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4
-#endif
+/* reuse GL_MAX_VARYING_COMPONENTS */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
 #endif
 
 #ifndef GL_ARB_half_float_vertex
@@ -1735,7 +1851,7 @@ extern "C" {
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46
-/* #define GL_INVALID_INDEX                  0xFFFFFFFFu - manual, due to fixed uint32_t size. GlueGen would create int64_t */
+/* #define GL_INVALID_INDEX               0xFFFFFFFFu - manual, due to fixed uint32_t size. GlueGen would create int64_t */
 #endif
 
 #ifndef GL_ARB_compatibility
@@ -1838,7 +1954,6 @@ extern "C" {
 #ifndef GL_ARB_texture_gather
 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E
 #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F
-#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F
 #endif
 
 #ifndef GL_ARB_texture_query_lod
@@ -2033,7 +2148,7 @@ extern "C" {
 #define GL_GEOMETRY_SHADER_BIT            0x00000004
 #define GL_TESS_CONTROL_SHADER_BIT        0x00000008
 #define GL_TESS_EVALUATION_SHADER_BIT     0x00000010
-#define GL_ALL_SHADER_BITS                0xFFFFFFFF
+/* #define GL_ALL_SHADER_BITS             0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
 #define GL_PROGRAM_SEPARABLE              0x8258
 #define GL_ACTIVE_PROGRAM                 0x8259
 #define GL_PROGRAM_PIPELINE_BINDING       0x825A
@@ -2118,6 +2233,143 @@ extern "C" {
 #ifndef GL_ARB_shader_stencil_export
 #endif
 
+#ifndef GL_ARB_base_instance
+#endif
+
+#ifndef GL_ARB_shading_language_420pack
+#endif
+
+#ifndef GL_ARB_transform_feedback_instanced
+#endif
+
+#ifndef GL_ARB_compressed_texture_pixel_storage
+#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH  0x9127
+#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128
+#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH  0x9129
+#define GL_UNPACK_COMPRESSED_BLOCK_SIZE   0x912A
+#define GL_PACK_COMPRESSED_BLOCK_WIDTH    0x912B
+#define GL_PACK_COMPRESSED_BLOCK_HEIGHT   0x912C
+#define GL_PACK_COMPRESSED_BLOCK_DEPTH    0x912D
+#define GL_PACK_COMPRESSED_BLOCK_SIZE     0x912E
+#endif
+
+#ifndef GL_ARB_conservative_depth
+#endif
+
+#ifndef GL_ARB_internalformat_query
+#define GL_NUM_SAMPLE_COUNTS              0x9380
+#endif
+
+#ifndef GL_ARB_map_buffer_alignment
+#define GL_MIN_MAP_BUFFER_ALIGNMENT       0x90BC
+#endif
+
+#ifndef GL_ARB_shader_atomic_counters
+#define GL_ATOMIC_COUNTER_BUFFER          0x92C0
+#define GL_ATOMIC_COUNTER_BUFFER_BINDING  0x92C1
+#define GL_ATOMIC_COUNTER_BUFFER_START    0x92C2
+#define GL_ATOMIC_COUNTER_BUFFER_SIZE     0x92C3
+#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4
+#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5
+#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB
+#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF
+#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0
+#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1
+#define GL_MAX_VERTEX_ATOMIC_COUNTERS     0x92D2
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS   0x92D5
+#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS   0x92D6
+#define GL_MAX_COMBINED_ATOMIC_COUNTERS   0x92D7
+#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8
+#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC
+#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS  0x92D9
+#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA
+#define GL_UNSIGNED_INT_ATOMIC_COUNTER    0x92DB
+#endif
+
+#ifndef GL_ARB_shader_image_load_store
+#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001
+#define GL_ELEMENT_ARRAY_BARRIER_BIT      0x00000002
+#define GL_UNIFORM_BARRIER_BIT            0x00000004
+#define GL_TEXTURE_FETCH_BARRIER_BIT      0x00000008
+#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020
+#define GL_COMMAND_BARRIER_BIT            0x00000040
+#define GL_PIXEL_BUFFER_BARRIER_BIT       0x00000080
+#define GL_TEXTURE_UPDATE_BARRIER_BIT     0x00000100
+#define GL_BUFFER_UPDATE_BARRIER_BIT      0x00000200
+#define GL_FRAMEBUFFER_BARRIER_BIT        0x00000400
+#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800
+#define GL_ATOMIC_COUNTER_BARRIER_BIT     0x00001000
+/* #define GL_ALL_BARRIER_BITS            0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
+#define GL_MAX_IMAGE_UNITS                0x8F38
+#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39
+#define GL_IMAGE_BINDING_NAME             0x8F3A
+#define GL_IMAGE_BINDING_LEVEL            0x8F3B
+#define GL_IMAGE_BINDING_LAYERED          0x8F3C
+#define GL_IMAGE_BINDING_LAYER            0x8F3D
+#define GL_IMAGE_BINDING_ACCESS           0x8F3E
+#define GL_IMAGE_1D                       0x904C
+#define GL_IMAGE_2D                       0x904D
+#define GL_IMAGE_3D                       0x904E
+#define GL_IMAGE_2D_RECT                  0x904F
+#define GL_IMAGE_CUBE                     0x9050
+#define GL_IMAGE_BUFFER                   0x9051
+#define GL_IMAGE_1D_ARRAY                 0x9052
+#define GL_IMAGE_2D_ARRAY                 0x9053
+#define GL_IMAGE_CUBE_MAP_ARRAY           0x9054
+#define GL_IMAGE_2D_MULTISAMPLE           0x9055
+#define GL_IMAGE_2D_MULTISAMPLE_ARRAY     0x9056
+#define GL_INT_IMAGE_1D                   0x9057
+#define GL_INT_IMAGE_2D                   0x9058
+#define GL_INT_IMAGE_3D                   0x9059
+#define GL_INT_IMAGE_2D_RECT              0x905A
+#define GL_INT_IMAGE_CUBE                 0x905B
+#define GL_INT_IMAGE_BUFFER               0x905C
+#define GL_INT_IMAGE_1D_ARRAY             0x905D
+#define GL_INT_IMAGE_2D_ARRAY             0x905E
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY       0x905F
+#define GL_INT_IMAGE_2D_MULTISAMPLE       0x9060
+#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061
+#define GL_UNSIGNED_INT_IMAGE_1D          0x9062
+#define GL_UNSIGNED_INT_IMAGE_2D          0x9063
+#define GL_UNSIGNED_INT_IMAGE_3D          0x9064
+#define GL_UNSIGNED_INT_IMAGE_2D_RECT     0x9065
+#define GL_UNSIGNED_INT_IMAGE_CUBE        0x9066
+#define GL_UNSIGNED_INT_IMAGE_BUFFER      0x9067
+#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY    0x9068
+#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY    0x9069
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C
+#define GL_MAX_IMAGE_SAMPLES              0x906D
+#define GL_IMAGE_BINDING_FORMAT           0x906E
+#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7
+#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8
+#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9
+#define GL_MAX_VERTEX_IMAGE_UNIFORMS      0x90CA
+#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB
+#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC
+#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS    0x90CD
+#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS    0x90CE
+#define GL_MAX_COMBINED_IMAGE_UNIFORMS    0x90CF
+#endif
+
+#ifndef GL_ARB_shading_language_packing
+#endif
+
+#ifndef GL_ARB_texture_storage
+#define GL_TEXTURE_IMMUTABLE_FORMAT       0x912F
+#endif
+
 #ifndef GL_EXT_abgr
 #define GL_ABGR_EXT                       0x8000
 #endif
@@ -4879,7 +5131,7 @@ extern "C" {
 #define GL_FRAMEBUFFER_BARRIER_BIT_EXT    0x00000400
 #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800
 #define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000
-#define GL_ALL_BARRIER_BITS_EXT           0xFFFFFFFF
+/* #define GL_ALL_BARRIER_BITS_EXT        0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
 #endif
 
 #ifndef GL_EXT_vertex_attrib_64bit
@@ -4903,6 +5155,8 @@ extern "C" {
 #define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B
 #define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C
 #define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D
+#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5E
+#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5F
 #define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44
 #define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV  0x8F45
 #endif
@@ -4997,6 +5251,54 @@ extern "C" {
 #ifndef GL_AMD_transform_feedback3_lines_triangles
 #endif
 
+#ifndef GL_AMD_depth_clamp_separate
+#define GL_DEPTH_CLAMP_NEAR_AMD           0x901E
+#define GL_DEPTH_CLAMP_FAR_AMD            0x901F
+#endif
+
+#ifndef GL_EXT_texture_sRGB_decode
+#define GL_TEXTURE_SRGB_DECODE_EXT        0x8A48
+#define GL_DECODE_EXT                     0x8A49
+#define GL_SKIP_DECODE_EXT                0x8A4A
+#endif
+
+#ifndef GL_NV_texture_multisample
+#define GL_TEXTURE_COVERAGE_SAMPLES_NV    0x9045
+#define GL_TEXTURE_COLOR_SAMPLES_NV       0x9046
+#endif
+
+#ifndef GL_AMD_blend_minmax_factor
+#define GL_FACTOR_MIN_AMD                 0x901C
+#define GL_FACTOR_MAX_AMD                 0x901D
+#endif
+
+#ifndef GL_AMD_sample_positions
+#define GL_SUBSAMPLE_DISTANCE_AMD         0x883F
+#endif
+
+#ifndef GL_EXT_x11_sync_object
+#define GL_SYNC_X11_FENCE_EXT             0x90E1
+#endif
+
+#ifndef GL_AMD_multi_draw_indirect
+#endif
+
+#ifndef GL_EXT_framebuffer_multisample_blit_scaled
+#define GL_SCALED_RESOLVE_FASTEST_EXT     0x90BA
+#define GL_SCALED_RESOLVE_NICEST_EXT      0x90BB
+#endif
+
+#ifndef GL_AMD_pinned_memory
+#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160
+#endif
+
+#ifndef GL_AMD_stencil_operation_extended
+#define GL_SET_AMD                        0x874A
+#define GL_REPLACE_VALUE_AMD              0x874B
+#define GL_STENCIL_OP_VALUE_AMD           0x874C
+#define GL_STENCIL_BACK_OP_VALUE_AMD      0x874D
+#endif
+
 
 /*************************************************************/
 
@@ -5036,7 +5338,7 @@ typedef unsigned short GLhalfNV;
 #include "gl-64bit-types.h"
 
 #ifndef GL_ARB_cl_event
-/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event 
+/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event
 struct _cl_context;
 struct _cl_event;
  */
@@ -5796,7 +6098,7 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divi
 
 #ifndef GL_VERSION_4_1
 #define GL_VERSION_4_1 1
-/* OpenGL 4.1 also reuses entry points from these extensions: */
+/* OpenGL 4.1 reuses entry points from these extensions: */
 /* ARB_ES2_compatibility */
 /* ARB_get_program_binary */
 /* ARB_separate_shader_objects */
@@ -5805,6 +6107,22 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divi
 /* ARB_viewport_array */
 #endif
 
+#ifndef GL_VERSION_4_2
+#define GL_VERSION_4_2 1
+/* OpenGL 4.2 reuses entry points from these extensions: */
+/* ARB_base_instance */
+/* ARB_shading_language_420pack (no entry points) */
+/* ARB_transform_feedback_instanced */
+/* ARB_compressed_texture_pixel_storage (no entry points) */
+/* ARB_conservative_depth (no entry points) */
+/* ARB_internalformat_query */
+/* ARB_map_buffer_alignment (no entry points) */
+/* ARB_shader_atomic_counters */
+/* ARB_shader_image_load_store */
+/* ARB_shading_language_packing (no entry points) */
+/* ARB_texture_storage */
+#endif
+
 #ifndef GL_ARB_multitexture
 #define GL_ARB_multitexture 1
 #ifdef GL_GLEXT_PROTOTYPES
@@ -6730,6 +7048,10 @@ typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum
 typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params);
 #endif
 
+#ifndef GL_ARB_shader_bit_encoding
+#define GL_ARB_shader_bit_encoding 1
+#endif
+
 #ifndef GL_ARB_texture_rgb10_a2ui
 #define GL_ARB_texture_rgb10_a2ui 1
 #endif
@@ -7238,6 +7560,92 @@ typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint locati
 #define GL_ARB_shader_stencil_export 1
 #endif
 
+#ifndef GL_ARB_base_instance
+#define GL_ARB_base_instance 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance);
+GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance);
+GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance);
+#endif
+
+#ifndef GL_ARB_shading_language_420pack
+#define GL_ARB_shading_language_420pack 1
+#endif
+
+#ifndef GL_ARB_transform_feedback_instanced
+#define GL_ARB_transform_feedback_instanced 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei primcount);
+GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei primcount);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei primcount);
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei primcount);
+#endif
+
+#ifndef GL_ARB_compressed_texture_pixel_storage
+#define GL_ARB_compressed_texture_pixel_storage 1
+#endif
+
+#ifndef GL_ARB_conservative_depth
+#define GL_ARB_conservative_depth 1
+#endif
+
+#ifndef GL_ARB_internalformat_query
+#define GL_ARB_internalformat_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+#endif
+
+#ifndef GL_ARB_map_buffer_alignment
+#define GL_ARB_map_buffer_alignment 1
+#endif
+
+#ifndef GL_ARB_shader_atomic_counters
+#define GL_ARB_shader_atomic_counters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_ARB_shader_image_load_store
+#define GL_ARB_shader_image_load_store 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers);
+#endif
+
+#ifndef GL_ARB_shading_language_packing
+#define GL_ARB_shading_language_packing 1
+#endif
+
+#ifndef GL_ARB_texture_storage
+#define GL_ARB_texture_storage 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
 #ifndef GL_EXT_abgr
 #define GL_EXT_abgr 1
 #endif
@@ -8685,8 +9093,8 @@ GLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdoubl
 GLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v);
 GLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
 GLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v);
-GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLuint count, const GLdouble *v);
-GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLsizei count, const GLdouble *v);
+GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLsizei count, const GLfloat *v);
 GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs);
 GLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform);
 GLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
@@ -8750,8 +9158,8 @@ typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint in
 typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
 typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
 typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *v);
 typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
 typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
 typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
@@ -10940,6 +11348,79 @@ typedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, cons
 #define GL_AMD_transform_feedback3_lines_triangles 1
 #endif
 
+#ifndef GL_AMD_depth_clamp_separate
+#define GL_AMD_depth_clamp_separate 1
+#endif
+
+#ifndef GL_EXT_texture_sRGB_decode
+#define GL_EXT_texture_sRGB_decode 1
+#endif
+
+#ifndef GL_NV_texture_multisample
+#define GL_NV_texture_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+#endif
+
+#ifndef GL_AMD_blend_minmax_factor
+#define GL_AMD_blend_minmax_factor 1
+#endif
+
+#ifndef GL_AMD_sample_positions
+#define GL_AMD_sample_positions 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val);
+#endif
+
+#ifndef GL_EXT_x11_sync_object
+#define GL_EXT_x11_sync_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags);
+#endif
+
+#ifndef GL_AMD_multi_draw_indirect
+#define GL_AMD_multi_draw_indirect 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+#endif
+
+#ifndef GL_EXT_framebuffer_multisample_blit_scaled
+#define GL_EXT_framebuffer_multisample_blit_scaled 1
+#endif
+
+#ifndef GL_AMD_pinned_memory
+#define GL_AMD_pinned_memory 1
+#endif
+
+#ifndef GL_AMD_stencil_operation_extended
+#define GL_AMD_stencil_operation_extended 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSTENCILOPVALUEAMDPROC) (GLenum face, GLuint value);
+#endif
+
+
 #ifndef GL_EXT_Cg_shader
 #define GL_CG_VERTEX_SHADER_EXT           0x890E
 #define GL_CG_FRAGMENT_SHADER_EXT         0x890F
diff --git a/make/stub_includes/opengl/GL3/gl3.h b/make/stub_includes/opengl/GL3/gl3.h
index a4109ba..daa0c25 100644
--- a/make/stub_includes/opengl/GL3/gl3.h
+++ b/make/stub_includes/opengl/GL3/gl3.h
@@ -6,7 +6,7 @@ extern "C" {
 #endif
 
 /*
-** Copyright (c) 2007-2010 The Khronos Group Inc.
+** Copyright (c) 2007-2012 The Khronos Group Inc.
 ** 
 ** Permission is hereby granted, free of charge, to any person obtaining a
 ** copy of this software and/or associated documentation files (the
@@ -36,15 +36,15 @@ extern "C" {
  * will probably change slightly as we make sure exactly the right set
  * of interfaces is included.
  *
- * gl3.h last updated on $Date: 2010-08-03 01:30:25 -0700 (Tue, 03 Aug 2010) $
+ * gl3.h last updated on $Date: 2012-01-26 02:57:23 -0800 (Thu, 26 Jan 2012) $
  *
- * RELEASE NOTES - 2010/03/11
+ * RELEASE NOTES - 2012/01/26
  *
  * gl3.h should be placed under a directory 'GL3' and included as
  * '<GL3/gl3.h>'.
  *
- * gl3.h only includes interfaces supported in a OpenGL 3.1 (without
- * GL_ARB_compatibility) or OpenGL 3.2, 3.3, 4.0, or 4.1 core profile
+ * gl3.h is supposed to only include APIs in a OpenGL 3.1 (without
+ * GL_ARB_compatibility) or OpenGL 3.2-4.2 (inclusive) core profile
  * implementation, as well as interfaces for newer ARB extensions which
  * can be supported by the core profile. It does not, and never will
  * include functionality removed from the core profile, such as
@@ -90,6 +90,7 @@ typedef int GLsizei;
 typedef unsigned char GLubyte;
 typedef unsigned short GLushort;
 typedef unsigned int GLuint;
+typedef unsigned short GLhalf;
 typedef float GLfloat;
 typedef float GLclampf;
 typedef double GLdouble;
@@ -607,8 +608,8 @@ typedef void GLvoid;
 #define GL_MINOR_VERSION                  0x821C
 #define GL_NUM_EXTENSIONS                 0x821D
 #define GL_CONTEXT_FLAGS                  0x821E
-#define GL_DEPTH_BUFFER                   0x8223
-#define GL_STENCIL_BUFFER                 0x8224
+#define GL_DEPTH_BUFFER                   0x8223  // n/a in spec, but other header files
+#define GL_STENCIL_BUFFER                 0x8224  // n/a in spec, but other header files
 #define GL_COMPRESSED_RED                 0x8225
 #define GL_COMPRESSED_RG                  0x8226
 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001
@@ -822,6 +823,8 @@ typedef void GLvoid;
 #endif
 
 #ifndef GL_VERSION_3_1
+/* #define GL_SAMPLER_2D_RECT             0x8B63 - we use subsumed GL_ARB_texture_rectangle */
+/* #define GL_SAMPLER_2D_RECT_SHADOW      0x8B64 - we use subsumed GL_ARB_texture_rectangle */
 #define GL_SAMPLER_BUFFER                 0x8DC2
 #define GL_INT_SAMPLER_2D_RECT            0x8DCD
 #define GL_INT_SAMPLER_BUFFER             0x8DD0
@@ -1112,6 +1115,124 @@ typedef void GLvoid;
 /* reuse GL_UNDEFINED_VERTEX */
 #endif
 
+#ifndef GL_VERSION_4_2
+/* Reuse tokens from ARB_base_instance (none) */
+/* Reuse tokens from ARB_shading_language_420pack (none) */
+/* Reuse tokens from ARB_transform_feedback_instanced (none) */
+/* Reuse tokens from ARB_compressed_texture_pixel_storage */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_WIDTH */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_HEIGHT */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_DEPTH */
+/* reuse GL_UNPACK_COMPRESSED_BLOCK_SIZE */
+/* reuse GL_PACK_COMPRESSED_BLOCK_WIDTH */
+/* reuse GL_PACK_COMPRESSED_BLOCK_HEIGHT */
+/* reuse GL_PACK_COMPRESSED_BLOCK_DEPTH */
+/* reuse GL_PACK_COMPRESSED_BLOCK_SIZE */
+/* Reuse tokens from ARB_conservative_depth (none) */
+/* Reuse tokens from ARB_internalformat_query */
+/* reuse GL_NUM_SAMPLE_COUNTS */
+/* Reuse tokens from ARB_map_buffer_alignment */
+/* reuse GL_MIN_MAP_BUFFER_ALIGNMENT */
+/* Reuse tokens from ARB_shader_atomic_counters */
+/* reuse GL_ATOMIC_COUNTER_BUFFER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_BINDING */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_START */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_SIZE */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER */
+/* reuse GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER */
+/* reuse GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_MAX_VERTEX_ATOMIC_COUNTERS */
+/* reuse GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS */
+/* reuse GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS */
+/* reuse GL_MAX_GEOMETRY_ATOMIC_COUNTERS */
+/* reuse GL_MAX_FRAGMENT_ATOMIC_COUNTERS */
+/* reuse GL_MAX_COMBINED_ATOMIC_COUNTERS */
+/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE */
+/* reuse GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS */
+/* reuse GL_ACTIVE_ATOMIC_COUNTER_BUFFERS */
+/* reuse GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX */
+/* reuse GL_UNSIGNED_INT_ATOMIC_COUNTER */
+/* Reuse tokens from ARB_shader_image_load_store */
+/* reuse GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT */
+/* reuse GL_ELEMENT_ARRAY_BARRIER_BIT */
+/* reuse GL_UNIFORM_BARRIER_BIT */
+/* reuse GL_TEXTURE_FETCH_BARRIER_BIT */
+/* reuse GL_SHADER_IMAGE_ACCESS_BARRIER_BIT */
+/* reuse GL_COMMAND_BARRIER_BIT */
+/* reuse GL_PIXEL_BUFFER_BARRIER_BIT */
+/* reuse GL_TEXTURE_UPDATE_BARRIER_BIT */
+/* reuse GL_BUFFER_UPDATE_BARRIER_BIT */
+/* reuse GL_FRAMEBUFFER_BARRIER_BIT */
+/* reuse GL_TRANSFORM_FEEDBACK_BARRIER_BIT */
+/* reuse GL_ATOMIC_COUNTER_BARRIER_BIT */
+/* reuse GL_ALL_BARRIER_BITS */
+/* reuse GL_MAX_IMAGE_UNITS */
+/* reuse GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS */
+/* reuse GL_IMAGE_BINDING_NAME */
+/* reuse GL_IMAGE_BINDING_LEVEL */
+/* reuse GL_IMAGE_BINDING_LAYERED */
+/* reuse GL_IMAGE_BINDING_LAYER */
+/* reuse GL_IMAGE_BINDING_ACCESS */
+/* reuse GL_IMAGE_1D */
+/* reuse GL_IMAGE_2D */
+/* reuse GL_IMAGE_3D */
+/* reuse GL_IMAGE_2D_RECT */
+/* reuse GL_IMAGE_CUBE */
+/* reuse GL_IMAGE_BUFFER */
+/* reuse GL_IMAGE_1D_ARRAY */
+/* reuse GL_IMAGE_2D_ARRAY */
+/* reuse GL_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_INT_IMAGE_1D */
+/* reuse GL_INT_IMAGE_2D */
+/* reuse GL_INT_IMAGE_3D */
+/* reuse GL_INT_IMAGE_2D_RECT */
+/* reuse GL_INT_IMAGE_CUBE */
+/* reuse GL_INT_IMAGE_BUFFER */
+/* reuse GL_INT_IMAGE_1D_ARRAY */
+/* reuse GL_INT_IMAGE_2D_ARRAY */
+/* reuse GL_INT_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_INT_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_1D */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D */
+/* reuse GL_UNSIGNED_INT_IMAGE_3D */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_RECT */
+/* reuse GL_UNSIGNED_INT_IMAGE_CUBE */
+/* reuse GL_UNSIGNED_INT_IMAGE_BUFFER */
+/* reuse GL_UNSIGNED_INT_IMAGE_1D_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE */
+/* reuse GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_MAX_IMAGE_SAMPLES */
+/* reuse GL_IMAGE_BINDING_FORMAT */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_TYPE */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE */
+/* reuse GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS */
+/* reuse GL_MAX_VERTEX_IMAGE_UNIFORMS */
+/* reuse GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS */
+/* reuse GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS */
+/* reuse GL_MAX_GEOMETRY_IMAGE_UNIFORMS */
+/* reuse GL_MAX_FRAGMENT_IMAGE_UNIFORMS */
+/* reuse GL_MAX_COMBINED_IMAGE_UNIFORMS */
+/* Reuse tokens from ARB_shading_language_packing (none) */
+/* Reuse tokens from ARB_texture_storage */
+/* reuse GL_TEXTURE_IMMUTABLE_FORMAT */
+#endif
+
 #ifndef GL_ARB_depth_buffer_float
 #define GL_DEPTH_COMPONENT32F             0x8CAC
 #define GL_DEPTH32F_STENCIL8              0x8CAD
@@ -1284,7 +1405,7 @@ typedef void GLvoid;
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45
 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46
-/* #define GL_INVALID_INDEX                  0xFFFFFFFFu - manual, due to fixed uint32_t size. GlueGen would create int64_t */
+/* #define GL_INVALID_INDEX               0xFFFFFFFFu - manual, due to fixed uint32_t size. GlueGen would create int64_t */
 #endif
 
 #ifndef GL_ARB_copy_buffer
@@ -1380,7 +1501,6 @@ typedef void GLvoid;
 #ifndef GL_ARB_texture_gather
 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E
 #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F
-#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F
 #endif
 
 #ifndef GL_ARB_texture_query_lod
@@ -1575,7 +1695,7 @@ typedef void GLvoid;
 #define GL_GEOMETRY_SHADER_BIT            0x00000004
 #define GL_TESS_CONTROL_SHADER_BIT        0x00000008
 #define GL_TESS_EVALUATION_SHADER_BIT     0x00000010
-#define GL_ALL_SHADER_BITS                0xFFFFFFFF
+/* #define GL_ALL_SHADER_BITS             0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
 #define GL_PROGRAM_SEPARABLE              0x8258
 #define GL_ACTIVE_PROGRAM                 0x8259
 #define GL_PROGRAM_PIPELINE_BINDING       0x825A
@@ -1660,6 +1780,143 @@ typedef void GLvoid;
 #ifndef GL_ARB_shader_stencil_export
 #endif
 
+#ifndef GL_ARB_base_instance
+#endif
+
+#ifndef GL_ARB_shading_language_420pack
+#endif
+
+#ifndef GL_ARB_transform_feedback_instanced
+#endif
+
+#ifndef GL_ARB_compressed_texture_pixel_storage
+#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH  0x9127
+#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128
+#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH  0x9129
+#define GL_UNPACK_COMPRESSED_BLOCK_SIZE   0x912A
+#define GL_PACK_COMPRESSED_BLOCK_WIDTH    0x912B
+#define GL_PACK_COMPRESSED_BLOCK_HEIGHT   0x912C
+#define GL_PACK_COMPRESSED_BLOCK_DEPTH    0x912D
+#define GL_PACK_COMPRESSED_BLOCK_SIZE     0x912E
+#endif
+
+#ifndef GL_ARB_conservative_depth
+#endif
+
+#ifndef GL_ARB_internalformat_query
+#define GL_NUM_SAMPLE_COUNTS              0x9380
+#endif
+
+#ifndef GL_ARB_map_buffer_alignment
+#define GL_MIN_MAP_BUFFER_ALIGNMENT       0x90BC
+#endif
+
+#ifndef GL_ARB_shader_atomic_counters
+#define GL_ATOMIC_COUNTER_BUFFER          0x92C0
+#define GL_ATOMIC_COUNTER_BUFFER_BINDING  0x92C1
+#define GL_ATOMIC_COUNTER_BUFFER_START    0x92C2
+#define GL_ATOMIC_COUNTER_BUFFER_SIZE     0x92C3
+#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4
+#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5
+#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA
+#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB
+#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF
+#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0
+#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1
+#define GL_MAX_VERTEX_ATOMIC_COUNTERS     0x92D2
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS   0x92D5
+#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS   0x92D6
+#define GL_MAX_COMBINED_ATOMIC_COUNTERS   0x92D7
+#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8
+#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC
+#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS  0x92D9
+#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA
+#define GL_UNSIGNED_INT_ATOMIC_COUNTER    0x92DB
+#endif
+
+#ifndef GL_ARB_shader_image_load_store
+#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001
+#define GL_ELEMENT_ARRAY_BARRIER_BIT      0x00000002
+#define GL_UNIFORM_BARRIER_BIT            0x00000004
+#define GL_TEXTURE_FETCH_BARRIER_BIT      0x00000008
+#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020
+#define GL_COMMAND_BARRIER_BIT            0x00000040
+#define GL_PIXEL_BUFFER_BARRIER_BIT       0x00000080
+#define GL_TEXTURE_UPDATE_BARRIER_BIT     0x00000100
+#define GL_BUFFER_UPDATE_BARRIER_BIT      0x00000200
+#define GL_FRAMEBUFFER_BARRIER_BIT        0x00000400
+#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800
+#define GL_ATOMIC_COUNTER_BARRIER_BIT     0x00001000
+/* #define GL_ALL_BARRIER_BITS            0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
+#define GL_MAX_IMAGE_UNITS                0x8F38
+#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39
+#define GL_IMAGE_BINDING_NAME             0x8F3A
+#define GL_IMAGE_BINDING_LEVEL            0x8F3B
+#define GL_IMAGE_BINDING_LAYERED          0x8F3C
+#define GL_IMAGE_BINDING_LAYER            0x8F3D
+#define GL_IMAGE_BINDING_ACCESS           0x8F3E
+#define GL_IMAGE_1D                       0x904C
+#define GL_IMAGE_2D                       0x904D
+#define GL_IMAGE_3D                       0x904E
+#define GL_IMAGE_2D_RECT                  0x904F
+#define GL_IMAGE_CUBE                     0x9050
+#define GL_IMAGE_BUFFER                   0x9051
+#define GL_IMAGE_1D_ARRAY                 0x9052
+#define GL_IMAGE_2D_ARRAY                 0x9053
+#define GL_IMAGE_CUBE_MAP_ARRAY           0x9054
+#define GL_IMAGE_2D_MULTISAMPLE           0x9055
+#define GL_IMAGE_2D_MULTISAMPLE_ARRAY     0x9056
+#define GL_INT_IMAGE_1D                   0x9057
+#define GL_INT_IMAGE_2D                   0x9058
+#define GL_INT_IMAGE_3D                   0x9059
+#define GL_INT_IMAGE_2D_RECT              0x905A
+#define GL_INT_IMAGE_CUBE                 0x905B
+#define GL_INT_IMAGE_BUFFER               0x905C
+#define GL_INT_IMAGE_1D_ARRAY             0x905D
+#define GL_INT_IMAGE_2D_ARRAY             0x905E
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY       0x905F
+#define GL_INT_IMAGE_2D_MULTISAMPLE       0x9060
+#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061
+#define GL_UNSIGNED_INT_IMAGE_1D          0x9062
+#define GL_UNSIGNED_INT_IMAGE_2D          0x9063
+#define GL_UNSIGNED_INT_IMAGE_3D          0x9064
+#define GL_UNSIGNED_INT_IMAGE_2D_RECT     0x9065
+#define GL_UNSIGNED_INT_IMAGE_CUBE        0x9066
+#define GL_UNSIGNED_INT_IMAGE_BUFFER      0x9067
+#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY    0x9068
+#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY    0x9069
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C
+#define GL_MAX_IMAGE_SAMPLES              0x906D
+#define GL_IMAGE_BINDING_FORMAT           0x906E
+#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7
+#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8
+#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9
+#define GL_MAX_VERTEX_IMAGE_UNIFORMS      0x90CA
+#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB
+#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC
+#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS    0x90CD
+#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS    0x90CE
+#define GL_MAX_COMBINED_IMAGE_UNIFORMS    0x90CF
+#endif
+
+#ifndef GL_ARB_shading_language_packing
+#endif
+
+#ifndef GL_ARB_texture_storage
+#define GL_TEXTURE_IMMUTABLE_FORMAT       0x912F
+#endif
+
 
 /*************************************************************/
 
@@ -1699,7 +1956,7 @@ typedef unsigned short GLhalfNV;
 #include "gl-64bit-types.h"
 
 #ifndef GL_ARB_cl_event
-/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event 
+/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event
 struct _cl_context;
 struct _cl_event;
  */
@@ -2368,6 +2625,22 @@ typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divi
 /* ARB_viewport_array */
 #endif
 
+#ifndef GL_VERSION_4_2
+#define GL_VERSION_4_2 1
+/* OpenGL 4.2 reuses entry points from these extensions: */
+/* ARB_base_instance */
+/* ARB_shading_language_420pack (no entry points) */
+/* ARB_transform_feedback_instanced */
+/* ARB_compressed_texture_pixel_storage (no entry points) */
+/* ARB_conservative_depth (no entry points) */
+/* ARB_internalformat_query */
+/* ARB_map_buffer_alignment (no entry points) */
+/* ARB_shader_atomic_counters */
+/* ARB_shader_image_load_store */
+/* ARB_shading_language_packing (no entry points) */
+/* ARB_texture_storage */
+#endif
+
 #ifndef GL_ARB_depth_buffer_float
 #define GL_ARB_depth_buffer_float 1
 #endif
@@ -2666,6 +2939,10 @@ typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum
 typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params);
 #endif
 
+#ifndef GL_ARB_shader_bit_encoding
+#define GL_ARB_shader_bit_encoding 1
+#endif
+
 #ifndef GL_ARB_texture_rgb10_a2ui
 #define GL_ARB_texture_rgb10_a2ui 1
 #endif
@@ -3174,6 +3451,92 @@ typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint locati
 #define GL_ARB_shader_stencil_export 1
 #endif
 
+#ifndef GL_ARB_base_instance
+#define GL_ARB_base_instance 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance);
+GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance);
+GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount, GLuint baseinstance);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLuint baseinstance);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount, GLint basevertex, GLuint baseinstance);
+#endif
+
+#ifndef GL_ARB_shading_language_420pack
+#define GL_ARB_shading_language_420pack 1
+#endif
+
+#ifndef GL_ARB_transform_feedback_instanced
+#define GL_ARB_transform_feedback_instanced 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei primcount);
+GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei primcount);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei primcount);
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei primcount);
+#endif
+
+#ifndef GL_ARB_compressed_texture_pixel_storage
+#define GL_ARB_compressed_texture_pixel_storage 1
+#endif
+
+#ifndef GL_ARB_conservative_depth
+#define GL_ARB_conservative_depth 1
+#endif
+
+#ifndef GL_ARB_internalformat_query
+#define GL_ARB_internalformat_query 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params);
+#endif
+
+#ifndef GL_ARB_map_buffer_alignment
+#define GL_ARB_map_buffer_alignment 1
+#endif
+
+#ifndef GL_ARB_shader_atomic_counters
+#define GL_ARB_shader_atomic_counters 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_ARB_shader_image_load_store
+#define GL_ARB_shader_image_load_store 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
+typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers);
+#endif
+
+#ifndef GL_ARB_shading_language_packing
+#define GL_ARB_shading_language_packing 1
+#endif
+
+#ifndef GL_ARB_texture_storage
+#define GL_ARB_texture_storage 1
+#ifdef GL3_PROTOTYPES
+GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif /* GL3_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
 #ifndef GL_ARB_texture_buffer_object
 #define GL_TEXTURE_BUFFER_ARB             0x8C2A
 #define GL_MAX_TEXTURE_BUFFER_SIZE_ARB    0x8C2B
diff --git a/make/stub_includes/opengl/GL3/gl3ext.h b/make/stub_includes/opengl/GL3/gl3ext.h
index 6c985da..8b05499 100644
--- a/make/stub_includes/opengl/GL3/gl3ext.h
+++ b/make/stub_includes/opengl/GL3/gl3ext.h
@@ -52,9 +52,8 @@
  *    #endif
  */
   
-
 /**
- * http://www.opengl.org/registry/specs/ARB/geometry_shader4.txt
+ * 47. http://www.opengl.org/registry/specs/ARB/geometry_shader4.txt
  */
 #ifndef GL_ARB_geometry_shader4
 #define GL_LINES_ADJACENCY_ARB            0x000A
@@ -90,15 +89,19 @@ GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, G
 GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
 GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
 #endif /* GL_GL3EXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
-typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
 #endif
 
-/**
- * http://www.opengl.org/registry/specs/AMD/vertex_shader_tessellator.txt
- */
+// #187
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#endif
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+// #363 http://www.opengl.org/registry/specs/AMD/vertex_shader_tessellator.txt
 #ifndef GL_AMD_vertex_shader_tessellator
 #define GL_SAMPLER_BUFFER_AMD                0x9001
 #define GL_INT_SAMPLER_BUFFER_AMD            0x9002
@@ -117,9 +120,7 @@ GLAPI void APIENTRY glTessellationModeAMD(GLenum mode);
 /* No need for explicit function pointer: we force generation of ProcAddress .. */
 #endif
 
-/**
- * http://www.opengl.org/registry/specs/NV/shader_buffer_load.txt
- */
+// #379 http://www.opengl.org/registry/specs/NV/shader_buffer_load.txt
 #ifndef GL_NV_shader_buffer_load
 #define GL_BUFFER_GPU_ADDRESS_NV          0x8F1D
 #define GL_GPU_ADDRESS_NV                 0x8F34
@@ -143,25 +144,10 @@ GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint6
 GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value);
 GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
 #endif /* GL_GL3EXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access);
-typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target);
-typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target);
-typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access);
-typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer);
-typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer);
-typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params);
-typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params);
-typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result);
-typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value);
-typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
-typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params);
-typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value);
-typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
 #endif
 
-/**
- * http://www.opengl.org/registry/specs/NV/vertex_buffer_unified_memory.txt
- */
+// #380 http://www.opengl.org/registry/specs/NV/vertex_buffer_unified_memory.txt
 #ifndef GL_NV_vertex_buffer_unified_memory
 #define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E
 #define GL_ELEMENT_ARRAY_UNIFIED_NV       0x8F1F
@@ -209,84 +195,10 @@ GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum typ
 GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride);
 GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result);
 #endif /* GL_GL3EXT_PROTOTYPES */
-typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);
-typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride);
-typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);
-typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);
-typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
-#endif
-
-
-
-#ifndef GL_APPLE_float_pixels
-#define GL_HALF_APPLE                      0x140B
-#define GL_COLOR_FLOAT_APPLE               0x8A0F
-#define GL_RGBA_FLOAT32_APPLE              0x8814
-#define GL_RGB_FLOAT32_APPLE               0x8815
-#define GL_ALPHA_FLOAT32_APPLE             0x8816
-#define GL_INTENSITY_FLOAT32_APPLE         0x8817
-#define GL_LUMINANCE_FLOAT32_APPLE         0x8818
-#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE   0x8819
-#define GL_RGBA_FLOAT16_APPLE              0x881A
-#define GL_RGB_FLOAT16_APPLE               0x881B
-#define GL_ALPHA_FLOAT16_APPLE             0x881C
-#define GL_INTENSITY_FLOAT16_APPLE         0x881D
-#define GL_LUMINANCE_FLOAT16_APPLE         0x881E
-#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE   0x881F
-#endif
-
-#ifndef GL_APPLE_float_pixels
-#define GL_APPLE_float_pixels 1
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_RGBA_FLOAT32_ATI               0x8814
-#define GL_RGB_FLOAT32_ATI                0x8815
-#define GL_ALPHA_FLOAT32_ATI              0x8816
-#define GL_INTENSITY_FLOAT32_ATI          0x8817
-#define GL_LUMINANCE_FLOAT32_ATI          0x8818
-#define GL_LUMINANCE_ALPHA_FLOAT32_ATI    0x8819
-#define GL_RGBA_FLOAT16_ATI               0x881A
-#define GL_RGB_FLOAT16_ATI                0x881B
-#define GL_ALPHA_FLOAT16_ATI              0x881C
-#define GL_INTENSITY_FLOAT16_ATI          0x881D
-#define GL_LUMINANCE_FLOAT16_ATI          0x881E
-#define GL_LUMINANCE_ALPHA_FLOAT16_ATI    0x881F
-#endif
-
-#ifndef GL_ATI_texture_float
-#define GL_ATI_texture_float 1
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_FLOAT_R_NV                     0x8880
-#define GL_FLOAT_RG_NV                    0x8881
-#define GL_FLOAT_RGB_NV                   0x8882
-#define GL_FLOAT_RGBA_NV                  0x8883
-#define GL_FLOAT_R16_NV                   0x8884
-#define GL_FLOAT_R32_NV                   0x8885
-#define GL_FLOAT_RG16_NV                  0x8886
-#define GL_FLOAT_RG32_NV                  0x8887
-#define GL_FLOAT_RGB16_NV                 0x8888
-#define GL_FLOAT_RGB32_NV                 0x8889
-#define GL_FLOAT_RGBA16_NV                0x888A
-#define GL_FLOAT_RGBA32_NV                0x888B
-#define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
-#define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
-#define GL_FLOAT_RGBA_MODE_NV             0x888E
-#endif
-
-#ifndef GL_NV_float_buffer
-#define GL_NV_float_buffer 1
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
 #endif
 
+// #395
 #ifndef GL_AMD_debug_output
 #define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD  0x9144
 #define GL_DEBUG_LOGGED_MESSAGES_AMD      0x9145
@@ -319,7 +231,121 @@ typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callba
 typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message);
 #endif
 
+// #401
+#ifndef GL_AMD_depth_clamp_separate
+#define GL_DEPTH_CLAMP_NEAR_AMD           0x901E
+#define GL_DEPTH_CLAMP_FAR_AMD            0x901F
+#endif
+#ifndef GL_AMD_depth_clamp_separate
+#define GL_AMD_depth_clamp_separate 1
+#endif
+
+// #402
+#ifndef GL_EXT_texture_sRGB_decode
+#define GL_TEXTURE_SRGB_DECODE_EXT        0x8A48
+#define GL_DECODE_EXT                     0x8A49
+#define GL_SKIP_DECODE_EXT                0x8A4A
+#endif
+#ifndef GL_EXT_texture_sRGB_decode
+#define GL_EXT_texture_sRGB_decode 1
+#endif
+
+// #403
+#ifndef GL_NV_texture_multisample
+#define GL_TEXTURE_COVERAGE_SAMPLES_NV    0x9045
+#define GL_TEXTURE_COLOR_SAMPLES_NV       0x9046
+#endif
+#ifndef GL_NV_texture_multisample
+#define GL_NV_texture_multisample 1
+#ifdef GL_GL3EXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations);
+GLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations);
+#endif /* GL_GL3EXT_PROTOTYPES */
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
+#endif
+
+// #404
+#ifndef GL_AMD_blend_minmax_factor
+#define GL_FACTOR_MIN_AMD                 0x901C
+#define GL_FACTOR_MAX_AMD                 0x901D
+#endif
+#ifndef GL_AMD_blend_minmax_factor
+#define GL_AMD_blend_minmax_factor 1
+#endif
+
+// #405
+#ifndef GL_AMD_sample_positions
+#define GL_SUBSAMPLE_DISTANCE_AMD         0x883F
+#endif
+#ifndef GL_AMD_sample_positions
+#define GL_AMD_sample_positions 1
+#ifdef GL_GL3EXT_PROTOTYPES
+GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val);
+#endif /* GL_GL3EXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val);
+#endif
+
+// #406
+#ifndef GL_EXT_x11_sync_object
+#define GL_SYNC_X11_FENCE_EXT             0x90E1
+#endif
+#ifndef GL_EXT_x11_sync_object
+#define GL_EXT_x11_sync_object 1
+#ifdef GL_GL3EXT_PROTOTYPES
+GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags);
+#endif /* GL_GL3EXT_PROTOTYPES */
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
+#endif
 
+// #408
+#ifndef GL_AMD_multi_draw_indirect
+#endif
+#ifndef GL_AMD_multi_draw_indirect
+#define GL_AMD_multi_draw_indirect 1
+#ifdef GL_GL3EXT_PROTOTYPES
+GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const GLvoid *indirect, GLsizei primcount, GLsizei stride);
+#endif /* GL_GL3EXT_PROTOTYPES */
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
+#endif
+
+// #409
+#ifndef GL_EXT_framebuffer_multisample_blit_scaled
+#define GL_SCALED_RESOLVE_FASTEST_EXT     0x90BA
+#define GL_SCALED_RESOLVE_NICEST_EXT      0x90BB
+#endif
+#ifndef GL_EXT_framebuffer_multisample_blit_scaled
+#define GL_EXT_framebuffer_multisample_blit_scaled 1
+#endif
+
+// #410 GL_NV_path_rendering ?
+
+// #411
+#ifndef GL_AMD_pinned_memory
+#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160
+#endif
+#ifndef GL_AMD_pinned_memory
+#define GL_AMD_pinned_memory 1
+#endif
+
+// #413
+#ifndef GL_AMD_stencil_operation_extended
+#define GL_SET_AMD                        0x874A
+#define GL_REPLACE_VALUE_AMD              0x874B
+#define GL_STENCIL_OP_VALUE_AMD           0x874C
+#define GL_STENCIL_BACK_OP_VALUE_AMD      0x874D
+#endif
+#ifndef GL_AMD_stencil_operation_extended
+#define GL_AMD_stencil_operation_extended 1
+#ifdef GL_GL3EXT_PROTOTYPES
+GLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value);
+#endif /* GL_GL3EXT_PROTOTYPES */
+/* No need for explicit function pointer: we force generation of ProcAddress .. */
+#endif
 
 #endif /* __gl3ext_h_ */
 
diff --git a/make/stub_includes/opengl/GLES/glext.h b/make/stub_includes/opengl/GLES/glext.h
index 9128773..b3d6b71 100644
--- a/make/stub_includes/opengl/GLES/glext.h
+++ b/make/stub_includes/opengl/GLES/glext.h
@@ -1,7 +1,7 @@
 #ifndef __glext_h_
 #define __glext_h_
 
-/* $Revision: 12119 $ on $Date:: 2010-07-27 17:40:32 -0700 #$ */
+/* $Revision: 16481 $ on $Date:: 2012-01-04 10:43:56 -0800 #$ */
 
 #ifdef __cplusplus
 extern "C" {
@@ -65,7 +65,16 @@ extern "C" {
 
 /* GL_OES_EGL_image */
 #ifndef GL_OES_EGL_image
-typedef void* GLeglImageOES;
+// typedef void* GLeglImageOES;
+typedef struct __GLeglImageOES *GLeglImageOES;
+#endif
+
+/* GL_OES_EGL_image_external */
+#ifndef GL_OES_EGL_image_external
+/* GLeglImageOES defined in GL_OES_EGL_image already. */
+#define GL_TEXTURE_EXTERNAL_OES                                 0x8D65
+#define GL_TEXTURE_BINDING_EXTERNAL_OES                         0x8D67
+#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES                     0x8D68
 #endif
 
 /* GL_OES_element_index_uint */
@@ -280,6 +289,14 @@ typedef void* GLeglImageOES;
 #define GL_STENCIL_EXT                                          0x1802
 #endif
 
+/* GL_EXT_multisampled_render_to_texture */
+#ifndef GL_EXT_multisampled_render_to_texture
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT           0x8D6C
+#define GL_RENDERBUFFER_SAMPLES_EXT                             0x9133
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT               0x9134
+#define GL_MAX_SAMPLES_EXT                                      0x9135
+#endif
+
 /* GL_EXT_multi_draw_arrays */
 /* No new tokens introduced by this extension. */
 
@@ -290,6 +307,32 @@ typedef void* GLeglImageOES;
 #define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT                       0x8366
 #endif
 
+/* GL_EXT_robustness */
+#ifndef GL_EXT_robustness
+/* reuse GL_NO_ERROR */
+#define GL_GUILTY_CONTEXT_RESET_EXT                             0x8253
+#define GL_INNOCENT_CONTEXT_RESET_EXT                           0x8254
+#define GL_UNKNOWN_CONTEXT_RESET_EXT                            0x8255
+#define GL_CONTEXT_ROBUST_ACCESS_EXT                            0x90F3
+#define GL_RESET_NOTIFICATION_STRATEGY_EXT                      0x8256
+#define GL_LOSE_CONTEXT_ON_RESET_EXT                            0x8252
+#define GL_NO_RESET_NOTIFICATION_EXT                            0x8261
+#endif
+
+/* GL_EXT_sRGB */
+#ifndef GL_EXT_sRGB
+#define GL_SRGB_EXT                                             0x8C40
+#define GL_SRGB_ALPHA_EXT                                       0x8C42
+#define GL_SRGB8_ALPHA8_EXT                                     0x8C43
+#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT            0x8210
+#endif
+
+/* GL_EXT_texture_compression_dxt1 */
+#ifndef GL_EXT_texture_compression_dxt1
+#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT                         0x83F0
+#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT                        0x83F1
+#endif
+
 /* GL_EXT_texture_filter_anisotropic */
 #ifndef GL_EXT_texture_filter_anisotropic
 #define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
@@ -308,6 +351,27 @@ typedef void* GLeglImageOES;
 #define GL_TEXTURE_LOD_BIAS_EXT                                 0x8501
 #endif
 
+/* GL_EXT_texture_storage */
+#ifndef GL_EXT_texture_storage
+#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT                         0x912F
+#define GL_ALPHA8_EXT                                           0x803C  
+#define GL_LUMINANCE8_EXT                                       0x8040
+#define GL_LUMINANCE8_ALPHA8_EXT                                0x8045
+#define GL_RGBA32F_EXT                                          0x8814  
+#define GL_RGB32F_EXT                                           0x8815
+#define GL_ALPHA32F_EXT                                         0x8816
+#define GL_LUMINANCE32F_EXT                                     0x8818
+#define GL_LUMINANCE_ALPHA32F_EXT                               0x8819
+/* reuse GL_RGBA16F_EXT */
+#define GL_RGB16F_EXT                                           0x881B
+#define GL_ALPHA16F_EXT                                         0x881C
+#define GL_LUMINANCE16F_EXT                                     0x881E
+#define GL_LUMINANCE_ALPHA16F_EXT                               0x881F
+#define GL_RGB10_A2_EXT                                         0x8059  
+#define GL_RGB10_EXT                                            0x8052
+#define GL_BGRA8_EXT                                            0x93A1
+#endif
+
 /*------------------------------------------------------------------------*
  * IMG extension tokens
  *------------------------------------------------------------------------*/
@@ -527,6 +591,12 @@ typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target,
 typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
 #endif
 
+/* GL_OES_EGL_image_external */
+#ifndef GL_OES_EGL_image_external
+#define GL_OES_EGL_image_external 1
+/* glEGLImageTargetTexture2DOES defined in GL_OES_EGL_image already. */
+#endif
+
 /* GL_OES_element_index_uint */
 #ifndef GL_OES_element_index_uint
 #define GL_OES_element_index_uint 1
@@ -883,6 +953,17 @@ GL_API void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttac
 typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
 #endif
 
+/* GL_EXT_multisampled_render_to_texture */
+#ifndef GL_EXT_multisampled_render_to_texture
+#define GL_EXT_multisampled_render_to_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum, GLsizei, GLenum, GLsizei, GLsizei);
+GL_API void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLsizei);
+#endif
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#endif
+
 /* GL_EXT_multi_draw_arrays */
 #ifndef GL_EXT_multi_draw_arrays
 #define GL_EXT_multi_draw_arrays 1
@@ -899,6 +980,31 @@ typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GL
 #define GL_EXT_read_format_bgra 1
 #endif
 
+/* GL_EXT_robustness */
+#ifndef GL_EXT_robustness
+#define GL_EXT_robustness 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void);
+GL_API void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+GL_API void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, float *params);
+GL_API void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#endif
+typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void);
+typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, float *params);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#endif
+
+/* GL_EXT_sRGB */
+#ifndef GL_EXT_sRGB
+#define GL_EXT_sRGB 1
+#endif
+
+/* GL_EXT_texture_compression_dxt1 */
+#ifndef GL_EXT_texture_compression_dxt1
+#define GL_EXT_texture_compression_dxt1 1
+#endif
+
 /* GL_EXT_texture_filter_anisotropic */
 #ifndef GL_EXT_texture_filter_anisotropic
 #define GL_EXT_texture_filter_anisotropic 1
@@ -914,6 +1020,25 @@ typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GL
 #define GL_EXT_texture_lod_bias 1
 #endif
 
+/* GL_EXT_texture_storage */
+#ifndef GL_EXT_texture_storage
+#define GL_EXT_texture_storage 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_API void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_API void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+GL_API void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_API void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_API void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
 /*------------------------------------------------------------------------*
  * IMG extension functions
  *------------------------------------------------------------------------*/
diff --git a/make/stub_includes/opengl/GLES2/gl2.h b/make/stub_includes/opengl/GLES2/gl2.h
index 03807e3..5c6d5f0 100644
--- a/make/stub_includes/opengl/GLES2/gl2.h
+++ b/make/stub_includes/opengl/GLES2/gl2.h
@@ -1,7 +1,7 @@
 #ifndef __gl2_h_
 #define __gl2_h_
 
-/* $Revision: 10602 $ on $Date:: 2010-03-04 22:35:34 -0800 #$ */
+/* $Revision: 16803 $ on $Date:: 2012-02-02 09:49:18 -0800 #$ */
 
 #include <GLES2/gl2platform.h>
 
diff --git a/make/stub_includes/opengl/GLES2/gl2ext.h b/make/stub_includes/opengl/GLES2/gl2ext.h
index 25fea47..04c0a64 100644
--- a/make/stub_includes/opengl/GLES2/gl2ext.h
+++ b/make/stub_includes/opengl/GLES2/gl2ext.h
@@ -1,7 +1,7 @@
 #ifndef __gl2ext_h_
 #define __gl2ext_h_
 
-/* $Revision: 12813 $ on $Date:: 2010-11-03 17:33:04 -0700 #$ */
+/* $Revision: 16619 $ on $Date:: 2012-01-18 10:00:14 -0800 #$ */
 
 #ifdef __cplusplus
 extern "C" {
@@ -54,7 +54,17 @@ extern "C" {
 
 /* GL_OES_EGL_image */
 #ifndef GL_OES_EGL_image
-typedef void* GLeglImageOES;
+// typedef void* GLeglImageOES;
+typedef struct __GLeglImageOES *GLeglImageOES;
+#endif
+
+/* GL_OES_EGL_image_external */
+#ifndef GL_OES_EGL_image_external
+/* GLeglImageOES defined in GL_OES_EGL_image already. */
+#define GL_TEXTURE_EXTERNAL_OES                                 0x8D65
+#define GL_SAMPLER_EXTERNAL_OES                                 0x8D66
+#define GL_TEXTURE_BINDING_EXTERNAL_OES                         0x8D67
+#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES                     0x8D68
 #endif
 
 /* GL_OES_element_index_uint */
@@ -187,7 +197,7 @@ typedef void* GLeglImageOES;
 #ifndef GL_ANGLE_framebuffer_blit
 #define GL_READ_FRAMEBUFFER_ANGLE                               0x8CA8
 #define GL_DRAW_FRAMEBUFFER_ANGLE                               0x8CA9
-#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE                       0x8CA6 
+#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE                       0x8CA6
 #define GL_READ_FRAMEBUFFER_BINDING_ANGLE                       0x8CAA
 #endif
 
@@ -252,6 +262,29 @@ typedef void* GLeglImageOES;
 #define GL_MAX_EXT                                              0x8008
 #endif
 
+/* GL_EXT_color_buffer_half_float */
+#ifndef GL_EXT_color_buffer_half_float
+#define GL_RGBA16F_EXT                                          0x881A
+#define GL_RGB16F_EXT                                           0x881B
+#define GL_RG16F_EXT                                            0x822F
+#define GL_R16F_EXT                                             0x822D
+#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT            0x8211
+#define GL_UNSIGNED_NORMALIZED_EXT                              0x8C17
+#endif
+
+/* GL_EXT_debug_label */
+#ifndef GL_EXT_debug_label
+#define GL_PROGRAM_PIPELINE_OBJECT_EXT                          0x8A4F
+#define GL_PROGRAM_OBJECT_EXT                                   0x8B40
+#define GL_SHADER_OBJECT_EXT                                    0x8B48
+#define GL_BUFFER_OBJECT_EXT                                    0x9151
+#define GL_QUERY_OBJECT_EXT                                     0x9153
+#define GL_VERTEX_ARRAY_OBJECT_EXT                              0x9154
+#endif
+
+/* GL_EXT_debug_marker */
+/* No new tokens introduced by this extension. */
+
 /* GL_EXT_discard_framebuffer */
 #ifndef GL_EXT_discard_framebuffer
 #define GL_COLOR_EXT                                            0x1800
@@ -259,9 +292,26 @@ typedef void* GLeglImageOES;
 #define GL_STENCIL_EXT                                          0x1802
 #endif
 
+/* GL_EXT_multisampled_render_to_texture */
+#ifndef GL_EXT_multisampled_render_to_texture
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT           0x8D6C
+#define GL_RENDERBUFFER_SAMPLES_EXT                             0x9133
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT               0x9134
+#define GL_MAX_SAMPLES_EXT                                      0x9135
+#endif
+
 /* GL_EXT_multi_draw_arrays */
 /* No new tokens introduced by this extension. */
 
+/* GL_EXT_occlusion_query_boolean */
+#ifndef GL_EXT_occlusion_query_boolean
+#define GL_ANY_SAMPLES_PASSED_EXT                               0x8C2F
+#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT                  0x8D6A
+#define GL_CURRENT_QUERY_EXT                                    0x8865
+#define GL_QUERY_RESULT_EXT                                     0x8866
+#define GL_QUERY_RESULT_AVAILABLE_EXT                           0x8867
+#endif
+
 /* GL_EXT_read_format_bgra */
 #ifndef GL_EXT_read_format_bgra
 #define GL_BGRA_EXT                                             0x80E1
@@ -269,20 +319,45 @@ typedef void* GLeglImageOES;
 #define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT                       0x8366
 #endif
 
-/* GL_EXT_texture_filter_anisotropic */
-#ifndef GL_EXT_texture_filter_anisotropic
-#define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
-#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT                       0x84FF
+/* GL_EXT_robustness */
+#ifndef GL_EXT_robustness
+/* reuse GL_NO_ERROR */
+#define GL_GUILTY_CONTEXT_RESET_EXT                             0x8253
+#define GL_INNOCENT_CONTEXT_RESET_EXT                           0x8254
+#define GL_UNKNOWN_CONTEXT_RESET_EXT                            0x8255
+#define GL_CONTEXT_ROBUST_ACCESS_EXT                            0x90F3
+#define GL_RESET_NOTIFICATION_STRATEGY_EXT                      0x8256
+#define GL_LOSE_CONTEXT_ON_RESET_EXT                            0x8252
+#define GL_NO_RESET_NOTIFICATION_EXT                            0x8261
 #endif
 
-/* GL_EXT_texture_format_BGRA8888 */
-#ifndef GL_EXT_texture_format_BGRA8888
-#define GL_BGRA_EXT                                             0x80E1
+/* GL_EXT_separate_shader_objects */
+#ifndef GL_EXT_separate_shader_objects
+#define GL_VERTEX_SHADER_BIT_EXT                                0x00000001
+#define GL_FRAGMENT_SHADER_BIT_EXT                              0x00000002
+/* #define GL_ALL_SHADER_BITS_EXT                               0xFFFFFFFF  - manual, due to fixed uint32_t size. GlueGen would create int64_t */
+#define GL_PROGRAM_SEPARABLE_EXT                                0x8258
+#define GL_ACTIVE_PROGRAM_EXT                                   0x8259
+#define GL_PROGRAM_PIPELINE_BINDING_EXT                         0x825A
 #endif
 
-/* GL_EXT_texture_type_2_10_10_10_REV */
-#ifndef GL_EXT_texture_type_2_10_10_10_REV
-#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT                      0x8368
+/* GL_EXT_shader_texture_lod */
+/* No new tokens introduced by this extension. */
+
+/* GL_EXT_shadow_samplers */
+#ifndef GL_EXT_shadow_samplers
+#define GL_TEXTURE_COMPARE_MODE_EXT                             0x884C
+#define GL_TEXTURE_COMPARE_FUNC_EXT                             0x884D
+#define GL_COMPARE_REF_TO_TEXTURE_EXT                           0x884E
+#define GL_SAMPLER_2D_SHADOW_EXT                                0x8B62
+#endif
+
+/* GL_EXT_sRGB */
+#ifndef GL_EXT_sRGB
+#define GL_SRGB_EXT                                             0x8C40
+#define GL_SRGB_ALPHA_EXT                                       0x8C42
+#define GL_SRGB8_ALPHA8_EXT                                     0x8C43
+#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT            0x8210
 #endif
 
 /* GL_EXT_texture_compression_dxt1 */
@@ -291,45 +366,65 @@ typedef void* GLeglImageOES;
 #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT                        0x83F1
 #endif
 
-/* GL_EXT_shader_texture_lod */
-/* No new tokens introduced by this extension. */
-
-/* GL_EXT_framebuffer_mixed_formats */
-#ifndef GL_EXT_framebuffer_mixed_formats
-#define GL_EXT_framebuffer_mixed_formats 1
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT                       0x84FF
 #endif
 
-/* GL_EXT_packed_float */
-#ifndef GL_EXT_packed_float
-#define GL_R11F_G11F_B10F_EXT                           0x8C3A
-#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT             0x8C3B
-#define GL_RGBA_SIGNED_COMPONENTS_EXT                   0x8C3C
-#endif
-#ifndef GL_EXT_packed_float
-#define GL_EXT_packed_float 1
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_BGRA_EXT                                             0x80E1
 #endif
 
-/* GL_EXT_texture_array */
-#ifndef GL_EXT_texture_array
-#define GL_TEXTURE_2D_ARRAY_EXT           0x8C1A
-#define GL_SAMPLER_2D_ARRAY_EXT           0x8DC1
-#define GL_TEXTURE_BINDING_2D_ARRAY_EXT   0x8C1D
-#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT   0x88FF
-#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4
+/* GL_EXT_texture_rg */
+#ifndef GL_EXT_texture_rg
+#define GL_RED_EXT                                              0x1903
+#define GL_RG_EXT                                               0x8227
+#define GL_R8_EXT                                               0x8229
+#define GL_RG8_EXT                                              0x822B
+#endif
+
+/* GL_EXT_texture_storage */
+#ifndef GL_EXT_texture_storage
+#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT                         0x912F // remove EXT
+#define GL_ALPHA8_EXT                                           0x803C // keep EXT 
+#define GL_LUMINANCE8_EXT                                       0x8040 // keep EXT
+#define GL_LUMINANCE8_ALPHA8_EXT                                0x8045 // keep EXT
+#define GL_RGBA32F_EXT                                          0x8814 // remove EXT 
+#define GL_RGB32F_EXT                                           0x8815 // remove EXT
+#define GL_ALPHA32F_EXT                                         0x8816 // -> ARB
+#define GL_LUMINANCE32F_EXT                                     0x8818 // -> ARB
+#define GL_LUMINANCE_ALPHA32F_EXT                               0x8819 // -> ARB
+/* reuse GL_RGBA16F_EXT */
+#define GL_RGB16F_EXT                                           0x881B // remove EXT (duplicate in GL_EXT_color_buffer_half_float)
+#define GL_ALPHA16F_EXT                                         0x881C // -> ARB
+#define GL_LUMINANCE16F_EXT                                     0x881E // -> ARB
+#define GL_LUMINANCE_ALPHA16F_EXT                               0x881F // -> ARB
+#define GL_RGB10_A2_EXT                                         0x8059 // remove EXT 
+#define GL_RGB10_EXT                                            0x8052 // remove EXT
+#define GL_BGRA8_EXT                                            0x93A1 // keep
 #endif
-#ifndef GL_EXT_texture_array
-#define GL_EXT_texture_array 1
+
+/* GL_EXT_texture_type_2_10_10_10_REV */
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT                      0x8368
 #endif
 
-/* GL_EXT_texture_compression_s3tc */
-#ifndef GL_EXT_texture_compression_s3tc
-/* GL_COMPRESSED_RGB_S3TC_DXT1_EXT defined in GL_EXT_texture_compression_dxt1 already. */
-/* GL_COMPRESSED_RGBA_S3TC_DXT1_EXT defined in GL_EXT_texture_compression_dxt1 already. */
-#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
-#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
+/* GL_EXT_unpack_subimage */
+#ifndef GL_EXT_unpack_subimage
+#define GL_UNPACK_ROW_LENGTH                                    0x0CF2
+#define GL_UNPACK_SKIP_ROWS                                     0x0CF3
+#define GL_UNPACK_SKIP_PIXELS                                   0x0CF4
 #endif
-#ifndef GL_EXT_texture_compression_s3tc
-#define GL_EXT_texture_compression_s3tc 1
+
+/*------------------------------------------------------------------------*
+ * DMP extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_DMP_shader_binary */
+#ifndef GL_DMP_shader_binary
+#define GL_SHADER_BINARY_DMP                                    0x9250
 #endif
 
 /*------------------------------------------------------------------------*
@@ -397,10 +492,90 @@ typedef void* GLeglImageOES;
 #define GL_DEPTH_COMPONENT16_NONLINEAR_NV                       0x8E2C
 #endif
 
+/* GL_NV_draw_buffers */
+#ifndef GL_NV_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_NV                                  0x8824
+#define GL_DRAW_BUFFER0_NV                                      0x8825
+#define GL_DRAW_BUFFER1_NV                                      0x8826
+#define GL_DRAW_BUFFER2_NV                                      0x8827
+#define GL_DRAW_BUFFER3_NV                                      0x8828
+#define GL_DRAW_BUFFER4_NV                                      0x8829
+#define GL_DRAW_BUFFER5_NV                                      0x882A
+#define GL_DRAW_BUFFER6_NV                                      0x882B
+#define GL_DRAW_BUFFER7_NV                                      0x882C
+#define GL_DRAW_BUFFER8_NV                                      0x882D
+#define GL_DRAW_BUFFER9_NV                                      0x882E
+#define GL_DRAW_BUFFER10_NV                                     0x882F
+#define GL_DRAW_BUFFER11_NV                                     0x8830
+#define GL_DRAW_BUFFER12_NV                                     0x8831
+#define GL_DRAW_BUFFER13_NV                                     0x8832
+#define GL_DRAW_BUFFER14_NV                                     0x8833
+#define GL_DRAW_BUFFER15_NV                                     0x8834
+#define GL_COLOR_ATTACHMENT0_NV                                 0x8CE0
+#define GL_COLOR_ATTACHMENT1_NV                                 0x8CE1
+#define GL_COLOR_ATTACHMENT2_NV                                 0x8CE2
+#define GL_COLOR_ATTACHMENT3_NV                                 0x8CE3
+#define GL_COLOR_ATTACHMENT4_NV                                 0x8CE4
+#define GL_COLOR_ATTACHMENT5_NV                                 0x8CE5
+#define GL_COLOR_ATTACHMENT6_NV                                 0x8CE6
+#define GL_COLOR_ATTACHMENT7_NV                                 0x8CE7
+#define GL_COLOR_ATTACHMENT8_NV                                 0x8CE8
+#define GL_COLOR_ATTACHMENT9_NV                                 0x8CE9
+#define GL_COLOR_ATTACHMENT10_NV                                0x8CEA
+#define GL_COLOR_ATTACHMENT11_NV                                0x8CEB
+#define GL_COLOR_ATTACHMENT12_NV                                0x8CEC
+#define GL_COLOR_ATTACHMENT13_NV                                0x8CED
+#define GL_COLOR_ATTACHMENT14_NV                                0x8CEE
+#define GL_COLOR_ATTACHMENT15_NV                                0x8CEF
+#endif
+
+/* GL_NV_fbo_color_attachments */
+#ifndef GL_NV_fbo_color_attachments
+#define GL_MAX_COLOR_ATTACHMENTS_NV                             0x8CDF
+/* GL_COLOR_ATTACHMENT{0-15}_NV defined in GL_NV_draw_buffers already. */
+#endif
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV                                     0x84F2
+#define GL_FENCE_STATUS_NV                                      0x84F3
+#define GL_FENCE_CONDITION_NV                                   0x84F4
+#endif
+
+/* GL_NV_read_buffer */
+#ifndef GL_NV_read_buffer
+#define GL_READ_BUFFER_NV                                       0x0C02
+#endif
+
+/* GL_NV_read_buffer_front */
+/* No new tokens introduced by this extension. */
+
+/* GL_NV_read_depth */
+/* No new tokens introduced by this extension. */
+
+/* GL_NV_read_depth_stencil */
+/* No new tokens introduced by this extension. */
+
+/* GL_NV_read_stencil */
+/* No new tokens introduced by this extension. */
+
+/* GL_NV_texture_compression_s3tc_update */
+/* No new tokens introduced by this extension. */
+
+/* GL_NV_texture_npot_2D_mipmap */
+/* No new tokens introduced by this extension. */
+
 /*------------------------------------------------------------------------*
  * QCOM extension tokens
  *------------------------------------------------------------------------*/
 
+/* GL_QCOM_alpha_test */
+#ifndef GL_QCOM_alpha_test
+#define GL_ALPHA_TEST_QCOM                                      0x0BC0
+#define GL_ALPHA_TEST_FUNC_QCOM                                 0x0BC1
+#define GL_ALPHA_TEST_REF_QCOM                                  0x0BC2
+#endif
+
 /* GL_QCOM_driver_control */
 /* No new tokens introduced by this extension. */
 
@@ -521,6 +696,12 @@ typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target,
 typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
 #endif
 
+/* GL_OES_EGL_image_external */
+#ifndef GL_OES_EGL_image_external
+#define GL_OES_EGL_image_external 1
+/* glEGLImageTargetTexture2DOES defined in GL_OES_EGL_image already. */
+#endif
+
 /* GL_OES_element_index_uint */
 #ifndef GL_OES_element_index_uint
 #define GL_OES_element_index_uint 1
@@ -777,6 +958,35 @@ typedef void (GL_APIENTRYP PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC) (void);
 #define GL_EXT_blend_minmax 1
 #endif
 
+/* GL_EXT_color_buffer_half_float */
+#ifndef GL_EXT_color_buffer_half_float
+#define GL_EXT_color_buffer_half_float 1
+#endif
+
+/* GL_EXT_debug_label */
+#ifndef GL_EXT_debug_label
+#define GL_EXT_debug_label 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label);
+GL_APICALL void GL_APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
+#endif
+typedef void (GL_APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label);
+typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
+#endif
+
+/* GL_EXT_debug_marker */
+#ifndef GL_EXT_debug_marker
+#define GL_EXT_debug_marker 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker);
+GL_APICALL void GL_APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker);
+GL_APICALL void GL_APIENTRY glPopGroupMarkerEXT (void);
+#endif
+typedef void (GL_APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker);
+typedef void (GL_APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker);
+typedef void (GL_APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void);
+#endif
+
 /* GL_EXT_discard_framebuffer */
 #ifndef GL_EXT_discard_framebuffer
 #define GL_EXT_discard_framebuffer 1
@@ -786,6 +996,17 @@ GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numA
 typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
 #endif
 
+/* GL_EXT_multisampled_render_to_texture */
+#ifndef GL_EXT_multisampled_render_to_texture
+#define GL_EXT_multisampled_render_to_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum, GLsizei, GLenum, GLsizei, GLsizei);
+GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLsizei);
+#endif
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#endif
+
 #ifndef GL_EXT_multi_draw_arrays
 #define GL_EXT_multi_draw_arrays 1
 #ifdef GL_GLEXT_PROTOTYPES
@@ -796,11 +1017,134 @@ typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *fir
 typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
 #endif
 
+/* GL_EXT_occlusion_query_boolean */
+#ifndef GL_EXT_occlusion_query_boolean
+#define GL_EXT_occlusion_query_boolean 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGenQueriesEXT (GLsizei n, GLuint *ids);
+GL_APICALL void GL_APIENTRY glDeleteQueriesEXT (GLsizei n, const GLuint *ids);
+GL_APICALL GLboolean GL_APIENTRY glIsQueryEXT (GLuint id);
+GL_APICALL void GL_APIENTRY glBeginQueryEXT (GLenum target, GLuint id);
+GL_APICALL void GL_APIENTRY glEndQueryEXT (GLenum target);
+GL_APICALL void GL_APIENTRY glGetQueryivEXT (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetQueryObjectuivEXT (GLuint id, GLenum pname, GLuint *params);
+#endif
+typedef void (GL_APIENTRYP PFNGLGENQUERIESEXTPROC) (GLsizei n, GLuint *ids);
+typedef void (GL_APIENTRYP PFNGLDELETEQUERIESEXTPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (GL_APIENTRYP PFNGLISQUERYEXTPROC) (GLuint id);
+typedef void (GL_APIENTRYP PFNGLBEGINQUERYEXTPROC) (GLenum target, GLuint id);
+typedef void (GL_APIENTRYP PFNGLENDQUERYEXTPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETQUERYIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVEXTPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
 /* GL_EXT_read_format_bgra */
 #ifndef GL_EXT_read_format_bgra
 #define GL_EXT_read_format_bgra 1
 #endif
 
+/* GL_EXT_robustness */
+#ifndef GL_EXT_robustness
+#define GL_EXT_robustness 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void);
+GL_APICALL void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+GL_APICALL void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, float *params);
+GL_APICALL void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#endif
+typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void);
+typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, float *params);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#endif
+
+/* GL_EXT_separate_shader_objects */
+#ifndef GL_EXT_separate_shader_objects
+#define GL_EXT_separate_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glUseProgramStagesEXT (GLuint pipeline, GLbitfield stages, GLuint program);
+GL_APICALL void GL_APIENTRY glActiveShaderProgramEXT (GLuint pipeline, GLuint program);
+GL_APICALL GLuint GL_APIENTRY glCreateShaderProgramvEXT (GLenum type, GLsizei count, const GLchar **strings);
+GL_APICALL void GL_APIENTRY glBindProgramPipelineEXT (GLuint pipeline);
+GL_APICALL void GL_APIENTRY glDeleteProgramPipelinesEXT (GLsizei n, const GLuint *pipelines);
+GL_APICALL void GL_APIENTRY glGenProgramPipelinesEXT (GLsizei n, GLuint *pipelines);
+GL_APICALL GLboolean GL_APIENTRY glIsProgramPipelineEXT (GLuint pipeline);
+GL_APICALL void GL_APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value);
+GL_APICALL void GL_APIENTRY glGetProgramPipelineivEXT (GLuint pipeline, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint x);
+GL_APICALL void GL_APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint x, GLint y);
+GL_APICALL void GL_APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint x, GLint y, GLint z);
+GL_APICALL void GL_APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint x, GLint y, GLint z, GLint w);
+GL_APICALL void GL_APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat x);
+GL_APICALL void GL_APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat x, GLfloat y);
+GL_APICALL void GL_APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void GL_APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void GL_APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glValidateProgramPipelineEXT (GLuint pipeline);
+GL_APICALL void GL_APIENTRY glGetProgramPipelineInfoLogEXT (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+#endif
+typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESEXTPROC) (GLuint pipeline, GLbitfield stages, GLuint program);
+typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMEXTPROC) (GLuint pipeline, GLuint program);
+typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVEXTPROC) (GLenum type, GLsizei count, const GLchar **strings);
+typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESEXTPROC) (GLsizei n, const GLuint *pipelines);
+typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESEXTPROC) (GLsizei n, GLuint *pipelines);
+typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVEXTPROC) (GLuint pipeline, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint x);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint x, GLint y);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint x, GLint y, GLint z);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint x, GLint y, GLint z, GLint w);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat x);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+#endif
+
+/* GL_EXT_shader_texture_lod */
+#ifndef GL_EXT_shader_texture_lod
+#define GL_EXT_shader_texture_lod 1
+#endif
+
+/* GL_EXT_shadow_samplers */
+#ifndef GL_EXT_shadow_samplers
+#define GL_EXT_shadow_samplers 1
+#endif
+
+/* GL_EXT_sRGB */
+#ifndef GL_EXT_sRGB
+#define GL_EXT_sRGB 1
+#endif
+
+/* GL_EXT_texture_compression_dxt1 */
+#ifndef GL_EXT_texture_compression_dxt1
+#define GL_EXT_texture_compression_dxt1 1
+#endif
+
 /* GL_EXT_texture_filter_anisotropic */
 #ifndef GL_EXT_texture_filter_anisotropic
 #define GL_EXT_texture_filter_anisotropic 1
@@ -811,19 +1155,47 @@ typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GL
 #define GL_EXT_texture_format_BGRA8888 1
 #endif
 
+/* GL_EXT_texture_rg */
+#ifndef GL_EXT_texture_rg
+#define GL_EXT_texture_rg 1
+#endif
+
+/* GL_EXT_texture_storage */
+#ifndef GL_EXT_texture_storage
+#define GL_EXT_texture_storage 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_APICALL void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+GL_APICALL void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_APICALL void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
 /* GL_EXT_texture_type_2_10_10_10_REV */
 #ifndef GL_EXT_texture_type_2_10_10_10_REV
 #define GL_EXT_texture_type_2_10_10_10_REV 1
 #endif
 
-/* GL_EXT_texture_compression_dxt1 */
-#ifndef GL_EXT_texture_compression_dxt1
-#define GL_EXT_texture_compression_dxt1 1
+/* GL_EXT_unpack_subimage */
+#ifndef GL_EXT_unpack_subimage
+#define GL_EXT_unpack_subimage 1
 #endif
 
-/* GL_EXT_shader_texture_lod */
-#ifndef GL_EXT_shader_texture_lod
-#define GL_EXT_shader_texture_lod 1
+/*------------------------------------------------------------------------*
+ * DMP extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_DMP_shader_binary */
+#ifndef GL_DMP_shader_binary
+#define GL_DMP_shader_binary 1
 #endif
 
 /*------------------------------------------------------------------------*
@@ -865,6 +1237,36 @@ typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG) (GLenum targ
  * NV extension functions
  *------------------------------------------------------------------------*/
 
+/* GL_NV_coverage_sample */
+#ifndef GL_NV_coverage_sample
+#define GL_NV_coverage_sample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask);
+GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation);
+#endif
+typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask);
+typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation);
+#endif
+
+/* GL_NV_depth_nonlinear */
+#ifndef GL_NV_depth_nonlinear
+#define GL_NV_depth_nonlinear 1
+#endif
+
+/* GL_NV_draw_buffers */
+#ifndef GL_NV_draw_buffers
+#define GL_NV_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawBuffersNV (GLsizei n, const GLenum *bufs);
+#endif
+typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSNVPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+/* GL_NV_fbo_color_attachments */
+#ifndef GL_NV_fbo_color_attachments
+#define GL_NV_fbo_color_attachments 1
+#endif
+
 /* GL_NV_fence */
 #ifndef GL_NV_fence
 #define GL_NV_fence 1
@@ -886,26 +1288,58 @@ typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
 typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
 #endif
 
-/* GL_NV_coverage_sample */
-#ifndef GL_NV_coverage_sample
-#define GL_NV_coverage_sample 1
+/* GL_NV_read_buffer */
+#ifndef GL_NV_read_buffer
+#define GL_NV_read_buffer 1
 #ifdef GL_GLEXT_PROTOTYPES
-GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask);
-GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation);
+GL_APICALL void GL_APIENTRY glReadBufferNV (GLenum mode);
 #endif
-typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask);
-typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation);
+typedef void (GL_APIENTRYP PFNGLREADBUFFERNVPROC) (GLenum mode);
 #endif
 
-/* GL_NV_depth_nonlinear */
-#ifndef GL_NV_depth_nonlinear
-#define GL_NV_depth_nonlinear 1
+/* GL_NV_read_buffer_front */
+#ifndef GL_NV_read_buffer_front
+#define GL_NV_read_buffer_front 1
+#endif
+
+/* GL_NV_read_depth */
+#ifndef GL_NV_read_depth
+#define GL_NV_read_depth 1
+#endif
+
+/* GL_NV_read_depth_stencil */
+#ifndef GL_NV_read_depth_stencil
+#define GL_NV_read_depth_stencil 1
+#endif
+
+/* GL_NV_read_stencil */
+#ifndef GL_NV_read_stencil
+#define GL_NV_read_stencil 1
+#endif
+
+/* GL_NV_texture_compression_s3tc_update */
+#ifndef GL_NV_texture_compression_s3tc_update
+#define GL_NV_texture_compression_s3tc_update 1
+#endif
+
+/* GL_NV_texture_npot_2D_mipmap */
+#ifndef GL_NV_texture_npot_2D_mipmap
+#define GL_NV_texture_npot_2D_mipmap 1
 #endif
 
 /*------------------------------------------------------------------------*
  * QCOM extension functions
  *------------------------------------------------------------------------*/
 
+/* GL_QCOM_alpha_test */
+#ifndef GL_QCOM_alpha_test
+#define GL_QCOM_alpha_test 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glAlphaFuncQCOM (GLenum func, GLclampf ref);
+#endif
+typedef void (GL_APIENTRYP PFNGLALPHAFUNCQCOMPROC) (GLenum func, GLclampf ref);
+#endif
+
 /* GL_QCOM_driver_control */
 #ifndef GL_QCOM_driver_control
 #define GL_QCOM_driver_control 1
@@ -989,6 +1423,43 @@ typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask);
 #define GL_VIV_shader_binary 1
 #endif
 
+/*------------------------------------------------------------------------*
+ * Additional tokens ..
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_texture_compression_s3tc */
+#ifndef GL_EXT_texture_compression_s3tc
+/* GL_COMPRESSED_RGB_S3TC_DXT1_EXT defined in GL_EXT_texture_compression_dxt1 already. */
+/* GL_COMPRESSED_RGBA_S3TC_DXT1_EXT defined in GL_EXT_texture_compression_dxt1 already. */
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
+#endif
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_EXT_texture_compression_s3tc 1
+#endif
+
+/* GL_EXT_texture_array */
+#ifndef GL_EXT_texture_array
+#define GL_TEXTURE_2D_ARRAY_EXT           0x8C1A
+#define GL_SAMPLER_2D_ARRAY_EXT           0x8DC1
+#define GL_TEXTURE_BINDING_2D_ARRAY_EXT   0x8C1D
+#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT   0x88FF
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4
+#endif
+#ifndef GL_EXT_texture_array
+#define GL_EXT_texture_array 1
+#endif
+
+/* GL_EXT_packed_float */
+#ifndef GL_EXT_packed_float
+#define GL_R11F_G11F_B10F_EXT                           0x8C3A
+#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT             0x8C3B
+#define GL_RGBA_SIGNED_COMPONENTS_EXT                   0x8C3C
+#endif
+#ifndef GL_EXT_packed_float
+#define GL_EXT_packed_float 1
+#endif
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/make/stub_includes/opengl/macosx-window-system.h b/make/stub_includes/opengl/macosx-window-system.h
index 347de62..e7fe135 100644
--- a/make/stub_includes/opengl/macosx-window-system.h
+++ b/make/stub_includes/opengl/macosx-window-system.h
@@ -55,7 +55,7 @@ void setContextTextureImageToPBuffer(NSOpenGLContext* ctx, NSOpenGLPixelBuffer*
 // NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSView* view, Bool opaque);
 NSOpenGLLayer* createNSOpenGLLayer(NSOpenGLContext* ctx, NSOpenGLPixelFormat* fmt, NSOpenGLPixelBuffer* pbuffer, Bool opaque, int texWidth, int texHeight);
 void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval);
-void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_ms);
+void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros);
 void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* glLayer);
 void releaseNSOpenGLLayer(NSOpenGLLayer *glLayer);
 
@@ -67,3 +67,6 @@ void setSwapInterval(NSOpenGLContext* ctx, int interval);
 Bool setGammaRamp(int tableSize, float* redRamp, float* greenRamp, float* blueRamp);
 void resetGammaRamp();
 
+/* returns the screen refresh rate in Hz */
+int getScreenRefreshRate(int scrn_idx);
+
diff --git a/make/stub_includes/win32/windows.h b/make/stub_includes/win32/windows.h
index f2f3900..51ebbdc 100644
--- a/make/stub_includes/win32/windows.h
+++ b/make/stub_includes/win32/windows.h
@@ -47,13 +47,3 @@ typedef HANDLE              HPBUFFERARB;
 typedef HANDLE              HPBUFFEREXT;
 typedef HANDLE              HGPUNV;
 
-typedef struct tagRECT {
-    LONG left;
-    LONG top;
-    LONG right;
-    LONG bottom;
-} RECT;
-
-typedef RECT*               PRECT;
-typedef RECT*               LPRECT;
-
diff --git a/make/stub_includes/win32/wingdi.h b/make/stub_includes/win32/wingdi.h
index b02512c..2d3e332 100644
--- a/make/stub_includes/win32/wingdi.h
+++ b/make/stub_includes/win32/wingdi.h
@@ -6,177 +6,24 @@
  *     This file has no copyright assigned and is placed in the Public Domain.
  *     No warranty is given; refer to the file DISCLAIMER.PD within this package.
  *
- * Editions / Removals and a split (wingdi.h -> wingdi.h + winwgl.h) were made by the JogAmp Community, 2010
+ * Editions / Removals and a split (wingdi.h -> wingdi.h + wingdi_types.h + winwgl.h) were made by the JogAmp Community, 2010, 2012
  */
 
-#ifndef WGL_GDI_VERSION_1_X
+#include "wingdi_types.h"
 
-typedef struct tagRGBQUAD {
-    BYTE rgbBlue;
-    BYTE rgbGreen;
-    BYTE rgbRed;
-    BYTE rgbReserved;
-} RGBQUAD;
-
-typedef RGBQUAD *LPRGBQUAD;
-
-typedef struct tagBITMAPINFOHEADER {
-    DWORD biSize;
-    LONG biWidth;
-    LONG biHeight;
-    WORD biPlanes;
-    WORD biBitCount;
-    DWORD biCompression;
-    DWORD biSizeImage;
-    LONG biXPelsPerMeter;
-    LONG biYPelsPerMeter;
-    DWORD biClrUsed;
-    DWORD biClrImportant;
-} BITMAPINFOHEADER,*LPBITMAPINFOHEADER,*PBITMAPINFOHEADER;
-
-typedef struct tagBITMAPINFO {
-    BITMAPINFOHEADER bmiHeader;
-    RGBQUAD bmiColors[1];
-} BITMAPINFO,*LPBITMAPINFO,*PBITMAPINFO;
-
-/* constants for the biCompression field */
-#define BI_RGB        0
-#define BI_RLE8       1
-#define BI_RLE4       2
-#define BI_BITFIELDS  3
-
-/* DIB color table identifiers */
-
-#define DIB_RGB_COLORS      0 /* color table in RGBs */
-#define DIB_PAL_COLORS      1 /* color table in palette indices */
-
-typedef struct tagPIXELFORMATDESCRIPTOR {
-    WORD nSize;
-    WORD nVersion;
-    DWORD dwFlags;
-    BYTE iPixelType;
-    BYTE cColorBits;
-    BYTE cRedBits;
-    BYTE cRedShift;
-    BYTE cGreenBits;
-    BYTE cGreenShift;
-    BYTE cBlueBits;
-    BYTE cBlueShift;
-    BYTE cAlphaBits;
-    BYTE cAlphaShift;
-    BYTE cAccumBits;
-    BYTE cAccumRedBits;
-    BYTE cAccumGreenBits;
-    BYTE cAccumBlueBits;
-    BYTE cAccumAlphaBits;
-    BYTE cDepthBits;
-    BYTE cStencilBits;
-    BYTE cAuxBuffers;
-    BYTE iLayerType;
-    BYTE bReserved;
-    DWORD dwLayerMask;
-    DWORD dwVisibleMask;
-    DWORD dwDamageMask;
-} PIXELFORMATDESCRIPTOR,*PPIXELFORMATDESCRIPTOR,*LPPIXELFORMATDESCRIPTOR;
-
-#define PFD_TYPE_RGBA 0
-#define PFD_TYPE_COLORINDEX 1
-
-#define PFD_MAIN_PLANE 0
-#define PFD_OVERLAY_PLANE 1
-#define PFD_UNDERLAY_PLANE (-1)
-
-#define PFD_DOUBLEBUFFER 0x00000001
-#define PFD_STEREO 0x00000002
-#define PFD_DRAW_TO_WINDOW 0x00000004
-#define PFD_DRAW_TO_BITMAP 0x00000008
-#define PFD_SUPPORT_GDI 0x00000010
-#define PFD_SUPPORT_OPENGL 0x00000020
-#define PFD_GENERIC_FORMAT 0x00000040
-#define PFD_NEED_PALETTE 0x00000080
-#define PFD_NEED_SYSTEM_PALETTE 0x00000100
-#define PFD_SWAP_EXCHANGE 0x00000200
-#define PFD_SWAP_COPY 0x00000400
-#define PFD_SWAP_LAYER_BUFFERS 0x00000800
-#define PFD_GENERIC_ACCELERATED 0x00001000
-#define PFD_SUPPORT_DIRECTDRAW 0x00002000
-
-#define PFD_DEPTH_DONTCARE 0x20000000
-#define PFD_DOUBLEBUFFER_DONTCARE 0x40000000
-#define PFD_STEREO_DONTCARE 0x80000000
-
-/* error codes (from winerror.h) */
-/* FIXME: these should have a trailing "L" but apparently PCPP doesn't handle that syntax */
-#define ERROR_SUCCESS                    0
-#define ERROR_INVALID_PIXEL_FORMAT       2000
-#define ERROR_NO_SYSTEM_RESOURCES        1450
-#define ERROR_INVALID_DATA               13
-#define ERROR_PROC_NOT_FOUND             127
-#define ERROR_INVALID_WINDOW_HANDLE      1400
-
-/*
- * ShowWindow() Commands
- */
-#define SW_HIDE             0
-#define SW_SHOWNORMAL       1
-#define SW_NORMAL           1
-#define SW_SHOWMINIMIZED    2
-#define SW_SHOWMAXIMIZED    3
-#define SW_MAXIMIZE         3
-#define SW_SHOWNOACTIVATE   4
-#define SW_SHOW             5
-#define SW_MINIMIZE         6
-#define SW_SHOWMINNOACTIVE  7
-#define SW_SHOWNA           8
-#define SW_RESTORE          9
-#define SW_SHOWDEFAULT      10
-#define SW_FORCEMINIMIZE    11
-#define SW_MAX              11
-
-/**
- * GetObjectType() Command
- */
-#define OBJ_PEN 1
-#define OBJ_BRUSH 2
-#define OBJ_DC 3
-#define OBJ_METADC 4
-#define OBJ_PAL 5
-#define OBJ_FONT 6
-#define OBJ_BITMAP 7
-#define OBJ_REGION 8
-#define OBJ_METAFILE 9
-#define OBJ_MEMDC 10
-#define OBJ_EXTPEN 11
-#define OBJ_ENHMETADC 12
-#define OBJ_ENHMETAFILE 13
-#define OBJ_COLORSPACE 14
-
-#endif /*  WGL_GDI_VERSION_1_X */
-
-#ifndef WGL_GDI_VERSION_1_X
-#define WGL_GDI_VERSION_1_X
+#ifndef GDI_VERSION_1_X
+#define GDI_VERSION_1_X
 
 // Windows routines
 WINBASEAPI DWORD WINAPI GetLastError(VOID);
 
-// OpenGL-related routines
+// GDI / ICD OpenGL-related routines
 WINGDIAPI int   WINAPI ChoosePixelFormat(HDC, CONST PIXELFORMATDESCRIPTOR *);
 WINGDIAPI int   WINAPI DescribePixelFormat(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
 WINGDIAPI int   WINAPI GetPixelFormat(HDC);
 WINGDIAPI BOOL  WINAPI SetPixelFormat(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
 WINGDIAPI BOOL  WINAPI SwapBuffers(HDC);
 
-/* --- FIXME: need to handle these entry points! 
-WINGDIAPI HGLRC WINAPI wglCreateLayerContext(HDC, int);
-WINGDIAPI BOOL  WINAPI wglUseFontBitmapsA(HDC, DWORD, DWORD, DWORD);
-WINGDIAPI BOOL  WINAPI wglUseFontBitmapsW(HDC, DWORD, DWORD, DWORD);
-#ifdef UNICODE
-#define wglUseFontBitmaps  wglUseFontBitmapsW
-#else
-#define wglUseFontBitmaps wglUseFontBitmapsA
-#endif // !UNICODE
-*/
-
 // Routines related to bitmap creation for off-screen rendering
 WINGDIAPI HDC     WINAPI CreateCompatibleDC(HDC);
 WINGDIAPI HBITMAP WINAPI CreateDIBSection(HDC, CONST BITMAPINFO *, UINT, VOID **, HANDLE, DWORD);
@@ -207,5 +54,5 @@ WINUSERAPI BOOL WINAPI SetProcessAffinityMask(HANDLE hProcess,DWORD_PTR dwProces
 WINGDIAPI BOOL        WINAPI GetDeviceGammaRamp(HDC,LPVOID);
 WINGDIAPI BOOL        WINAPI SetDeviceGammaRamp(HDC,LPVOID);
 
-#endif /*  WGL_GDI_VERSION_1_X */
+#endif /*  GDI_VERSION_1_X */
 
diff --git a/make/stub_includes/win32/wingdi.h b/make/stub_includes/win32/wingdi_types.h
similarity index 60%
copy from make/stub_includes/win32/wingdi.h
copy to make/stub_includes/win32/wingdi_types.h
index b02512c..d23502c 100644
--- a/make/stub_includes/win32/wingdi.h
+++ b/make/stub_includes/win32/wingdi_types.h
@@ -6,10 +6,20 @@
  *     This file has no copyright assigned and is placed in the Public Domain.
  *     No warranty is given; refer to the file DISCLAIMER.PD within this package.
  *
- * Editions / Removals and a split (wingdi.h -> wingdi.h + winwgl.h) were made by the JogAmp Community, 2010
+ * Editions / Removals and a split (wingdi.h -> wingdi.h + wingdi_types.h + winwgl.h) were made by the JogAmp Community, 2010, 2012
  */
 
-#ifndef WGL_GDI_VERSION_1_X
+#ifndef GDI_VERSION_1_X
+
+typedef struct tagRECT {
+    LONG left;
+    LONG top;
+    LONG right;
+    LONG bottom;
+} RECT;
+
+typedef RECT*               PRECT;
+typedef RECT*               LPRECT;
 
 typedef struct tagRGBQUAD {
     BYTE rgbBlue;
@@ -151,61 +161,6 @@ typedef struct tagPIXELFORMATDESCRIPTOR {
 #define OBJ_ENHMETAFILE 13
 #define OBJ_COLORSPACE 14
 
-#endif /*  WGL_GDI_VERSION_1_X */
-
-#ifndef WGL_GDI_VERSION_1_X
-#define WGL_GDI_VERSION_1_X
-
-// Windows routines
-WINBASEAPI DWORD WINAPI GetLastError(VOID);
-
-// OpenGL-related routines
-WINGDIAPI int   WINAPI ChoosePixelFormat(HDC, CONST PIXELFORMATDESCRIPTOR *);
-WINGDIAPI int   WINAPI DescribePixelFormat(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
-WINGDIAPI int   WINAPI GetPixelFormat(HDC);
-WINGDIAPI BOOL  WINAPI SetPixelFormat(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
-WINGDIAPI BOOL  WINAPI SwapBuffers(HDC);
-
-/* --- FIXME: need to handle these entry points! 
-WINGDIAPI HGLRC WINAPI wglCreateLayerContext(HDC, int);
-WINGDIAPI BOOL  WINAPI wglUseFontBitmapsA(HDC, DWORD, DWORD, DWORD);
-WINGDIAPI BOOL  WINAPI wglUseFontBitmapsW(HDC, DWORD, DWORD, DWORD);
-#ifdef UNICODE
-#define wglUseFontBitmaps  wglUseFontBitmapsW
-#else
-#define wglUseFontBitmaps wglUseFontBitmapsA
-#endif // !UNICODE
-*/
-
-// Routines related to bitmap creation for off-screen rendering
-WINGDIAPI HDC     WINAPI CreateCompatibleDC(HDC);
-WINGDIAPI HBITMAP WINAPI CreateDIBSection(HDC, CONST BITMAPINFO *, UINT, VOID **, HANDLE, DWORD);
-WINGDIAPI BOOL    WINAPI DeleteDC(HDC);
-WINGDIAPI BOOL    WINAPI DeleteObject(HGDIOBJ);
-WINGDIAPI HGDIOBJ WINAPI SelectObject(HDC, HGDIOBJ);
-
-// Routines for creation of a dummy window, device context and OpenGL
-// context for the purposes of getting wglChoosePixelFormatARB and
-// associated routines
-           HINSTANCE   GetApplicationHandle();
-WINUSERAPI BOOL WINAPI ShowWindow(HWND hWnd, int nCmdShow);
-WINUSERAPI HDC  WINAPI GetDC(HWND);
-WINUSERAPI int  WINAPI ReleaseDC(HWND hWnd, HDC hDC);
-WINUSERAPI HWND WINAPI WindowFromDC(HDC hDC); // avail in >= Win2k
-WINUSERAPI BOOL WINAPI GetClientRect(HWND hwnd, LPRECT lpRect);
-WINUSERAPI BOOL WINAPI DestroyWindow(HWND hWnd);
-WINUSERAPI DWORD WINAPI GetObjectType(HGDIOBJ h);
-WINUSERAPI BOOL WINAPI IsWindowVisible(HWND hWnd);
-WINUSERAPI BOOL WINAPI IsWindow(HWND hWnd);
-
-WINUSERAPI HANDLE WINAPI GetCurrentProcess(void);
-WINUSERAPI BOOL WINAPI GetProcessAffinityMask(HANDLE hProcess,PDWORD_PTR lpProcessAffinityMask,PDWORD_PTR lpSystemAffinityMask);
-WINUSERAPI BOOL WINAPI SetProcessAffinityMask(HANDLE hProcess,DWORD_PTR dwProcessAffinityMask);
-
-
-// Routines for changing gamma ramp of display device
-WINGDIAPI BOOL        WINAPI GetDeviceGammaRamp(HDC,LPVOID);
-WINGDIAPI BOOL        WINAPI SetDeviceGammaRamp(HDC,LPVOID);
-
-#endif /*  WGL_GDI_VERSION_1_X */
+#endif /*  GDI_VERSION_1_X */
+
 
diff --git a/make/stub_includes/win32/winwgl.h b/make/stub_includes/win32/winwgl.h
index 5e9cc2f..c0dfb9b 100644
--- a/make/stub_includes/win32/winwgl.h
+++ b/make/stub_includes/win32/winwgl.h
@@ -6,9 +6,11 @@
  *     This file has no copyright assigned and is placed in the Public Domain.
  *     No warranty is given; refer to the file DISCLAIMER.PD within this package.
  *
- * Editions / Removals and a split (wingdi.h -> wingdi.h + winwgl.h) were made by the JogAmp Community, 2010
+ * Editions / Removals and a split (wingdi.h -> wingdi.h + wingdi_types.h + winwgl.h) were made by the JogAmp Community, 2010, 2012
  */
 
+#include "wingdi_types.h"
+
 #ifndef WGL_GDI_VERSION_1_X
 
 /* layer types */
@@ -59,6 +61,13 @@ WINGDIAPI BOOL  WINAPI wglShareLists(HGLRC, HGLRC);
 WINGDIAPI PROC  WINAPI wglGetProcAddress(LPCSTR);
 WINGDIAPI BOOL  WINAPI wglSwapLayerBuffers(HDC,UINT);
 
+// Runtime Link GDI/OpenGL-related routines
+WINGDIAPI int   WINAPI wglChoosePixelFormat(HDC, CONST PIXELFORMATDESCRIPTOR *);
+WINGDIAPI int   WINAPI wglDescribePixelFormat(HDC, int, UINT, LPPIXELFORMATDESCRIPTOR);
+WINGDIAPI int   WINAPI wglGetPixelFormat(HDC);
+WINGDIAPI BOOL  WINAPI wglSetPixelFormat(HDC, int, CONST PIXELFORMATDESCRIPTOR *);
+WINGDIAPI BOOL  WINAPI wglSwapBuffers(HDC);
+
 /* --- FIXME: need to handle these entry points! 
 WINGDIAPI HGLRC WINAPI wglCreateLayerContext(HDC, int);
 WINGDIAPI BOOL  WINAPI wglUseFontBitmapsA(HDC, DWORD, DWORD, DWORD);
diff --git a/make/stub_includes/x11/window-lib.c b/make/stub_includes/x11/window-lib.c
index 7b6da3c..bc5df4a 100644
--- a/make/stub_includes/x11/window-lib.c
+++ b/make/stub_includes/x11/window-lib.c
@@ -8,6 +8,8 @@
 #define _Xconst const
 #endif /* _Xconst */
 
+#include <XineramaHelper.h>
+
 extern intptr_t XSynchronize(Display *display, Bool onoff);
 
 extern int XFlush(Display *display);
@@ -52,9 +54,6 @@ extern int XFree(
     void*		/* data */
 );
 
-// Helper routine for querying whether Xinerama is enabled.
-Bool XineramaEnabled(Display* display);
-
 // Routines for changing gamma settings.
 // Note that these are not currently supported on Solaris.
 Bool XF86VidModeGetGammaRampSize(
diff --git a/src/android/com/jogamp/android/launcher/ClassLoaderUtil.java b/src/android/com/jogamp/android/launcher/ClassLoaderUtil.java
deleted file mode 100644
index 4f0bf46..0000000
--- a/src/android/com/jogamp/android/launcher/ClassLoaderUtil.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * Copyright 2011 JogAmp Community. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- * 
- *    1. Redistributions of source code must retain the above copyright notice, this list of
- *       conditions and the following disclaimer.
- * 
- *    2. Redistributions in binary form must reproduce the above copyright notice, this list
- *       of conditions and the following disclaimer in the documentation and/or other materials
- *       provided with the distribution.
- * 
- * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * The views and conclusions contained in the software and documentation are those of the
- * authors and should not be interpreted as representing official policies, either expressed
- * or implied, of JogAmp Community.
- */
-
-package com.jogamp.android.launcher;
-
-import java.io.File;
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.util.Log;
-import dalvik.system.DexClassLoader;
-
-public class ClassLoaderUtil {
-   private static final String TAG = "JogampClassLoader";
-   
-   public static final String packageGlueGen = "com.jogamp.common";       
-   public static final String packageJogl = "javax.media.opengl";
-   
-   public static final String dexPathName= "jogampDex";
-   
-   private static LauncherTempFileCache tmpFileCache = null;
-   private static ClassLoader jogAmpClassLoader = null;
-   
-   public static synchronized ClassLoader createJogampClassLoaderSingleton(Context ctx, String userPackageName) {
-       if(null==jogAmpClassLoader) {
-           if(null!=tmpFileCache) {
-               throw new InternalError("XXX0");
-           }
-           if(!LauncherTempFileCache.initSingleton(ctx)) {
-               throw new InternalError("TempFileCache initialization error");
-           }
-           tmpFileCache = new LauncherTempFileCache();
-           if(!tmpFileCache.isValid()) {
-               throw new InternalError("TempFileCache instantiation error");                
-           }
-           final ApplicationInfo ai = ctx.getApplicationInfo();
-           Log.d(TAG, "S: userPackageName: "+userPackageName+", dataDir: "+ai.dataDir+", nativeLibraryDir: "+ai.nativeLibraryDir);
-    
-           final String appDir = new File(ai.dataDir).getParent();
-           final String libSub = ai.nativeLibraryDir.substring(ai.nativeLibraryDir.lastIndexOf('/')+1);
-           Log.d(TAG, "S: appDir: "+appDir+", libSub: "+libSub);
-           
-           final String libPathName = appDir + "/" + packageGlueGen + "/" + libSub + "/:" +
-                                      appDir + "/" + packageJogl + "/" + libSub + "/" ;
-           Log.d(TAG, "S: libPath: "+libPathName);
-                   
-           String apkGlueGen = null;
-           String apkJogl = null;
-       
-           try {
-               apkGlueGen = ctx.getPackageManager().getApplicationInfo(packageGlueGen,0).sourceDir;
-               apkJogl = ctx.getPackageManager().getApplicationInfo(packageJogl,0).sourceDir;
-           } catch (PackageManager.NameNotFoundException e) {
-               Log.d(TAG, "error: "+e, e);
-           }
-           if(null == apkGlueGen || null == apkJogl) {
-               Log.d(TAG, "not found: gluegen <"+apkGlueGen+">, jogl <"+apkJogl+">");
-               return null;
-           }
-           
-           final String cp = apkGlueGen + ":" + apkJogl ;
-           Log.d(TAG, "jogamp cp: " + cp);
-       
-           final File dexPath = new File(tmpFileCache.getTempDir(), dexPathName);
-           Log.d(TAG, "jogamp dexPath: " + dexPath.getAbsolutePath());
-           dexPath.mkdir();
-           jogAmpClassLoader = new DexClassLoader(cp, dexPath.getAbsolutePath(), libPathName, ctx.getClassLoader());
-       } else {
-           if(null==tmpFileCache) {
-               throw new InternalError("XXX1");
-           }           
-       }
-       
-       String apkUser = null;
-       try {
-           apkUser = ctx.getPackageManager().getApplicationInfo(userPackageName,0).sourceDir;
-       } catch (PackageManager.NameNotFoundException e) {
-           Log.d(TAG, "error: "+e, e);
-       }
-       if(null == apkUser) {
-           Log.d(TAG, "not found: user apk <"+apkUser+">");
-           return null;
-       }
-       
-       Log.d(TAG, "user cp: " + apkUser);
-       final File dexPath = new File(tmpFileCache.getTempDir(), userPackageName);
-       Log.d(TAG, "user dexPath: " + dexPath.getAbsolutePath());
-       dexPath.mkdir();
-       ClassLoader cl = new DexClassLoader(apkUser, dexPath.getAbsolutePath(), null, jogAmpClassLoader);
-       Log.d(TAG, "cl: " + cl);
-       // setAPKClassLoader(dexLoader);
-       
-       return cl;
-   }
-
-}
diff --git a/src/android/com/jogamp/android/launcher/LauncherTempFileCache.java b/src/android/com/jogamp/android/launcher/LauncherTempFileCache.java
deleted file mode 100644
index 9d98d07..0000000
--- a/src/android/com/jogamp/android/launcher/LauncherTempFileCache.java
+++ /dev/null
@@ -1,477 +0,0 @@
-/**
- * Copyright 2011 JogAmp Community. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- *
- *    1. Redistributions of source code must retain the above copyright notice, this list of
- *       conditions and the following disclaimer.
- *
- *    2. Redistributions in binary form must reproduce the above copyright notice, this list
- *       of conditions and the following disclaimer in the documentation and/or other materials
- *       provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * The views and conclusions contained in the software and documentation are those of the
- * authors and should not be interpreted as representing official policies, either expressed
- * or implied, of JogAmp Community.
- */
-package com.jogamp.android.launcher;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-
-import android.content.Context;
-
-public class LauncherTempFileCache {
-    private static final boolean DEBUG = true;
-
-    // Lifecycle: For all JVMs, ClassLoader and times.
-    private static final String tmpDirPrefix = "jogamp.tmp.cache";
-    
-    // Get the value of the tmproot system property
-    // Lifecycle: For all JVMs and ClassLoader
-    /* package */ static final String tmpRootPropName = "jnlp.jogamp.tmp.cache.root";
-
-    // Flag indicating that we got a fatal error in the static initializer.
-    private static boolean staticInitError = false;
-    
-    private static File tmpBaseDir;
-
-    // String representing the name of the temp root directory relative to the
-    // tmpBaseDir. Its value is "jlnNNNNN", which is the unique filename created
-    // by File.createTempFile() without the ".tmp" extension.
-    //
-    // Lifecycle: For all JVMs and ClassLoader
-    //
-    private static String tmpRootPropValue;
-
-    private static File tmpRootDir;
-
-    // Flag indicating that we got a fatal error in the initializer.
-    private boolean initError = false;
-
-    private File individualTmpDir;
-    
-    /**
-     * Documented way to kick off static initialization
-     * @return true is static initialization was successful
-     */
-    public static synchronized boolean initSingleton(Context ctx) {
-        if(null == tmpRootDir && !staticInitError) {
-            // Create / initialize the temp root directory, starting the Reaper
-            // thread to reclaim old installations if necessary. If we get an
-            // exception, set an error code.
-            try {
-                initTmpRoot(ctx);
-            } catch (Exception ex) {
-                ex.printStackTrace();
-                staticInitError = true;
-            }
-        }
-        return !staticInitError;        
-    }
-    
-    /**
-     * This method is called by the static initializer to create / initialize
-     * the temp root directory that will hold the temp directories for this
-     * instance of the JVM. This is done as follows:
-     *
-     *     1. Synchronize on a global lock. Note that for this purpose we will
-     *        use System.out in the absence of a true global lock facility.
-     *        We are careful not to hold this lock too long.
-     *
-     *     2. Check for the existence of the "jnlp.applet.launcher.tmproot"
-     *        system property.
-     *
-     *         a. If set, then some other thread in a different ClassLoader has
-     *            already created the tmprootdir, so we just need to
-     *            use it. The remaining steps are skipped.
-     *
-     *         b. If not set, then we are the first thread in this JVM to run,
-     *            and we need to create the the tmprootdir.
-     *
-     *     3. Create the tmprootdir, along with the appropriate locks.
-     *        Note that we perform the operations in the following order,
-     *        prior to creating tmprootdir itself, to work around the fact that
-     *        the file creation and file lock steps are not atomic, and we need
-     *        to ensure that a newly-created tmprootdir isn't reaped by a
-     *        concurrently running JVM.
-     *
-     *            create jlnNNNN.tmp using File.createTempFile()
-     *            lock jlnNNNN.tmp
-     *            create jlnNNNN.lck while holding the lock on the .tmp file
-     *            lock jlnNNNN.lck
-     *
-     *        Since the Reaper thread will enumerate the list of *.lck files
-     *        before starting, we can guarantee that if there exists a *.lck file
-     *        for an active process, then the corresponding *.tmp file is locked
-     *        by that active process. This guarantee lets us avoid reaping an
-     *        active process' files.
-     *
-     *     4. Set the "jnlp.applet.launcher.tmproot" system property.
-     *
-     *     5. Add a shutdown hook to cleanup jlnNNNN.lck and jlnNNNN.tmp. We
-     *        don't actually expect that this shutdown hook will ever be called,
-     *        but the act of doing this, ensures that the locks never get
-     *        garbage-collected, which is necessary for correct behavior when
-     *        the first ClassLoader is later unloaded, while subsequent Applets
-     *        are still running.
-     *
-     *     6. Start the Reaper thread to cleanup old installations.
-     */
-    private static void initTmpRoot(Context ctx) throws IOException {
-        if (DEBUG) {
-            System.err.println("TempFileCache: Static Initialization ----------------------------------------------");
-            System.err.println("TempFileCache: Thread: "+Thread.currentThread().getName()+", CL 0x"+Integer.toHexString(LauncherTempFileCache.class.getClassLoader().hashCode()));
-        }
-
-        synchronized (System.out) {
-            // Get the name of the tmpbase directory.
-            {
-                final File tmpRoot = ctx.getDir("temp", Context.MODE_WORLD_READABLE);
-                tmpBaseDir = new File(tmpRoot, tmpDirPrefix);
-            }
-            tmpRootPropValue = System.getProperty(tmpRootPropName);
-
-            if (tmpRootPropValue == null) {
-                // Create the tmpbase directory if it doesn't already exist
-                tmpBaseDir.mkdir();
-                if (!tmpBaseDir.isDirectory()) {
-                    throw new IOException("Cannot create directory " + tmpBaseDir);
-                }
-
-                // Create ${tmpbase}/jlnNNNN.tmp then lock the file
-                File tmpFile = File.createTempFile("jln", ".tmp", tmpBaseDir);
-                if (DEBUG) {
-                    System.err.println("TempFileCache: tmpFile = " + tmpFile.getAbsolutePath());
-                }
-                final FileOutputStream tmpOut = new FileOutputStream(tmpFile);
-                final FileChannel tmpChannel = tmpOut.getChannel();
-                final FileLock tmpLock = tmpChannel.lock();
-
-                // Strip off the ".tmp" to get the name of the tmprootdir
-                String tmpFileName = tmpFile.getAbsolutePath();
-                String tmpRootName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp"));
-
-                // create ${tmpbase}/jlnNNNN.lck then lock the file
-                String lckFileName = tmpRootName + ".lck";
-                File lckFile = new File(lckFileName);
-                if (DEBUG) {
-                    System.err.println("TempFileCache: lckFile = " + lckFile.getAbsolutePath());
-                }
-                lckFile.createNewFile();
-                final FileOutputStream lckOut = new FileOutputStream(lckFile);
-                final FileChannel lckChannel = lckOut.getChannel();
-                final FileLock lckLock = lckChannel.lock();
-
-                // Create tmprootdir
-                tmpRootDir = new File(tmpRootName);
-                if (DEBUG) {
-                    System.err.println("TempFileCache: tmpRootDir = " + tmpRootDir.getAbsolutePath());
-                }
-                if (!tmpRootDir.mkdir()) {
-                    throw new IOException("Cannot create " + tmpRootDir);
-                }
-
-                // Add shutdown hook to cleanup the OutputStream, FileChannel,
-                // and FileLock for the jlnNNNN.lck and jlnNNNN.lck files.
-                // We do this so that the locks never get garbage-collected.
-                Runtime.getRuntime().addShutdownHook(new Thread() {
-                    /* @Override */
-                    public void run() {
-                        // NOTE: we don't really expect that this code will ever
-                        // be called. If it does, we will close the output
-                        // stream, which will in turn close the channel.
-                        // We will then release the lock.
-                        try {
-                            tmpOut.close();
-                            tmpLock.release();
-                            lckOut.close();
-                            lckLock.release();
-                        } catch (IOException ex) {
-                            // Do nothing
-                        }
-                    }
-                });
-
-                // Set the system property...
-                tmpRootPropValue = tmpRootName.substring(tmpRootName.lastIndexOf(File.separator) + 1);
-                System.setProperty(tmpRootPropName, tmpRootPropValue);
-                if (DEBUG) {
-                    System.err.println("TempFileCache: Setting " + tmpRootPropName + "=" + tmpRootPropValue);
-                }
-
-                // Start a new Reaper thread to do stuff...
-                Thread reaperThread = new Thread() {
-                    /* @Override */
-                    public void run() {
-                        deleteOldTempDirs();
-                    }
-                };
-                reaperThread.setName("TempFileCache-Reaper");
-                reaperThread.start();
-            } else {
-                // Make sure that the property is not set to an illegal value
-                if (tmpRootPropValue.indexOf('/') >= 0 ||
-                        tmpRootPropValue.indexOf(File.separatorChar) >= 0) {
-                    throw new IOException("Illegal value of: " + tmpRootPropName);
-                }
-
-                // Set tmpRootDir = ${tmpbase}/${jnlp.applet.launcher.tmproot}
-                if (DEBUG) {
-                    System.err.println("TempFileCache: Using existing value of: " +
-                            tmpRootPropName + "=" + tmpRootPropValue);
-                }
-                tmpRootDir = new File(tmpBaseDir, tmpRootPropValue);
-                if (DEBUG) {
-                    System.err.println("TempFileCache: tmpRootDir = " + tmpRootDir.getAbsolutePath());
-                }
-                if (!tmpRootDir.isDirectory()) {
-                    throw new IOException("Cannot access " + tmpRootDir);
-                }
-            }
-        }
-        if (DEBUG) {
-            System.err.println("------------------------------------------------------------------ (static ok: "+(!staticInitError)+")");
-        }
-    }
-
-    /**
-     * Called by the Reaper thread to delete old temp directories
-     * Only one of these threads will run per JVM invocation.
-     */
-    private static void deleteOldTempDirs() {
-        if (DEBUG) {
-            System.err.println("TempFileCache: *** Reaper: deleteOldTempDirs in " +
-                    tmpBaseDir.getAbsolutePath());
-        }
-
-        // enumerate list of jnl*.lck files, ignore our own jlnNNNN file
-        final String ourLockFile = tmpRootPropValue + ".lck";
-        FilenameFilter lckFilter = new FilenameFilter() {
-            /* @Override */
-            public boolean accept(File dir, String name) {
-                return name.endsWith(".lck") && !name.equals(ourLockFile);
-            }
-        };
-
-        // For each file <file>.lck in the list we will first try to lock
-        // <file>.tmp if that succeeds then we will try to lock <file>.lck
-        // (which should always succeed unless there is a problem). If we can
-        // get the lock on both files, then it must be an old installation, and
-        // we will delete it.
-        String[] fileNames = tmpBaseDir.list(lckFilter);
-        if (fileNames != null) {
-            for (int i = 0; i < fileNames.length; i++) {
-                String lckFileName = fileNames[i];
-                String tmpDirName = lckFileName.substring(0, lckFileName.lastIndexOf(".lck"));
-                String tmpFileName = tmpDirName + ".tmp";
-
-                File lckFile = new File(tmpBaseDir, lckFileName);
-                File tmpFile = new File(tmpBaseDir, tmpFileName);
-                File tmpDir = new File(tmpBaseDir, tmpDirName);
-
-                if (lckFile.exists() && tmpFile.exists() && tmpDir.isDirectory()) {
-                    FileOutputStream tmpOut = null;
-                    FileChannel tmpChannel = null;
-                    FileLock tmpLock = null;
-
-                    try {
-                        tmpOut = new FileOutputStream(tmpFile);
-                        tmpChannel = tmpOut.getChannel();
-                        tmpLock = tmpChannel.tryLock();
-                    } catch (Exception ex) {
-                        // Ignore exceptions
-                        if (DEBUG) {
-                            ex.printStackTrace();
-                        }
-                    }
-
-                    if (tmpLock != null) {
-                        FileOutputStream lckOut = null;
-                        FileChannel lckChannel = null;
-                        FileLock lckLock = null;
-
-                        try {
-                            lckOut = new FileOutputStream(lckFile);
-                            lckChannel = lckOut.getChannel();
-                            lckLock = lckChannel.tryLock();
-                        } catch (Exception ex) {
-                            if (DEBUG) {
-                                ex.printStackTrace();
-                            }
-                        }
-
-                        if (lckLock != null) {
-                            // Recursively remove the old tmpDir and all of
-                            // its contents
-                            removeAll(tmpDir);
-
-                            // Close the streams and delete the .lck and .tmp
-                            // files. Note that there is a slight race condition
-                            // in that another process could open a stream at
-                            // the same time we are trying to delete it, which will
-                            // prevent deletion, but we won't worry about it, since
-                            // the worst that will happen is we might have an
-                            // occasional 0-byte .lck or .tmp file left around
-                            try {
-                                lckOut.close();
-                            } catch (IOException ex) {
-                            }
-                            lckFile.delete();
-                            try {
-                                tmpOut.close();
-                            } catch (IOException ex) {
-                            }
-                            tmpFile.delete();
-                        } else {
-                            try {
-                                // Close the file and channel for the *.lck file
-                                if (lckOut != null) {
-                                    lckOut.close();
-                                }
-                                // Close the file/channel and release the lock
-                                // on the *.tmp file
-                                tmpOut.close();
-                                tmpLock.release();
-                            } catch (IOException ex) {
-                                if (DEBUG) {
-                                    ex.printStackTrace();
-                                }
-                            }
-                        }
-                    }
-                } else {
-                    if (DEBUG) {
-                        System.err.println("TempFileCache: Skipping: " + tmpDir.getAbsolutePath());
-                    }
-                }
-            }
-        }
-    }
-
-    /**
-     * Remove the specified file or directory. If "path" is a directory, then
-     * recursively remove all entries, then remove the directory itself.
-     */
-    private static void removeAll(File path) {
-        if (DEBUG) {
-            System.err.println("TempFileCache: removeAll(" + path + ")");
-        }
-
-        if (path.isDirectory()) {
-            // Recursively remove all files/directories in this directory
-            File[] list = path.listFiles();
-            if (list != null) {
-                for (int i = 0; i < list.length; i++) {
-                    removeAll(list[i]);
-                }
-            }
-        }
-
-        path.delete();
-    }
-
-    public LauncherTempFileCache () {
-        if (DEBUG) {
-            System.err.println("TempFileCache: new TempFileCache() --------------------- (static ok: "+(!staticInitError)+")");
-            System.err.println("TempFileCache: Thread: "+Thread.currentThread().getName()+", CL 0x"+Integer.toHexString(LauncherTempFileCache.class.getClassLoader().hashCode())+", this 0x"+Integer.toHexString(hashCode()));
-        }
-        if(!staticInitError) { 
-            try {
-                createTmpDir();
-            } catch (Exception ex) {
-                ex.printStackTrace();
-                initError = true;
-            }
-        }
-        if (DEBUG) {
-            System.err.println("tempDir: "+individualTmpDir+" (ok: "+(!initError)+")");
-            System.err.println("----------------------------------------------------------");
-        }        
-    }
-    
-    /**
-     * @return true is static and object initialization was successful
-     */
-    public boolean isValid() { return !staticInitError && !initError; }
-    
-    /**
-     * Base temp directory used by TempFileCache. 
-     * Lifecycle: For all JVMs, ClassLoader and times.
-     * 
-     * This is set to:
-     *
-     * ${java.io.tmpdir}/<tmpDirPrefix>
-     *
-     * 
-     * @return
-     */
-    public File getBaseDir() { return tmpBaseDir; }
-
-    /**
-     * Root temp directory for this JVM instance. Used to store individual
-     * directories.
-     *
-     * Lifecycle: For all JVMs and ClassLoader
-     *
-     * <tmpBaseDir>/<tmpRootPropValue>
-     *
-     * Use Case: Per ClassLoader files, eg. native libraries. 
-     *
-     * Old temp directories are cleaned up the next time a JVM is launched that
-     * uses TempFileCache.
-     *
-     * 
-     * @return
-     */
-    public File getRootDir() { return tmpRootDir; }
-    
-    /**
-     * Temporary directory for individual files (eg. native libraries of one ClassLoader instance).
-     * The directory name is:
-     *
-     * Lifecycle: Within each JVM .. use case dependent, ie. per ClassLoader
-     *
-     * <tmpRootDir>/jlnMMMMM
-     *
-     * where jlnMMMMM is the unique filename created by File.createTempFile()
-     * without the ".tmp" extension.
-     *
-     * 
-     * @return
-     */
-    public File getTempDir() { return individualTmpDir; }
-    
-    
-    /**
-     * Create the temp directory in tmpRootDir. To do this, we create a temp
-     * file with a ".tmp" extension, and then create a directory of the
-     * same name but without the ".tmp". The temp file, directory, and all
-     * files in the directory will be reaped the next time this is started.
-     * We avoid deleteOnExit, because it doesn't work reliably.
-     */
-    private void createTmpDir() throws IOException {
-        File tmpFile = File.createTempFile("jln", ".tmp", tmpRootDir);
-        String tmpFileName = tmpFile.getAbsolutePath();
-        String tmpDirName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp"));
-        individualTmpDir = new File(tmpDirName);
-        if (!individualTmpDir.mkdir()) {
-            throw new IOException("Cannot create " + individualTmpDir);
-        }
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherActivity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherActivity.java
deleted file mode 100644
index 3120fc7..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherActivity.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * Copyright 2011 JogAmp Community. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- * 
- *    1. Redistributions of source code must retain the above copyright notice, this list of
- *       conditions and the following disclaimer.
- * 
- *    2. Redistributions in binary form must reproduce the above copyright notice, this list
- *       of conditions and the following disclaimer in the documentation and/or other materials
- *       provided with the distribution.
- * 
- * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * The views and conclusions contained in the software and documentation are those of the
- * authors and should not be interpreted as representing official policies, either expressed
- * or implied, of JogAmp Community.
- */
-package com.jogamp.android.launcher;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.TextView;
-import android.util.Log;
-
-public abstract class NEWTLauncherActivity extends Activity {
-   static final String TAG = "NEWTLauncherActivity";
-   TextView tv = null;
-   Method mOnCreate, mOnDestroy, mOnPause, mOnRestart, mOnResume, 
-          mOnStart, mOnStop, mSetIsInvokedByExternalActivity;
-   Class<?> activityClazz = null;
-   Object activityObject  = null;
-   
-   public abstract String getUserActivityName();
-   public abstract String getUserPackageName();
-   
-   @Override
-   public void onCreate(Bundle savedInstanceState) {
-       Log.d(TAG, "onCreate - S");
-       super.onCreate(savedInstanceState);
-       
-       System.setProperty("jogamp.debug.JNILibLoader", "true");
-       System.setProperty("jogamp.debug.NativeLibrary", "true");
-       // System.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
-       // System.setProperty("jogamp.debug.IOUtil", "true");       
-
-       // System.setProperty("nativewindow.debug", "all");
-       System.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
-
-       // System.setProperty("jogl.debug", "all");
-       // System.setProperty("jogl.debug.GLProfile", "true");
-       System.setProperty("jogl.debug.GLDrawable", "true");
-       System.setProperty("jogl.debug.GLContext", "true");
-       System.setProperty("jogl.debug.GLSLCode", "true");
-       System.setProperty("jogl.debug.CapabilitiesChooser", "true");
-       
-       // System.setProperty("jogl.debug.GLSLState", "true");
-       // System.setProperty("jogl.debug.DebugGL", "true");
-       // System.setProperty("jogl.debug.TraceGL", "true");
-
-       // System.setProperty("newt.debug", "all");
-       System.setProperty("newt.debug.Window", "true");
-       // System.setProperty("newt.debug.Window.MouseEvent", "true");
-       // System.setProperty("newt.debug.Window.KeyEvent", "true");
-
-       ClassLoader cl = ClassLoaderUtil.createJogampClassLoaderSingleton(this, getUserPackageName());
-       if(null != cl) {
-           try {
-               activityClazz = Class.forName(getUserActivityName(), true, cl);
-               Log.d(TAG, "Activity Clazz "+activityClazz);
-               activityObject = createInstance(activityClazz, null);
-               Log.d(TAG, "Activity Object "+activityObject);
-               mOnCreate = activityClazz.getMethod("onCreate", Bundle.class);
-               mOnDestroy = activityClazz.getMethod("onDestroy");
-               mOnPause = activityClazz.getMethod("onPause");
-               mOnRestart = activityClazz.getMethod("onRestart");
-               mOnResume = activityClazz.getMethod("onResume");
-               mOnStart = activityClazz.getMethod("onStart");
-               mOnStop = activityClazz.getMethod("onStop");
-               mSetIsInvokedByExternalActivity = activityClazz.getMethod("setIsInvokedByExternalActivity", Activity.class);
-           } catch (Exception e) {
-               Log.d(TAG, "error: "+e, e);
-               throw new RuntimeException(e);
-           }
-       }
-
-       if( null == mOnCreate || null == mOnDestroy || null == mOnPause ||
-           null == mOnRestart || null == mOnResume ||
-           null == mSetIsInvokedByExternalActivity ) {
-           RuntimeException e = new RuntimeException("XXX - incomplete method set");
-           Log.d(TAG, "error: "+e, e);
-           throw e;
-       }
-       
-       callMethod(activityObject, mSetIsInvokedByExternalActivity, this);
-       
-       callMethod(activityObject, mOnCreate, savedInstanceState);
-       Log.d(TAG, "onCreate - X");
-   }
-   
-   @Override
-   public void onStart() {
-     Log.d(TAG, "onStart - S");
-     callMethod(activityObject, mOnStart);
-     super.onStart();
-     Log.d(TAG, "onStart - X");
-   }
-     
-   @Override
-   public void onRestart() {
-     Log.d(TAG, "onRestart - S");
-     callMethod(activityObject, mOnRestart);
-     super.onRestart();
-     Log.d(TAG, "onRestart - X");
-   }
-
-   @Override
-   public void onResume() {
-     Log.d(TAG, "onResume - S");
-     callMethod(activityObject, mOnResume);
-     super.onResume();
-     Log.d(TAG, "onResume - X");
-   }
-
-   @Override
-   public void onPause() {
-     Log.d(TAG, "onPause - S");
-     callMethod(activityObject, mOnPause);
-     super.onPause();
-     Log.d(TAG, "onPause - X");
-   }
-
-   @Override
-   public void onStop() {
-     Log.d(TAG, "onStop - S");
-     callMethod(activityObject, mOnStop);
-     super.onStop();  
-     Log.d(TAG, "onStop - X");
-   }
-
-   @Override
-   public void onDestroy() {
-     Log.d(TAG, "onDestroy - S");
-     callMethod(activityObject, mOnDestroy);
-     super.onDestroy();  
-     finish();
-     Log.d(TAG, "onDestroy - X");
-   }   
-
-   @Override
-   public void finish() {
-     Log.d(TAG, "finish - S");
-     super.finish();  
-     Log.d(TAG, "finish - X");
-   }   
-
-  /**
-   * @throws JogampRuntimeException if the instance can not be created.
-   */
-  public static final Object createInstance(Class<?> clazz, Class<?>[] cstrArgTypes, Object ... cstrArgs) 
-      throws RuntimeException
-  {
-    return createInstance(getConstructor(clazz, cstrArgTypes), cstrArgs);
-  }
-
-  public static final Object createInstance(Constructor<?> cstr, Object ... cstrArgs) 
-      throws RuntimeException
-  {
-    try {
-        return cstr.newInstance(cstrArgs);
-    } catch (Exception e) {
-      Throwable t = e;
-      if (t instanceof InvocationTargetException) {
-        t = ((InvocationTargetException) t).getTargetException();
-      }
-      if (t instanceof Error) {
-        throw (Error) t;
-      }
-      if (t instanceof RuntimeException) {
-        throw (RuntimeException) t;
-      }
-      throw new RuntimeException("can not create instance of "+cstr.getName(), t);
-    }
-  }
-  
-    /**
-     * @throws JogampRuntimeException if the constructor can not be delivered.
-     */
-    protected static final Constructor<?> getConstructor(Class<?> clazz, Class<?> ... cstrArgTypes) 
-        throws RuntimeException {
-        try {
-            if(null == cstrArgTypes) {
-                cstrArgTypes = zeroTypes;
-            }
-            return clazz.getDeclaredConstructor(cstrArgTypes);
-        } catch (NoSuchMethodException ex) {
-            throw new RuntimeException("Constructor: '" + clazz + "(" + asString(cstrArgTypes) + ")' not found", ex);
-        }
-    }
-    
-    protected static final Class<?>[] zeroTypes = new Class[0];
-
-    protected static final String asString(Class<?>[] argTypes) {
-        StringBuffer args = new StringBuffer();
-        boolean coma = false;
-        if(null != argTypes) {
-            for (int i = 0; i < argTypes.length; i++) {
-                if(coma) {
-                     args.append(", ");
-                }
-                args.append(argTypes[i].getName());
-                coma = true;
-            }
-        }
-        return args.toString();
-    }
-    
-  protected static final Object callMethod(Object instance, Method method, Object ... args)
-      throws RuntimeException
-  {
-    try {
-        return method.invoke(instance, args);
-    } catch (Exception e) {
-      Throwable t = e;
-      if (t instanceof InvocationTargetException) {
-        t = ((InvocationTargetException) t).getTargetException();
-      }
-      if (t instanceof Error) {
-        throw (Error) t;
-      }
-      if (t instanceof RuntimeException) {
-        throw (RuntimeException) t;
-      }
-      throw new RuntimeException("calling "+method+" failed", t);
-    }
-  }
-
-
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherElektronActivity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherElektronActivity.java
deleted file mode 100644
index 85a751e..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherElektronActivity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherElektronActivity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTElektronActivity";
-    static String pkg = "com.jogamp.opengl.test";
-    
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES1Activity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES1Activity.java
deleted file mode 100644
index 05b4754..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES1Activity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherGearsES1Activity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES1Activity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2Activity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2Activity.java
deleted file mode 100644
index 78f2b74..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2Activity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherGearsES2Activity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2Activity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2TransActivity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2TransActivity.java
deleted file mode 100644
index c55620f..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherGearsES2TransActivity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherGearsES2TransActivity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2TransActivity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI1pActivity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI1pActivity.java
deleted file mode 100644
index 1af0de1..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI1pActivity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherGraphUI1pActivity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTGraphUI1pActivity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI2pActivity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI2pActivity.java
deleted file mode 100644
index 0a5f8d2..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherGraphUI2pActivity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherGraphUI2pActivity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTGraphUI2pActivity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES1Activity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES1Activity.java
deleted file mode 100644
index af52705..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES1Activity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherRedSquareES1Activity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTRedSquareES1Activity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES2Activity.java b/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES2Activity.java
deleted file mode 100644
index 03e2ad7..0000000
--- a/src/android/com/jogamp/android/launcher/NEWTLauncherRedSquareES2Activity.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.jogamp.android.launcher;
-
-public class NEWTLauncherRedSquareES2Activity extends NEWTLauncherActivity {
-    static String demo = "com.jogamp.opengl.test.android.NEWTRedSquareES2Activity";
-    static String pkg = "com.jogamp.opengl.test";
-
-    @Override
-    public String getUserActivityName() {
-        return demo;
-    }
-    @Override
-    public String getUserPackageName() {
-        return pkg;
-    }
-}
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java
index f3d0d37..1d9cf36 100644
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildComposablePipeline.java
@@ -564,7 +564,7 @@ public class BuildComposablePipeline {
          */
         protected void postMethodEmissionHook(PrintWriter output) {
             output.println("  public String toString() {");
-            output.println("    StringBuffer sb = new StringBuffer();");
+            output.println("    StringBuilder sb = new StringBuilder();");
             output.println("    sb.append(\"" + getOutputName() + " [ implementing " + baseInterfaceClass.getName() + ",\\n\\t\");");
             if (null != prologClassOpt) {
                 output.println("    sb.append(\" prolog: \"+" + getPrologObjectNameOpt() + ".toString()+\",\\n\\t\");");
@@ -859,7 +859,7 @@ public class BuildComposablePipeline {
                     + ".glGetError();");
             output.println("    if (err == GL_NO_ERROR) { return; }");
             output.println();
-            output.println("    StringBuffer buf = new StringBuffer(Thread.currentThread()+");
+            output.println("    StringBuilder buf = new StringBuilder(Thread.currentThread()+");
             output.println("      \" glGetError() returned the following error codes after a call to \" + caller + \": \");");
             output.println();
             output.println("    // Loop repeatedly to allow for distributed GL implementations,");
@@ -1010,7 +1010,7 @@ public class BuildComposablePipeline {
             output.println("protected String dumpArray(Object obj)");
             output.println("{");
             output.println("  if (obj == null) return \"[null]\";");
-            output.println("  StringBuffer sb = new StringBuffer(\"[\");");
+            output.println("  StringBuilder sb = new StringBuilder(\"[\");");
             output.println("  int len  = java.lang.reflect.Array.getLength(obj);");
             output.println("  int count = Math.min(len,16);");
             output.println("  for ( int i =0; i < count; i++ ) {");
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java
index 3131267..87a734e 100644
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/BuildStaticGLInfo.java
@@ -117,13 +117,13 @@ public class BuildStaticGLInfo {
   protected static Pattern definePattern =
     Pattern.compile("\\#define ([CEW]?GL[XU]?_[A-Za-z0-9_]+)\\s*([A-Za-z0-9_]+)(.*)");
 
-  // Maps function / #define names to the names of the extensions they're declared in
-  protected Map<String, String> declarationToExtensionMap = new HashMap<String, String>();
+  // Maps function / #define names to Set of names of the extensions they're declared in
+  protected Map<String, Set<String>> declarationToExtensionMap = new HashMap<String, Set<String>>();
 
   // Maps extension names to Set of identifiers (both #defines and
   // function names) this extension declares
   protected Map<String, Set<String>> extensionToDeclarationMap = new HashMap<String, Set<String>>();
-  protected boolean debug = false;
+  protected boolean DEBUG = false;
 
     /**
      * The first argument is the package to which the StaticGLInfo class
@@ -177,7 +177,7 @@ public class BuildStaticGLInfo {
     }
 
     public void setDebug(boolean v) {
-        debug = v;
+        DEBUG = v;
     }
 
     /** Parses the supplied C header files and adds the function
@@ -206,7 +206,7 @@ public class BuildStaticGLInfo {
                     identifier = m.group(defineIdentifierGroup).trim();
                     type = 1;
                 } else if (line.startsWith("#endif")) {
-                    if (debug) {
+                    if (DEBUG) {
                         System.err.println("END ASSOCIATION BLOCK: <" + activeAssociation + ">");
                     }
                     activeAssociation = null;
@@ -216,7 +216,7 @@ public class BuildStaticGLInfo {
                         && // Handles #ifndef GL_... #define GL_...
                         !identifier.equals(activeAssociation)) {
                     addAssociation(identifier, activeAssociation);
-                    if (debug) {
+                    if (DEBUG) {
                         System.err.println("  ADDING ASSOCIATION: <" + identifier + "> <" + activeAssociation + "> ; type " + type);
                     }
                 }
@@ -224,7 +224,7 @@ public class BuildStaticGLInfo {
                 // found a new #ifndef GL_XXX block
                 activeAssociation = m.group(1).trim();
 
-                if (debug) {
+                if (DEBUG) {
                     System.err.println("BEGIN ASSOCIATION BLOCK: <" + activeAssociation + ">");
                 }
             }
@@ -245,7 +245,7 @@ public class BuildStaticGLInfo {
         }
     }
 
-    public String getExtension(String identifier) {
+    public Set<String> getExtension(String identifier) {
         return declarationToExtensionMap.get(identifier);
     }
 
@@ -350,7 +350,13 @@ public class BuildStaticGLInfo {
     // Internals only below this point
     //
     protected void addAssociation(String identifier, String association) {
-        declarationToExtensionMap.put(identifier, association);
+        Set<String> extensions = declarationToExtensionMap.get(identifier);
+        if(null == extensions) {
+            extensions = new HashSet<String>();
+            declarationToExtensionMap.put(identifier, extensions);
+        }
+        extensions.add(association);
+        
         Set<String> identifiers = extensionToDeclarationMap.get(association);
         if (identifiers == null) {
             identifiers = new HashSet<String>();
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java
index d03e1bd..c1a4fac 100755
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLConfiguration.java
@@ -40,6 +40,7 @@
 package com.jogamp.gluegen.opengl;
 
 import com.jogamp.gluegen.GlueEmitterControls;
+import com.jogamp.gluegen.GlueGen;
 import com.jogamp.gluegen.MethodBinding;
 import com.jogamp.gluegen.procaddress.ProcAddressConfiguration;
 import com.jogamp.gluegen.runtime.opengl.GLExtensionNames;
@@ -206,10 +207,22 @@ public class GLConfiguration extends ProcAddressConfiguration {
 
     protected boolean shouldIgnoreExtension(String symbol, boolean criteria) {
         if (criteria && glInfo != null) {
-            String extension = glInfo.getExtension(symbol);
-            if (extension != null
-                    && ignoredExtensions.contains(extension)) {
-                return true;
+            Set<String> extensionNames = glInfo.getExtension(symbol);
+            if(null!=extensionNames) {
+                for(Iterator<String> i=extensionNames.iterator(); i.hasNext(); ) {
+                    String extensionName = i.next();
+                    if (extensionName != null && ignoredExtensions.contains(extensionName)) {
+                        if (DEBUG_IGNORES) {
+                            System.err.print("Ignore symbol <" + symbol + "> of extension <" + extensionName + ">");
+                            if(extensionNames.size()==1) {
+                                System.err.println(", single .");
+                            } else {
+                                System.err.println(", WARNING MULTIPLE OCCURENCE: "+extensionNames);
+                            }
+                        }
+                        return true;
+                    }
+                }
             }
             boolean isGLEnum = GLExtensionNames.isGLEnumeration(symbol);
             boolean isGLFunc = GLExtensionNames.isGLFunction(symbol);
@@ -279,6 +292,7 @@ public class GLConfiguration extends ProcAddressConfiguration {
     public void parseGLHeaders(GlueEmitterControls controls) throws IOException {
         if (!glHeaders.isEmpty()) {
             glInfo = new BuildStaticGLInfo();
+            glInfo.setDebug(GlueGen.debug());
             for (String file : glHeaders) {
                 String fullPath = controls.findHeaderFile(file);
                 if (fullPath == null) {
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java
index a096934..f4658ad 100644
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLEmitter.java
@@ -103,6 +103,9 @@ public class GLEmitter extends ProcAddressEmitter {
             return;
         }
         for (String extension : extensionsRenamedIntoCore) {
+            if(JavaConfiguration.DEBUG_RENAMES) {
+                System.err.println("<RenameExtensionIntoCore: "+extension+" BEGIN");
+            }
             Set<String> declarations = glInfo.getDeclarations(extension);
             if (declarations != null) {
                 for (Iterator<String> iterator = declarations.iterator(); iterator.hasNext();) {
@@ -120,6 +123,9 @@ public class GLEmitter extends ProcAddressEmitter {
                     }
                 }
             }
+            if(JavaConfiguration.DEBUG_RENAMES) {
+                System.err.println("RenameExtensionIntoCore: "+extension+" END>");
+            }            
         }
     }
 
@@ -321,8 +327,8 @@ public class GLEmitter extends ProcAddressEmitter {
         }
         String symbolRenamed = def.getName();
         StringBuilder newComment = new StringBuilder();
-        newComment.append("Part of <code>");
-        if (0 == addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, def.getAliasedNames())) {
+        newComment.append("Part of ");
+        if (0 == addExtensionsOfSymbols2Buffer(newComment, ", ", "; ", symbolRenamed, def.getAliasedNames())) {
             if (def.isEnum()) {
                 String enumName = def.getEnumName();
                 if (null != enumName) {
@@ -348,7 +354,6 @@ public class GLEmitter extends ProcAddressEmitter {
                 }
             }
         }
-        newComment.append("</code>");
 
         if (null != optionalComment) {
             newComment.append("<br>");
@@ -358,7 +363,48 @@ public class GLEmitter extends ProcAddressEmitter {
         super.emitDefine(def, newComment.toString());
     }
 
-    public int addExtensionsOfSymbols2Buffer(StringBuilder buf, String sep, String first, Collection<String> col) {
+    private int addExtensionListOfSymbol2Buffer(BuildStaticGLInfo glInfo, StringBuilder buf, String sep1, String name) {
+        int num = 0;
+        Set<String> extensionNames = glInfo.getExtension(name);
+        if(null!=extensionNames) {
+            for(Iterator<String> i=extensionNames.iterator(); i.hasNext(); ) {
+                String extensionName = i.next();
+                if (null != extensionName) {
+                    buf.append("<code>");
+                    buf.append(extensionName);
+                    buf.append("</code>");
+                    if (i.hasNext()) {
+                        buf.append(sep1); // same-name seperator
+                    }
+                    num++;
+                }
+            }
+        }
+        return num;
+    }
+    private int addExtensionListOfAliasedSymbols2Buffer(BuildStaticGLInfo glInfo, StringBuilder buf, String sep1, String sep2, String name, Collection<String> exclude) {
+        int num = 0;
+        if(null != name) { 
+            num += addExtensionListOfSymbol2Buffer(glInfo, buf, sep1, name); // extensions of given name
+            boolean needsSep2 = 0<num;
+            Set<String> origNames = cfg.getRenamedJavaSymbols(name);
+            if(null != origNames) {
+                for(String origName : origNames) {
+                    if(!exclude.contains(origName)) {
+                        if (needsSep2) {
+                            buf.append(sep2); // diff-name seperator
+                        }            
+                        int num2 = addExtensionListOfSymbol2Buffer(glInfo, buf, sep1, origName); // extensions of orig-name
+                        needsSep2 = num<num2;
+                        num += num2;
+                    }
+                }
+            }
+        }
+        return num;
+    }
+    
+    public int addExtensionsOfSymbols2Buffer(StringBuilder buf, String sep1, String sep2, String first, Collection<String> col) {
         BuildStaticGLInfo glInfo = getGLConfig().getGLInfo();
         if (null == glInfo) {
             throw new RuntimeException("No GLInfo for: " + first);
@@ -367,28 +413,16 @@ public class GLEmitter extends ProcAddressEmitter {
         if (null == buf) {
             buf = new StringBuilder();
         }
-        String extensionName;
-
-        Iterator<String> iter = col.iterator();
-        if (null != first) {
-            extensionName = glInfo.getExtension(first);
-            if (null != extensionName) {
-                buf.append(extensionName);
-                if (iter.hasNext()) {
-                    buf.append(sep);
-                }
-                num++;
-            }
-        }
-        while (iter.hasNext()) {
-            extensionName = glInfo.getExtension(iter.next());
-            if (null != extensionName) {
-                buf.append(extensionName);
-                if (iter.hasNext()) {
-                    buf.append(sep);
-                }
-                num++;
+
+        num += addExtensionListOfAliasedSymbols2Buffer(glInfo, buf, sep1, sep2, first, col);
+        boolean needsSep2 = 0<num;
+        for(Iterator<String> iter = col.iterator(); iter.hasNext(); ) {
+            if(needsSep2) {
+                buf.append(sep2); // diff-name seperator
             }
+            int num2 = addExtensionListOfAliasedSymbols2Buffer(glInfo, buf, sep1, sep2, iter.next(), col);
+            needsSep2 = num<num2;
+            num += num2;
         }
         return num;
     }
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java
index 87d8708..0166743 100755
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/GLJavaMethodBindingEmitter.java
@@ -108,8 +108,8 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit
             String symbolRenamed = binding.getName();
             StringBuilder newComment = new StringBuilder();
 
-            newComment.append("<br>Part of <code>");
-            if (0 == glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", symbolRenamed, binding.getAliasedNames())) {
+            newComment.append("<br>Part of ");
+            if (0 == glEmitter.addExtensionsOfSymbols2Buffer(newComment, ", ", "; ", symbolRenamed, binding.getAliasedNames())) {
                 if (glEmitter.getGLConfig().getAllowNonGLExtensions()) {
                     newComment.append("CORE FUNC");
                 } else {
@@ -121,7 +121,6 @@ public class GLJavaMethodBindingEmitter extends ProcAddressJavaMethodBindingEmit
                     throw ex;
                 }
             }
-            newComment.append("</code>");
             writer.print(newComment.toString());
         }
     }
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java
index bfaf7ac..adb1c2a 100755
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureEmitter.java
@@ -55,6 +55,8 @@ import java.util.Set;
 
 /**
  * Emitter producing NativeSignature attributes.
+ * 
+ * Review: This Package/Class is not used and subject to be deleted. 
  */
 public class NativeSignatureEmitter extends GLEmitter {
 
diff --git a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java
index b4cab28..e98478b 100755
--- a/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java
+++ b/src/jogl/classes/com/jogamp/gluegen/opengl/nativesig/NativeSignatureJavaMethodBindingEmitter.java
@@ -50,6 +50,7 @@ import com.jogamp.gluegen.procaddress.ProcAddressJavaMethodBindingEmitter;
 
 import java.io.PrintWriter;
 
+/** Review: This Package/Class is not used and subject to be deleted. */
 public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBindingEmitter {
 
   public NativeSignatureJavaMethodBindingEmitter(GLJavaMethodBindingEmitter methodToWrap) {
@@ -106,7 +107,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding
     } else if (type.isPrimitiveArray()) {
       writer.print("MO");
     } else if (type.isPrimitive()) {
-      Class clazz = type.getJavaClass();
+      Class<?> clazz = type.getJavaClass();
       if      (clazz == Byte.TYPE)      { writer.print("B"); }
       else if (clazz == Character.TYPE) { writer.print("C"); }
       else if (clazz == Double.TYPE)    { writer.print("D"); }
@@ -145,7 +146,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding
     super.emitPreCallSetup(binding, writer);
     for (int i = 0; i < binding.getNumArguments(); i++) {
       JavaType type = binding.getJavaArgumentType(i);
-      if (type.isNIOBuffer() && !directNIOOnly) {
+      if (type.isNIOBuffer() && !useNIODirectOnly ) {
         // Emit declarations for variables holding primitive arrays as type Object
         // We don't know 100% sure we're going to use these at this point in the code, though
         writer.println("  Object " + getNIOBufferArrayName(i) + " = (_direct ? null : Buffers.getArray(" +
@@ -245,29 +246,31 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding
     writer.print("    ");
     JavaType returnType = binding.getJavaReturnType();
     boolean needsResultAssignment = false;
-
+    
     if (!returnType.isVoid()) {
       if (returnType.isCompoundTypeWrapper() ||
           returnType.isNIOByteBuffer()) {
-        writer.println("java.nio.ByteBuffer _res;");
+        writer.println("final java.nio.ByteBuffer _res;");
         needsResultAssignment = true;
       } else if (returnType.isArrayOfCompoundTypeWrappers()) {
-        writer.println("java.nio.ByteBuffer[] _res;");
+        writer.println("final java.nio.ByteBuffer[] _res;");
         needsResultAssignment = true;
       } else if (returnType.isString() || returnType.isNIOByteBuffer()) {
+        writer.print("final ");
         writer.print(returnType);
         writer.println(" _res;");
         needsResultAssignment = true;
       } else {
         // Always assign to "_res" variable so we can clean up
         // outgoing String arguments, for example
+        writer.print("final ");
         emitReturnType(writer);
         writer.println(" _res;");
         needsResultAssignment = true;
       }
     }
 
-    if (binding.signatureCanUseIndirectNIO() && !directNIOOnly) {
+    if (binding.signatureCanUseIndirectNIO() && !useNIODirectOnly) {
       // Must generate two calls for this gated on whether the NIO
       // buffers coming in are all direct or indirect
       writer.println("if (_direct) {");
@@ -310,7 +313,7 @@ public class NativeSignatureJavaMethodBindingEmitter extends GLJavaMethodBinding
       writer.print(";");
     }
 
-    if (binding.signatureCanUseIndirectNIO() && !directNIOOnly) {
+    if (binding.signatureCanUseIndirectNIO() && !useNIODirectOnly) {
       // Must generate two calls for this gated on whether the NIO
       // buffers coming in are all direct or indirect
       writer.println();
diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java
index 749c7ef..6371388 100755
--- a/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java
+++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/GLRegion.java
@@ -114,14 +114,16 @@ public abstract class GLRegion extends Region {
      * current width/hight of window for multi pass rendering
      * of the region.
      * @param matrix current {@link PMVMatrix}.
+     * @param rs the RenderState to be used
      * @param vp_width current screen width
      * @param vp_height current screen height
-     * @param width texture width for mp rendering
+     * @param texWidth desired texture width for multipass-rendering. 
+     *        The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched.
      */
-    public final void draw(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int width) {
+    public final void draw(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) {
         update(gl, rs);
-        drawImpl(gl, rs, vp_width, vp_height, width);
+        drawImpl(gl, rs, vp_width, vp_height, texWidth);
     }
     
-    protected abstract void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int width);
+    protected abstract void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth);
 }
diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java
index 86d962f..2f078d7 100644
--- a/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java
+++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/RegionRenderer.java
@@ -54,10 +54,11 @@ public abstract class RegionRenderer extends Renderer {
      *  the triangles of the shapes will be generated, if not yet generated
      * @param region the OutlineShape to Render.
      * @param position the initial translation of the outlineShape. 
-     * @param texSize texture size for multipass render
+     * @param texWidth desired texture width for multipass-rendering. 
+     *        The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched.
      * @throws Exception if HwRegionRenderer not initialized
      */
-    public final void draw(GL2ES2 gl, Region region, float[] position, int texSize) {
+    public final void draw(GL2ES2 gl, Region region, float[] position, int[/*1*/] texWidth) {
         if(!isInitialized()) {
             throw new GLException("RegionRenderer: not initialized!");
         }
@@ -65,14 +66,14 @@ public abstract class RegionRenderer extends Renderer {
             throw new GLException("Incompatible render modes, : region modes "+region.getRenderModes()+
                                   " doesn't contain renderer modes "+this.getRenderModes());
         }        
-        drawImpl(gl, region, position, texSize);
+        drawImpl(gl, region, position, texWidth);
     }
     
     /**
      * Usually just dispatched the draw call to the Region's draw implementation,
-     * e.g. {@link com.jogamp.graph.curve.opengl.GLRegion#draw(GL2ES2, RenderState, int, int, int) GLRegion#draw(GL2ES2, RenderState, int, int, int)}.
+     * e.g. {@link com.jogamp.graph.curve.opengl.GLRegion#draw(GL2ES2, RenderState, int, int, int[]) GLRegion#draw(GL2ES2, RenderState, int, int, int[])}.
      */
-    protected abstract void drawImpl(GL2ES2 gl, Region region, float[] position, int texSize);
+    protected abstract void drawImpl(GL2ES2 gl, Region region, float[] position, int[] texWidth);
 
     @Override
     protected void destroyImpl(GL2ES2 gl) {
diff --git a/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java b/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java
index b466670..8dc41b0 100644
--- a/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java
+++ b/src/jogl/classes/com/jogamp/graph/curve/opengl/TextRenderer.java
@@ -59,11 +59,12 @@ public abstract class TextRenderer extends Renderer {
      * @param str text to be rendered 
      * @param position the lower left corner of the string 
      * @param fontSize font size
-     * @param texSize texture size for multipass render
+     * @param texWidth desired texture width for multipass-rendering. 
+     *        The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched.
      * @throws Exception if TextRenderer not initialized
      */
     public abstract void drawString3D(GL2ES2 gl, Font font,
-                                      String str, float[] position, int fontSize, int texSize);
+                                      String str, float[] position, int fontSize, int[/*1*/] texSize);
 
     /**Create the resulting {@link GlyphString} that represents
      * the String wrt to the font.
diff --git a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java
index dff8903..33d4873 100644
--- a/src/jogl/classes/com/jogamp/graph/font/FontFactory.java
+++ b/src/jogl/classes/com/jogamp/graph/font/FontFactory.java
@@ -29,15 +29,15 @@ package com.jogamp.graph.font;
 
 import java.io.File;
 import java.io.IOException;
-import java.net.URL;
-import java.security.AccessController;
+import java.net.URLConnection;
 
+import com.jogamp.common.util.PropertyAccess;
 import com.jogamp.common.util.ReflectionUtil;
+import com.jogamp.common.util.SecurityUtil;
 
 import jogamp.graph.font.FontConstructor;
 import jogamp.graph.font.JavaFontLoader;
 import jogamp.graph.font.UbuntuFontLoader;
-import jogamp.opengl.Debug;
 
 public class FontFactory {
     /** Ubuntu is the default font family */
@@ -53,8 +53,8 @@ public class FontFactory {
          * For example:
          *   "jogamp.graph.font.typecast.TypecastFontFactory" (default)
          *   "jogamp.graph.font.ttf.TTFFontImpl"
-         */
-        String fontImplName = Debug.getProperty("FontImpl", true, AccessController.getContext());
+         */        
+        String fontImplName = PropertyAccess.getProperty("FontImpl", true, SecurityUtil.getCommonAccessControlContext(FontFactory.class));
         if(null == fontImplName) {
             fontImplName = "jogamp.graph.font.typecast.TypecastFontConstructor";
         }
@@ -78,8 +78,8 @@ public class FontFactory {
         return fontConstr.create(file);
     }
 
-    public static final Font get(final URL url) throws IOException {
-        return fontConstr.create(url);
+    public static final Font get(final URLConnection conn) throws IOException {
+        return fontConstr.create(conn);
     }    
     
     public static boolean isPrintableChar( char c ) {
diff --git a/src/jogl/classes/com/jogamp/graph/font/FontSet.java b/src/jogl/classes/com/jogamp/graph/font/FontSet.java
index 0cee811..d376922 100644
--- a/src/jogl/classes/com/jogamp/graph/font/FontSet.java
+++ b/src/jogl/classes/com/jogamp/graph/font/FontSet.java
@@ -27,6 +27,8 @@
  */
 package com.jogamp.graph.font;
 
+import java.io.IOException;
+
 
 public interface FontSet {
 
@@ -54,7 +56,7 @@ public interface FontSet {
     /** ITALIC style bit flag */
     public static final int STYLE_ITALIC      = 1 << 3;
 
-    Font getDefault();
+    Font getDefault() throws IOException ;
     
-    Font get(int family, int stylebits);
+    Font get(int family, int stylebits) throws IOException ;
 }
diff --git a/src/jogl/classes/com/jogamp/opengl/FloatUtil.java b/src/jogl/classes/com/jogamp/opengl/FloatUtil.java
new file mode 100644
index 0000000..54fac46
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/FloatUtil.java
@@ -0,0 +1,289 @@
+/**
+ * Copyright 2010 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ *
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ *
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl;
+
+import java.nio.FloatBuffer;
+
+/**
+ * Basic Float math utility functions.
+ * <p>
+ * Derived from ProjectFloat.java - Created 11-jan-2004
+ * </p>
+ * 
+ * @author Erik Duijs
+ * @author Kenneth Russell
+ * @author Sven Gothel
+ */
+public class FloatUtil {
+  private static final float[] IDENTITY_MATRIX =
+    new float[] {
+      1.0f, 0.0f, 0.0f, 0.0f,
+      0.0f, 1.0f, 0.0f, 0.0f,
+      0.0f, 0.0f, 1.0f, 0.0f,
+      0.0f, 0.0f, 0.0f, 1.0f };
+
+  private static final float[] ZERO_MATRIX =
+    new float[] {
+      0.0f, 0.0f, 0.0f, 0.0f,
+      0.0f, 0.0f, 0.0f, 0.0f,
+      0.0f, 0.0f, 0.0f, 0.0f,
+      0.0f, 0.0f, 0.0f, 0.0f };
+
+  /**
+   * Make matrix an identity matrix
+   */
+  public static final void makeIdentityf(float[] m, int offset) {
+    for (int i = 0; i < 16; i++) {
+      m[i+offset] = IDENTITY_MATRIX[i];
+    }
+  }
+
+  /**
+   * Make matrix an identity matrix
+   */
+  public static final void makeIdentityf(FloatBuffer m) {
+    int oldPos = m.position();
+    m.put(IDENTITY_MATRIX);
+    m.position(oldPos);
+  }
+
+  /**
+   * Make matrix an zero matrix
+   */
+  public static final void makeZero(float[] m, int offset) {
+    for (int i = 0; i < 16; i++) {
+      m[i+offset] = 0;
+    }
+  }
+
+  /**
+   * Make matrix an zero matrix
+   */
+  public static final void makeZero(FloatBuffer m) {
+    int oldPos = m.position();
+    m.put(ZERO_MATRIX);
+    m.position(oldPos);
+  }
+  
+  /**
+   * @param a
+   * @param b
+   * @param d result a*b
+   */
+  public static final void multMatrixf(final float[] a, int a_off, final float[] b, int b_off, float[] d, int d_off) {
+     for (int i = 0; i < 4; i++) {
+        final float ai0=a[a_off+i+0*4],  ai1=a[a_off+i+1*4],  ai2=a[a_off+i+2*4],  ai3=a[a_off+i+3*4];
+        d[d_off+i+0*4] = ai0 * b[b_off+0+0*4] + ai1 * b[b_off+1+0*4] + ai2 * b[b_off+2+0*4] + ai3 * b[b_off+3+0*4] ;
+        d[d_off+i+1*4] = ai0 * b[b_off+0+1*4] + ai1 * b[b_off+1+1*4] + ai2 * b[b_off+2+1*4] + ai3 * b[b_off+3+1*4] ;
+        d[d_off+i+2*4] = ai0 * b[b_off+0+2*4] + ai1 * b[b_off+1+2*4] + ai2 * b[b_off+2+2*4] + ai3 * b[b_off+3+2*4] ;
+        d[d_off+i+3*4] = ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] ;
+     }
+  }
+
+  /**
+   * @param a
+   * @param b
+   * @param d result a*b
+   */
+  public static final void multMatrixf(final float[] a, int a_off, final float[] b, int b_off, FloatBuffer d) {
+     final int dP = d.position();
+     for (int i = 0; i < 4; i++) {
+        final float ai0=a[a_off+i+0*4],  ai1=a[a_off+i+1*4],  ai2=a[a_off+i+2*4],  ai3=a[a_off+i+3*4];
+        d.put(dP+i+0*4 , ai0 * b[b_off+0+0*4] + ai1 * b[b_off+1+0*4] + ai2 * b[b_off+2+0*4] + ai3 * b[b_off+3+0*4] );
+        d.put(dP+i+1*4 , ai0 * b[b_off+0+1*4] + ai1 * b[b_off+1+1*4] + ai2 * b[b_off+2+1*4] + ai3 * b[b_off+3+1*4] );
+        d.put(dP+i+2*4 , ai0 * b[b_off+0+2*4] + ai1 * b[b_off+1+2*4] + ai2 * b[b_off+2+2*4] + ai3 * b[b_off+3+2*4] );
+        d.put(dP+i+3*4 , ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] );
+     }
+  }
+
+  /**
+   * @param a
+   * @param b
+   * @param d result a*b
+   */
+  public static final void multMatrixf(final FloatBuffer a, final float[] b, int b_off, FloatBuffer d) {
+     final int aP = a.position(); 
+     final int dP = d.position();
+     for (int i = 0; i < 4; i++) {
+        final float ai0=a.get(aP+i+0*4),  ai1=a.get(aP+i+1*4),  ai2=a.get(aP+i+2*4),  ai3=a.get(aP+i+3*4);
+        d.put(dP+i+0*4 , ai0 * b[b_off+0+0*4] + ai1 * b[b_off+1+0*4] + ai2 * b[b_off+2+0*4] + ai3 * b[b_off+3+0*4] );
+        d.put(dP+i+1*4 , ai0 * b[b_off+0+1*4] + ai1 * b[b_off+1+1*4] + ai2 * b[b_off+2+1*4] + ai3 * b[b_off+3+1*4] );
+        d.put(dP+i+2*4 , ai0 * b[b_off+0+2*4] + ai1 * b[b_off+1+2*4] + ai2 * b[b_off+2+2*4] + ai3 * b[b_off+3+2*4] );
+        d.put(dP+i+3*4 , ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] );
+     }
+  }
+
+  /**
+   * @param a
+   * @param b
+   * @param d result a*b
+   */
+  public static final void multMatrixf(final FloatBuffer a, final FloatBuffer b, FloatBuffer d) {
+     final int aP = a.position(); 
+     final int bP = b.position();
+     final int dP = d.position();
+     for (int i = 0; i < 4; i++) {
+        final float ai0=a.get(aP+i+0*4),  ai1=a.get(aP+i+1*4),  ai2=a.get(aP+i+2*4),  ai3=a.get(aP+i+3*4);
+        d.put(dP+i+0*4 , ai0 * b.get(bP+0+0*4) + ai1 * b.get(bP+1+0*4) + ai2 * b.get(bP+2+0*4) + ai3 * b.get(bP+3+0*4) );
+        d.put(dP+i+1*4 , ai0 * b.get(bP+0+1*4) + ai1 * b.get(bP+1+1*4) + ai2 * b.get(bP+2+1*4) + ai3 * b.get(bP+3+1*4) );
+        d.put(dP+i+2*4 , ai0 * b.get(bP+0+2*4) + ai1 * b.get(bP+1+2*4) + ai2 * b.get(bP+2+2*4) + ai3 * b.get(bP+3+2*4) );
+        d.put(dP+i+3*4 , ai0 * b.get(bP+0+3*4) + ai1 * b.get(bP+1+3*4) + ai2 * b.get(bP+2+3*4) + ai3 * b.get(bP+3+3*4) );
+     }
+  }
+  
+  
+  /**
+   * Normalize vector
+   *
+   * @param v makes len(v)==1
+   */
+  public static final void normalize(float[] v) {
+    float r = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
+    
+    if ( r == 0.0 || r == 1.0) {
+      return;
+    }
+
+    r = 1.0f / r;
+
+    v[0] *= r;
+    v[1] *= r;
+    v[2] *= r;
+  }
+
+  /**
+   * Normalize vector
+   *
+   * @param v makes len(v)==1
+   */
+  public static final void normalize(FloatBuffer v) {
+    final int vPos = v.position();
+
+    float r = (float) Math.sqrt(v.get(0+vPos) * v.get(0+vPos) +
+                                v.get(1+vPos) * v.get(1+vPos) +
+                                v.get(2+vPos) * v.get(2+vPos));
+    
+    if ( r == 0.0 || r == 1.0) {
+      return;
+    }
+
+    r = 1.0f / r;
+
+    v.put(0+vPos, v.get(0+vPos) * r);
+    v.put(1+vPos, v.get(1+vPos) * r);
+    v.put(2+vPos, v.get(2+vPos) * r);
+  }
+
+
+  /**
+   * Calculate cross-product
+   *
+   * @param v1
+   * @param v2
+   * @param result v1 X v2
+   */
+  public static final void cross(float[] v1, float[] v2, float[] result) {
+    result[0] = v1[1] * v2[2] - v1[2] * v2[1];
+    result[1] = v1[2] * v2[0] - v1[0] * v2[2];
+    result[2] = v1[0] * v2[1] - v1[1] * v2[0];
+  }
+
+  /**
+   * Calculate cross-product
+   *
+   * @param v1
+   * @param v2
+   * @param result v1 X v2
+   */
+  public static final void cross(FloatBuffer v1, FloatBuffer v2, FloatBuffer result) {
+    final int v1Pos = v1.position();
+    final int v2Pos = v2.position();
+    final int rPos  = result.position();
+
+    result.put(0+rPos, v1.get(1+v1Pos) * v2.get(2+v2Pos) - v1.get(2+v1Pos) * v2.get(1+v2Pos));
+    result.put(1+rPos, v1.get(2+v1Pos) * v2.get(0+v2Pos) - v1.get(0+v1Pos) * v2.get(2+v2Pos));
+    result.put(2+rPos, v1.get(0+v1Pos) * v2.get(1+v2Pos) - v1.get(1+v1Pos) * v2.get(0+v2Pos));
+  }
+
+  /**
+   * Method __gluMultMatrixVecf
+   * 
+   * @param m_in
+   * @param m_in_off
+   * @param v_in
+   * @param v_out m_in * v_in
+   */
+  public static final void multMatrixVecf(float[] m_in, int m_in_off, float[] v_in, int v_in_off, float[] v_out) {
+    for (int i = 0; i < 4; i++) {
+      v_out[i] =
+        v_in[0+v_in_off] * m_in[0*4+i+m_in_off] +
+        v_in[1+v_in_off] * m_in[1*4+i+m_in_off] +
+        v_in[2+v_in_off] * m_in[2*4+i+m_in_off] +
+        v_in[3+v_in_off] * m_in[3*4+i+m_in_off];
+    }
+  }
+
+  /**
+   * Method __gluMultMatrixVecf
+   * 
+   * @param m_in
+   * @param m_in_off
+   * @param v_in
+   * @param v_out m_in * v_in
+   */
+  public static final void multMatrixVecf(float[] m_in, float[] v_in, float[] v_out) {
+    for (int i = 0; i < 4; i++) {
+      v_out[i] =
+        v_in[0] * m_in[0*4+i] +
+        v_in[1] * m_in[1*4+i] +
+        v_in[2] * m_in[2*4+i] +
+        v_in[3] * m_in[3*4+i];
+    }
+  }
+  
+  /**
+   * Method __gluMultMatrixVecf
+   * 
+   * @param m_in
+   * @param v_in
+   * @param v_out m_in * v_in
+   */
+  public static final void multMatrixVecf(FloatBuffer m_in, FloatBuffer v_in, FloatBuffer v_out) {
+    int inPos = v_in.position();
+    int outPos = v_out.position();
+    int matrixPos = m_in.position();
+    for (int i = 0; i < 4; i++) {
+      v_out.put(i + outPos,
+              v_in.get(0+inPos) * m_in.get(0*4+i+matrixPos) +
+              v_in.get(1+inPos) * m_in.get(1*4+i+matrixPos) +
+              v_in.get(2+inPos) * m_in.get(2*4+i+matrixPos) +
+              v_in.get(3+inPos) * m_in.get(3*4+i+matrixPos));
+    }
+  }
+
+}
\ No newline at end of file
diff --git a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java
index 8cb2517..c8e5d21 100644
--- a/src/jogl/classes/com/jogamp/opengl/JoglVersion.java
+++ b/src/jogl/classes/com/jogamp/opengl/JoglVersion.java
@@ -30,10 +30,12 @@ package com.jogamp.opengl;
 
 import com.jogamp.common.GlueGenVersion;
 import javax.media.opengl.*;
+
 import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.VersionUtil;
 import com.jogamp.common.util.JogampVersion;
-import com.jogamp.nativewindow.NativeWindowVersion;
+
+import java.util.List;
 import java.util.jar.Manifest;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 
@@ -68,6 +70,48 @@ public class JoglVersion extends JogampVersion {
         return toString(gl, null).toString();
     }
 
+    public static StringBuilder getAvailableCapabilitiesInfo(GLDrawableFactory factory, AbstractGraphicsDevice device, StringBuilder sb) {
+        if(null==sb) {
+            sb = new StringBuilder();
+        }
+        boolean done = false;
+        if(null!=factory) {
+            try {
+                final List<GLCapabilitiesImmutable> availCaps = factory.getAvailableCapabilities(device);
+                if(null != availCaps && availCaps.size()>0) {
+                    for(int i=0; i<availCaps.size(); i++) {
+                        sb.append("\t").append(availCaps.get(i)).append(Platform.getNewline());
+                    }
+                    done = true;
+                }
+            } catch (GLException gle) { /* n/a */ }
+        }
+        if(!done) {
+            sb.append("\tnone").append(Platform.getNewline());
+        }
+        sb.append(Platform.getNewline());
+        return sb;        
+    }
+    
+    public static StringBuilder getDefaultOpenGLInfo(StringBuilder sb) {
+        if(null==sb) {
+            sb = new StringBuilder();
+        }
+        final AbstractGraphicsDevice device = GLProfile.getDefaultDevice();
+        sb.append("Default Profiles     ").append(Platform.getNewline());
+        if(null!=device) {
+            GLProfile.glAvailabilityToString(device, sb, "\t", 1);
+        } else {
+            sb.append("none");
+        }
+        sb.append(Platform.getNewline()).append(Platform.getNewline());
+        sb.append("Desktop Capabilities: ").append(Platform.getNewline());
+        getAvailableCapabilitiesInfo(GLDrawableFactory.getDesktopFactory(), device, sb);
+        sb.append("EGL Capabilities: ").append(Platform.getNewline());
+        getAvailableCapabilitiesInfo(GLDrawableFactory.getEGLFactory(), device, sb);
+        return sb;
+    }
+    
     public static StringBuilder getGLInfo(GL gl, StringBuilder sb) {
         AbstractGraphicsDevice device = gl.getContext().getGLDrawable().getNativeSurface()
                                             .getGraphicsConfiguration().getScreen().getDevice();
@@ -78,30 +122,35 @@ public class JoglVersion extends JogampVersion {
 
         sb.append(VersionUtil.SEPERATOR).append(Platform.getNewline());
         sb.append(device.getClass().getSimpleName()).append("[type ")
-                .append(device.getType()).append(", connection ").append(device.getConnection()).append("]: ")
-                .append(GLProfile.glAvailabilityToString(device));
+                .append(device.getType()).append(", connection ").append(device.getConnection()).append("]: ").append(Platform.getNewline());
+        GLProfile.glAvailabilityToString(device, sb, "\t", 1);        
         sb.append(Platform.getNewline());
-        sb.append("Swap Interval ").append(gl.getSwapInterval());
+        sb.append("Swap Interval  ").append(gl.getSwapInterval());
         sb.append(Platform.getNewline());
-        sb.append("GL Profile    ").append(gl.getGLProfile());
+        sb.append("GL Profile     ").append(gl.getGLProfile());
         sb.append(Platform.getNewline());
-        sb.append("CTX VERSION   ").append(gl.getContext().getGLVersion());
+        sb.append("CTX VERSION    ").append(gl.getContext().getGLVersion());
         sb.append(Platform.getNewline());
-        sb.append("GL            ").append(gl);
+        sb.append("GL             ").append(gl);
         sb.append(Platform.getNewline());
-        sb.append("GL_VENDOR     ").append(gl.glGetString(gl.GL_VENDOR));
+        sb.append("GL_VENDOR      ").append(gl.glGetString(GL.GL_VENDOR));
         sb.append(Platform.getNewline());
-        sb.append("GL_VERSION    ").append(gl.glGetString(gl.GL_VERSION));
+        sb.append("GL_RENDERER    ").append(gl.glGetString(GL.GL_RENDERER));
         sb.append(Platform.getNewline());
-        sb.append("GL_EXTENSIONS ");
+        sb.append("GL_VERSION     ").append(gl.glGetString(GL.GL_VERSION));
+        sb.append(Platform.getNewline());        
+        sb.append("GLSL           ").append(gl.hasGLSL()).append(", has-compiler: ").append(gl.isFunctionAvailable("glCompileShader"));
+        if(gl.hasGLSL()) {
+            sb.append(", version: ").append(gl.glGetString(GL2ES2.GL_SHADING_LANGUAGE_VERSION));
+        }
         sb.append(Platform.getNewline());
-        sb.append("              ").append(ctx.getGLExtensionsString());
+        sb.append("GL_EXTENSIONS  ").append(ctx.getGLExtensionCount());
         sb.append(Platform.getNewline());
-        sb.append("GLX_EXTENSIONS ");
+        sb.append("               ").append(ctx.getGLExtensionsString());
         sb.append(Platform.getNewline());
-        sb.append("              ").append(ctx.getPlatformExtensionsString());
+        sb.append("GLX_EXTENSIONS ").append(ctx.getPlatformExtensionCount());
         sb.append(Platform.getNewline());
-        sb.append("GLSL          ").append(gl.hasGLSL()).append(", shader-compiler: ").append(gl.isFunctionAvailable("glCompileShader"));
+        sb.append("               ").append(ctx.getPlatformExtensionsString());
         sb.append(Platform.getNewline());
         sb.append(VersionUtil.SEPERATOR);
 
diff --git a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java
index ba159b8..d901096 100644
--- a/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/com/jogamp/opengl/cg/CgDynamicLibraryBundleInfo.java
@@ -29,8 +29,10 @@
 package com.jogamp.opengl.cg;
 
 import com.jogamp.common.jvm.JNILibLoaderBase;
+import com.jogamp.common.os.DynamicLibraryBundle;
 import com.jogamp.common.os.DynamicLibraryBundleInfo;
 import com.jogamp.common.os.Platform;
+import com.jogamp.common.util.RunnableExecutor;
 import com.jogamp.common.util.cache.TempJarCache;
 
 import java.security.AccessController;
@@ -66,25 +68,31 @@ public class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo {
     }
 
     /** Make Cg symbols available to CgGL */
+    @Override
     public boolean shallLinkGlobal() { return true; }
 
     /** default **/
+    @Override
     public boolean shallLookupGlobal() { return false; }
 
     /** Tool has none **/
+    @Override
     public final List<String> getToolGetProcAddressFuncNameList() {
         return null;
     }
 
     /** Tool has none **/
+    @Override
     public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
         return 0;
     }
     
+    @Override
     public boolean useToolGetProcAdressFirst(String funcName) {
         return false;
     }
 
+    @Override
     public List<List<String>> getToolLibNames() {
         final List<List<String>> libsList = new ArrayList<List<String>>();
         final List<String> libsCg = new ArrayList<String>();
@@ -98,9 +106,15 @@ public class CgDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo {
         return libsList;
     }
 
+    @Override
     public final List<String> getGlueLibNames() {
         return glueLibNames;
     }
+
+    @Override
+    public RunnableExecutor getLibLoaderExecutor() {
+        return DynamicLibraryBundle.getDefaultRunnableExecutor();
+    }    
 }
 
 
diff --git a/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java
new file mode 100644
index 0000000..f2cddca
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/swt/GLCanvas.java
@@ -0,0 +1,563 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ *
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ *
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.swt;
+
+import javax.media.nativewindow.AbstractGraphicsDevice;
+import javax.media.nativewindow.NativeSurface;
+import javax.media.nativewindow.ProxySurface;
+import javax.media.opengl.GL;
+import javax.media.opengl.GLAnimatorControl;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesChooser;
+import javax.media.opengl.GLCapabilitiesImmutable;
+import javax.media.opengl.GLContext;
+import javax.media.opengl.GLDrawable;
+import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.GLRunnable;
+import javax.media.opengl.Threading;
+
+import jogamp.opengl.GLContextImpl;
+import jogamp.opengl.GLDrawableHelper;
+import jogamp.opengl.ThreadingImpl;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ControlAdapter;
+import org.eclipse.swt.events.ControlEvent;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+
+import com.jogamp.common.GlueGenVersion;
+import com.jogamp.common.util.VersionUtil;
+import com.jogamp.common.util.locks.LockFactory;
+import com.jogamp.common.util.locks.RecursiveLock;
+import com.jogamp.nativewindow.swt.SWTAccessor;
+import com.jogamp.opengl.JoglVersion;
+
+/**
+ * Native SWT Canvas implementing GLAutoDrawable
+ * <p>
+ * FIXME: Still needs AWT for threading impl., 
+ *        ie. will issue a 'wrong thread' error if runs in headless mode!
+ * </p>
+ */
+public class GLCanvas extends Canvas implements GLAutoDrawable {
+
+   /*
+    * Flag for whether the SWT thread should be used for OpenGL calls when in single-threaded mode. This is controlled
+    * by the setting of the threading mode to worker (do not use SWT thread), awt (use SWT thread), or false (always use
+    * calling thread).
+    * 
+    * @see Threading
+    * 
+    * Now done dynamically to avoid early loading of gluegen library.
+    */
+   //private static final boolean useSWTThread = ThreadingImpl.getMode() != ThreadingImpl.WORKER;
+
+   /* GL Stuff */
+   private final GLDrawableHelper drawableHelper = new GLDrawableHelper();
+   private GLDrawable drawable;
+   private GLContext context;
+
+   /* Native window surface */
+   private AbstractGraphicsDevice device;
+   private final long nativeWindowHandle;
+   private final ProxySurface proxySurface;
+
+   /* Construction parameters stored for GLAutoDrawable accessor methods */
+   private int ctxCreationFlags = 0;
+   
+   private final GLCapabilitiesImmutable glCapsRequested;
+
+   /*
+    * Lock for access to GLDrawable, as used in GLCanvas,
+    */
+   private final RecursiveLock lock = LockFactory.createRecursiveLock();
+
+   /* Flag indicating whether an unprocessed reshape is pending. */
+   private volatile boolean sendReshape;
+
+   /*
+    * Invokes init(...) on all GLEventListeners. Assumes context is current when run.
+    */
+   private final Runnable initAction = new Runnable() {
+      public void run() {
+         drawableHelper.init(GLCanvas.this);
+      }
+   };
+
+   /*
+    * Action to handle display in OpenGL, also processes reshape since they should be done at the same time.
+    * 
+    * Assumes GLContext is current when run.
+    */
+   private final Runnable displayAction = new Runnable() {
+      public void run() {
+         if (sendReshape) {
+            drawableHelper.reshape(GLCanvas.this, 0, 0, getWidth(), getHeight());
+            sendReshape = false;
+         }
+         drawableHelper.display(GLCanvas.this);
+      }
+   };
+
+   /* Action to make specified context current prior to running displayAction */
+   private final Runnable makeCurrentAndDisplayAction = new Runnable() {
+      public void run() {
+         drawableHelper.invokeGL(drawable, context, displayAction, initAction);
+      }
+   };
+
+   /* Swaps buffers, assuming the GLContext is current */
+   private final Runnable swapBuffersAction = new Runnable() {
+      public void run() {
+         drawable.swapBuffers();
+      }
+   };
+
+   /* Swaps buffers, making the GLContext current first */
+   private final Runnable makeCurrentAndSwapBuffersAction = new Runnable() {
+      public void run() {
+         drawableHelper.invokeGL(drawable, context, swapBuffersAction, initAction);
+      }
+   };
+
+   /*
+    * Disposes of OpenGL resources
+    */
+   private final Runnable postDisposeGLAction = new Runnable() {
+      public void run() {
+         context = null;         
+         if (null != drawable) {
+            drawable.setRealized(false);
+            drawable = null;
+         }
+      }
+   };
+
+   private final Runnable disposeOnEDTGLAction = new Runnable() {
+      public void run() {
+         drawableHelper.disposeGL(GLCanvas.this, drawable, context, postDisposeGLAction);
+      }
+   };
+
+   private final Runnable disposeGraphicsDeviceAction = new Runnable() {
+      public void run() {
+         if (null != device) {
+            device.close();
+            device = null;
+         }
+      }
+   };
+
+   /**
+    * Storage for the client area rectangle so that it may be accessed from outside of the SWT thread.
+    */
+   private volatile Rectangle clientArea;
+
+   /**
+    * Creates a new SWT GLCanvas.
+    * 
+    * @param parent
+    *           Required (non-null) parent Composite.
+    * @param style
+    *           Optional SWT style bit-field. The {@link SWT#NO_BACKGROUND} bit is set before passing this up to the
+    *           Canvas constructor, so OpenGL handles the background.
+    * @param caps
+    *           Optional GLCapabilities. If not provided, the default capabilities for the default GLProfile for the
+    *           graphics device determined by the parent Composite are used. Note that the GLCapabilities that are
+    *           actually used may differ based on the capabilities of the graphics device.
+    * @param chooser
+    *           Optional GLCapabilitiesChooser to customize the selection of the used GLCapabilities based on the
+    *           requested GLCapabilities, and the available capabilities of the graphics device.
+    * @param shareWith
+    *           Optional GLContext to share state (textures, vbos, shaders, etc.) with.
+    */
+   public GLCanvas(final Composite parent, final int style, GLCapabilitiesImmutable caps,
+                   final GLCapabilitiesChooser chooser, final GLContext shareWith) {
+      /* NO_BACKGROUND required to avoid clearing bg in native SWT widget (we do this in the GL display) */
+      super(parent, style | SWT.NO_BACKGROUND);
+      
+      GLProfile.initSingleton(); // ensure JOGL is completly initialized
+
+      SWTAccessor.setRealized(this, true);
+
+      clientArea = GLCanvas.this.getClientArea();
+
+      /* Get the nativewindow-Graphics Device associated with this control (which is determined by the parent Composite) */
+      device = SWTAccessor.getDevice(this);
+      /* Native handle for the control, used to associate with GLContext */
+      nativeWindowHandle = SWTAccessor.getWindowHandle(this);
+
+      /* Select default GLCapabilities if none was provided, otherwise clone provided caps to ensure safety */
+      if(null == caps) {
+          caps = new GLCapabilities(GLProfile.getDefault(device));
+      }
+      glCapsRequested = caps;
+      
+      final GLDrawableFactory glFactory = GLDrawableFactory.getFactory(caps.getGLProfile());
+
+      /* Create a NativeWindow proxy for the SWT canvas */
+      proxySurface = glFactory.createProxySurface(device, nativeWindowHandle, caps, chooser);
+
+      /* Associate a GL surface with the proxy */
+      drawable = glFactory.createGLDrawable(proxySurface);
+      drawable.setRealized(true);
+
+      context = drawable.createContext(shareWith);
+      context.setSynchronized(true);
+      
+      /* Register SWT listeners (e.g. PaintListener) to render/resize GL surface. */
+      /* TODO: verify that these do not need to be manually de-registered when destroying the SWT component */
+      addPaintListener(new PaintListener() {
+         public void paintControl(final PaintEvent arg0) {
+            if (!drawableHelper.isExternalAnimatorAnimating()) {
+               display();
+            }
+         }
+      });
+      
+      addControlListener(new ControlAdapter() {
+         @Override
+         public void controlResized(final ControlEvent arg0) {
+            clientArea = GLCanvas.this.getClientArea();
+            /* Mark for OpenGL reshape next time the control is painted */
+            sendReshape = true;
+         }
+      });
+   }
+
+   public void addGLEventListener(final GLEventListener arg0) {
+      drawableHelper.addGLEventListener(arg0);
+   }
+
+   public void addGLEventListener(final int arg0, final GLEventListener arg1) throws IndexOutOfBoundsException {
+      drawableHelper.addGLEventListener(arg0, arg1);
+   }
+
+   /**
+    * {@inheritDoc}
+    * <p>
+    * Also disposes of the SWT component.
+    */
+   public void destroy() {
+      drawable.setRealized(false);
+      dispose();
+   }
+
+   public void display() {
+      runInGLThread(makeCurrentAndDisplayAction, displayAction);
+   }
+
+   public GLAnimatorControl getAnimator() {
+      return drawableHelper.getAnimator();
+   }
+
+   public boolean getAutoSwapBufferMode() {
+      return drawableHelper.getAutoSwapBufferMode();
+   }
+
+   public GLContext getContext() {
+      return context;
+   }
+
+   public int getContextCreationFlags() {
+      return ctxCreationFlags;
+   }
+
+   public GL getGL() {
+      final GLContext ctx = getContext();
+      return (ctx == null) ? null : ctx.getGL();
+   }
+
+   public void invoke(final boolean wait, final GLRunnable run) {
+      /* Queue task for running during the next display(). */
+      drawableHelper.invoke(this, wait, run);
+   }
+
+   public void removeGLEventListener(final GLEventListener arg0) {
+      drawableHelper.removeGLEventListener(arg0);
+   }
+
+   public void setAnimator(final GLAnimatorControl arg0) throws GLException {
+      drawableHelper.setAnimator(arg0);
+   }
+
+   public void setAutoSwapBufferMode(final boolean arg0) {
+      drawableHelper.setAutoSwapBufferMode(arg0);
+   }
+
+   public void setContext(final GLContext ctx) {
+      this.context = ctx;
+      if (ctx instanceof GLContextImpl) {
+         ((GLContextImpl) ctx).setContextCreationFlags(ctxCreationFlags);
+      }
+   }
+
+   public void setContextCreationFlags(final int arg0) {
+      ctxCreationFlags = arg0;
+   }
+
+   public GL setGL(final GL arg0) {
+      final GLContext ctx = getContext();
+      if (ctx != null) {
+         ctx.setGL(arg0);
+         return arg0;
+      }
+      return null;
+   }
+
+   public GLContext createContext(final GLContext arg0) {
+      lock.lock();
+      try {
+         final GLDrawable drawable = this.drawable;
+         return (drawable != null) ? drawable.createContext(arg0) : null;
+      } finally {
+         lock.unlock();
+      }
+   }
+
+   public GLCapabilitiesImmutable getChosenGLCapabilities() {
+      return (GLCapabilitiesImmutable)proxySurface.getGraphicsConfiguration().getChosenCapabilities();
+   }
+
+   /**
+    * Accessor for the GLCapabilities that were requested (via the constructor parameter).
+    * 
+    * @return Non-null GLCapabilities.
+    */
+   public GLCapabilitiesImmutable getRequestedGLCapabilities() {
+      return (GLCapabilitiesImmutable)proxySurface.getGraphicsConfiguration().getRequestedCapabilities();
+   }
+
+   public GLDrawableFactory getFactory() {
+      lock.lock();
+      try {
+         final GLDrawable drawable = this.drawable;
+         return (drawable != null) ? drawable.getFactory() : null;
+      } finally {
+         lock.unlock();
+      }
+   }
+
+   public GLProfile getGLProfile() {
+      return glCapsRequested.getGLProfile();
+   }
+
+   public long getHandle() {
+      lock.lock();
+      try {
+         final GLDrawable drawable = this.drawable;
+         return (drawable != null) ? drawable.getHandle() : 0;
+      } finally {
+         lock.unlock();
+      }
+   }
+
+   public int getHeight() {
+      final Rectangle clientArea = this.clientArea;
+      if (clientArea == null) return 0;
+      return clientArea.height;
+   }
+
+   public NativeSurface getNativeSurface() {
+      lock.lock();
+      try {
+         final GLDrawable drawable = this.drawable;
+         return (drawable != null) ? drawable.getNativeSurface() : null;
+      } finally {
+         lock.unlock();
+      }
+   }
+
+   public int getWidth() {
+      final Rectangle clientArea = this.clientArea;
+      if (clientArea == null) return 0;
+      return clientArea.width;
+   }
+
+   public boolean isRealized() {
+      lock.lock();
+      try {
+         final GLDrawable drawable = this.drawable;
+         return (drawable != null) ? drawable.isRealized() : false;
+      } finally {
+         lock.unlock();
+      }
+   }
+
+   public void setRealized(final boolean arg0) {
+      /* Intentionally empty */
+   }
+
+   public void swapBuffers() throws GLException {
+      runInGLThread(makeCurrentAndSwapBuffersAction, swapBuffersAction);
+   }
+
+   // FIXME: API of update() method ?
+   public void update() {
+    // FIXME:     display();
+   }
+
+   public void dispose() {
+      lock.lock();
+      try {
+         final Display display = getDisplay();
+
+         if (null != context) {
+            boolean animatorPaused = false;
+            final GLAnimatorControl animator = getAnimator();
+            if (null != animator) {
+               // can't remove us from animator for recreational addNotify()
+               animatorPaused = animator.pause();
+            }
+            if(context.isCreated()) {
+                if (Threading.isSingleThreaded() && !Threading.isOpenGLThread()) {
+                   runInDesignatedGLThread(disposeOnEDTGLAction);
+                } else if (context.isCreated()) {
+                   drawableHelper.disposeGL(GLCanvas.this, drawable, context, postDisposeGLAction);
+                }
+            }
+
+            if (animatorPaused) {
+               animator.resume();
+            }
+         }
+         if (display.getThread() == Thread.currentThread()) {
+            disposeGraphicsDeviceAction.run();
+         } else {
+            display.syncExec(disposeGraphicsDeviceAction);
+         }
+      } finally {
+         lock.unlock();
+      }
+      super.dispose();
+   }
+
+   /**
+    * Determines whether the current thread is the appropriate thread to use the GLContext in. If we are using one of
+    * the single-threaded policies in {@link Threading}, than this is either the SWT event dispatch thread, or the
+    * OpenGL worker thread depending on the state of {@link #useSWTThread}. Otherwise this always returns true because
+    * the threading model is user defined.
+    * <p>
+    * TODO: should this be moved to {@link Threading}?
+    * 
+    * @return true if the calling thread is the correct thread to execute OpenGL calls in, false otherwise.
+    */
+   protected boolean isRenderThread() {
+      if (Threading.isSingleThreaded()) {
+         if (ThreadingImpl.getMode() != ThreadingImpl.Mode.ST_WORKER) {
+            final Display display = getDisplay();
+            return display != null && display.getThread() == Thread.currentThread();
+         }
+         return Threading.isOpenGLThread();
+      }
+      /*
+       * For multi-threaded rendering, the render thread is not defined...
+       */
+      return true;
+   }
+
+   /**
+    * Runs the specified action in the designated OpenGL thread. If the current thread is designated, then the
+    * syncAction is run synchronously, otherwise the asyncAction is dispatched to the appropriate worker thread.
+    * 
+    * @param asyncAction
+    *           The non-null action to dispatch to an OpenGL worker thread. This action should not assume that a
+    *           GLContext is current when invoked.
+    * @param syncAction
+    *           The non-null action to run synchronously if the current thread is designated to handle OpenGL calls.
+    *           This action may assume the GLContext is current.
+    */
+   private void runInGLThread(final Runnable asyncAction, final Runnable syncAction) {
+      if (Threading.isSingleThreaded() && !isRenderThread()) {
+         /* Run in designated GL thread */
+         runInDesignatedGLThread(asyncAction);
+      } else {
+         /* Run in current thread... */
+         drawableHelper.invokeGL(drawable, context, syncAction, initAction);
+      }
+   }
+
+   /**
+    * Dispatches the specified runnable to the appropriate OpenGL worker thread (either the SWT event dispatch thread,
+    * or the OpenGL worker thread depending on the state of {@link #useSWTThread}).
+    * 
+    * @param makeCurrentAndRunAction
+    *           The non-null action to dispatch.
+    */
+   private void runInDesignatedGLThread(final Runnable makeCurrentAndRunAction) {
+      if (ThreadingImpl.getMode() != ThreadingImpl.Mode.ST_WORKER) {
+         final Display display = getDisplay();
+         assert display.getThread() != Thread.currentThread() : "Incorrect use of thread dispatching.";
+         display.syncExec(makeCurrentAndRunAction);
+      } else {
+         Threading.invokeOnOpenGLThread(true, makeCurrentAndRunAction);
+      }
+   }
+
+   
+   public static void main(final String[] args) {
+       System.err.println(VersionUtil.getPlatformInfo());
+       System.err.println(GlueGenVersion.getInstance());
+       // System.err.println(NativeWindowVersion.getInstance());
+       System.err.println(JoglVersion.getInstance());
+
+       System.err.println(JoglVersion.getDefaultOpenGLInfo(null).toString());
+       
+       final GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault(GLProfile.getDefaultDevice()) );
+       final Display display = new Display();
+       final Shell shell = new Shell(display);
+       shell.setSize(128,128);
+       shell.setLayout(new FillLayout());
+
+       final GLCanvas canvas = new GLCanvas(shell, 0, caps, null, null);
+
+       canvas.addGLEventListener(new GLEventListener() {
+           public void init(final GLAutoDrawable drawable) {
+               GL gl = drawable.getGL();
+               System.err.println(JoglVersion.getGLInfo(gl, null));
+           }
+           public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) {}                 
+           public void display(final GLAutoDrawable drawable) {}
+           public void dispose(final GLAutoDrawable drawable) {}         
+       });
+       shell.open();
+       canvas.display();
+       display.dispose();
+   }
+}
diff --git a/src/jogl/classes/com/jogamp/opengl/util/Animator.java b/src/jogl/classes/com/jogamp/opengl/util/Animator.java
index a902388..20ba27c 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/Animator.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/Animator.java
@@ -243,7 +243,8 @@ public class Animator extends AnimatorBase {
         // dependencies on the Animator's internal thread. Currently we
         // use a couple of heuristics to determine whether we should do
         // the blocking wait().
-        long remaining = impl.blockUntilDone(animThread) ? TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION : 0;
+        final boolean blocking = impl.blockUntilDone(animThread);
+        long remaining = blocking ? TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION : 0;
         while (remaining>0 && condition.result()) {
             long td = System.currentTimeMillis();
             try {
@@ -253,12 +254,13 @@ public class Animator extends AnimatorBase {
         }
         if(DEBUG) {
             if(remaining<0) {
-                System.err.println("finishLifecycleAction(" + condition.getClass().getName() + "): ++++++ timeout reached ++++++ ");
+                System.err.println("finishLifecycleAction(" + condition.getClass().getName() + "): ++++++ timeout reached ++++++ " + Thread.currentThread().getName());
             }
             System.err.println("finishLifecycleAction(" + condition.getClass().getName() + "): finished "+
-                    "- waited " + (TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION-remaining) + "/" + TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION + 
+                    "- blocking "+blocking+
+                    ", waited " + (blocking ? ( TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION - remaining ) : 0 ) + "/" + TO_WAIT_FOR_FINISH_LIFECYCLE_ACTION + 
                     ", started: " + isStartedImpl() +", animating: " + isAnimatingImpl() +
-                    ", paused: " + isPausedImpl() + ", drawables " + drawables.size());
+                    ", paused: " + isPausedImpl() + ", drawables " + drawables.size() + " - " + Thread.currentThread().getName());
         }
     }
 
@@ -277,6 +279,11 @@ public class Animator extends AnimatorBase {
         } else {
             thread = new Thread(threadGroup, runnable, threadName);
         }
+        thread.setDaemon(false); // force to be non daemon, regardless of parent thread 
+        if(DEBUG) {
+            final Thread ct = Thread.currentThread();
+            System.err.println("Animator "+ct.getName()+"[daemon "+ct.isDaemon()+"]: starting "+thread.getName()+"[daemon "+thread.isDaemon()+"]");
+        }
         thread.start();
         finishLifecycleAction(waitForStartedCondition);
         return true;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java
index 9bea27f..d65967d 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/AnimatorBase.java
@@ -92,7 +92,7 @@ public abstract class AnimatorBase implements GLAnimatorControl {
 
     public synchronized void add(GLAutoDrawable drawable) {
         if(DEBUG) {
-            System.err.println("Animator add: "+drawable.hashCode()+" - "+Thread.currentThread());
+            System.err.println("Animator add: "+drawable.hashCode()+" - "+Thread.currentThread().getName());
         }
         boolean paused = pause();
         drawables.add(drawable);
@@ -113,7 +113,7 @@ public abstract class AnimatorBase implements GLAnimatorControl {
 
     public synchronized void remove(GLAutoDrawable drawable) {
         if(DEBUG) {
-            System.err.println("Animator remove: "+drawable.hashCode()+" - "+Thread.currentThread() + ": "+toString());
+            System.err.println("Animator remove: "+drawable.hashCode()+" - "+Thread.currentThread().getName() + ": "+toString());
         }
 
         boolean paused = pause();
diff --git a/src/jogl/classes/com/jogamp/opengl/util/FBObject.java b/src/jogl/classes/com/jogamp/opengl/util/FBObject.java
index 0b60941..3e049a3 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/FBObject.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/FBObject.java
@@ -210,18 +210,14 @@ public class FBObject {
      */
     public int attachTexture2D(GL gl, int texUnit, int magFilter, int minFilter, int wrapS, int wrapT) throws GLException {
         final int textureInternalFormat, textureDataFormat, textureDataType;
-        if(gl.isGL2()) { 
-            textureInternalFormat=GL.GL_RGBA8;
-            textureDataFormat=GL2.GL_BGRA;
-            textureDataType=GL2.GL_UNSIGNED_INT_8_8_8_8_REV;
-        } else if(gl.isGLES()) { 
+        if(gl.isGLES()) { 
             textureInternalFormat=GL.GL_RGBA;
             textureDataFormat=GL.GL_RGBA;
             textureDataType=GL.GL_UNSIGNED_BYTE;
-        } else {
-            textureInternalFormat=GL.GL_RGB;
-            textureDataFormat=GL.GL_RGB;
-            textureDataType=GL.GL_UNSIGNED_BYTE;
+        } else { 
+            textureInternalFormat=GL.GL_RGBA8;
+            textureDataFormat=GL.GL_BGRA;
+            textureDataType=GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV;
         }
         return attachTexture2D(gl, texUnit, textureInternalFormat, textureDataFormat, textureDataType, magFilter, minFilter, wrapS, wrapT);
     }
@@ -265,7 +261,18 @@ public class FBObject {
         checkNoError(gl, gl.glGetError(), "FBObject Init.bindTex");  // throws GLException if error        
         gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, textureInternalFormat, width, height, 0,
                         textureDataFormat, textureDataType, null);
-        checkNoError(gl, gl.glGetError(), "FBObject Init.texImage2D");  // throws GLException if error        
+        int glerr = gl.glGetError();
+        if(GL.GL_NO_ERROR != glerr) {
+            int[] sz = new int[1];
+            gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, sz, 0);
+            // throws GLException if error
+            checkNoError(gl, glerr, "FBObject Init.texImage2D: "+
+                                    " int-fmt 0x"+Integer.toHexString(textureInternalFormat)+
+                                    ", "+width+"x"+height+
+                                    ", data-fmt 0x"+Integer.toHexString(textureDataFormat)+
+                                    ", data-type 0x"+Integer.toHexString(textureDataType)+
+                                    ", max tex-sz "+sz[0]);
+        }
         if( 0 < magFilter ) {
             gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter);
         }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java
index a61fe0d..134dd96 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataClient.java
@@ -23,7 +23,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
 
   /**
    * Create a client side buffer object, using a predefined fixed function array index
-   * and starting with a new created Buffer object with initialSize size
+   * and starting with a new created Buffer object with initialElementCount size
    *
    * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected.
    * On profile ES2 the fixed function emulation will transform these calls to 
@@ -37,16 +37,16 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
    * @param comps The array component number
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize
+   * @param initialElementCount
    *
    * @see javax.media.opengl.GLContext#getPredefinedArrayIndexName(int)
    */  
-  public static GLArrayDataClient createFixed(int index, int comps, int dataType, boolean normalized, int initialSize)
+  public static GLArrayDataClient createFixed(int index, int comps, int dataType, boolean normalized, int initialElementCount)
     throws GLException
   {
       GLArrayDataClient adc = new GLArrayDataClient();
       GLArrayHandler glArrayHandler = new GLFixedArrayHandler(adc);
-      adc.init(null, index, comps, dataType, normalized, 0, null, initialSize, false, glArrayHandler, 0, 0, 0, 0, false);
+      adc.init(null, index, comps, dataType, normalized, 0, null, initialElementCount, false, glArrayHandler, 0, 0, 0, 0, false);
       return adc;
   }
 
@@ -83,20 +83,20 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
 
   /**
    * Create a client side buffer object, using a custom GLSL array attribute name
-   * and starting with a new created Buffer object with initialSize size
+   * and starting with a new created Buffer object with initialElementCount size
    * @param name  The custom name for the GL attribute. 
    * @param comps The array component number
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize
+   * @param initialElementCount
    */
   public static GLArrayDataClient createGLSL(String name, int comps, 
-                                             int dataType, boolean normalized, int initialSize)
+                                             int dataType, boolean normalized, int initialElementCount)
     throws GLException
   {
       GLArrayDataClient adc = new GLArrayDataClient();
       GLArrayHandler glArrayHandler = new GLSLArrayHandler(adc);
-      adc.init(name, -1, comps, dataType, normalized, 0, null, initialSize, true, glArrayHandler, 0, 0, 0, 0, true);
+      adc.init(name, -1, comps, dataType, normalized, 0, null, initialElementCount, true, glArrayHandler, 0, 0, 0, 0, true);
       return adc;
   }
 
@@ -274,12 +274,12 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
                        ", index "+index+
                        ", location "+location+
                        ", isVertexAttribute "+isVertexAttribute+
-                       ", dataType "+componentType+ 
+                       ", dataType 0x"+Integer.toHexString(componentType)+ 
                        ", bufferClazz "+componentClazz+ 
                        ", elements "+getElementCount()+
                        ", components "+components+ 
                        ", stride "+strideB+"b "+strideL+"c"+
-                       ", initialSize "+initialSize+ 
+                       ", initialElementCount "+initialElementCount+ 
                        ", sealed "+sealed+ 
                        ", bufferEnabled "+bufferEnabled+ 
                        ", bufferWritten "+bufferWritten+ 
@@ -292,44 +292,46 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
 
   protected final boolean growBufferIfNecessary(int spare) {
     if(buffer==null || buffer.remaining()<spare) { 
-        growBuffer(Math.max(initialSize, spare));
+        growBuffer(Math.max(initialElementCount, spare));
         return true;
     }
     return false;
   }
 
-  protected final void growBuffer(int additional) {     
+  protected final void growBuffer(int additionalElements) {     
     if(!alive || sealed) {
        throw new GLException("Invalid state: "+this); 
     }
 
     // add the stride delta
-    additional += (additional/components)*(strideL-components);
+    additionalElements += (additionalElements/components)*(strideL-components);
 
-    int osize = (buffer!=null)?buffer.capacity():0;
+    final int osize = (buffer!=null) ? buffer.capacity() : 0;
+    final int nsize = osize + ( additionalElements * components );
+    
     if(componentClazz==ByteBuffer.class) {
-        ByteBuffer newBBuffer = Buffers.newDirectByteBuffer( (osize+additional) * components );
+        ByteBuffer newBBuffer = Buffers.newDirectByteBuffer( nsize );
         if(buffer!=null) {
             buffer.flip();
             newBBuffer.put((ByteBuffer)buffer);
         }
         buffer = newBBuffer;
     } else if(componentClazz==ShortBuffer.class) {
-        ShortBuffer newSBuffer = Buffers.newDirectShortBuffer( (osize+additional) * components );
+        ShortBuffer newSBuffer = Buffers.newDirectShortBuffer( nsize );
         if(buffer!=null) {
             buffer.flip();
             newSBuffer.put((ShortBuffer)buffer);
         }
         buffer = newSBuffer;
     } else if(componentClazz==IntBuffer.class) {
-        IntBuffer newIBuffer = Buffers.newDirectIntBuffer( (osize+additional) * components );
+        IntBuffer newIBuffer = Buffers.newDirectIntBuffer( nsize );
         if(buffer!=null) {
             buffer.flip();
             newIBuffer.put((IntBuffer)buffer);
         }
         buffer = newIBuffer;
     } else if(componentClazz==FloatBuffer.class) {
-        FloatBuffer newFBuffer = Buffers.newDirectFloatBuffer( (osize+additional) * components );
+        FloatBuffer newFBuffer = Buffers.newDirectFloatBuffer( nsize );
         if(buffer!=null) {
             buffer.flip();
             newFBuffer.put((FloatBuffer)buffer);
@@ -338,6 +340,9 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
     } else {
         throw new GLException("Given Buffer Class not supported: "+componentClazz+":\n\t"+this);
     }
+    if(DEBUG) {
+        System.err.println("*** Grow: comps: "+components+", "+(osize/components)+"/"+osize+" -> "+(nsize/components)+"/"+nsize+", "+this);
+    }
   }
 
   protected final void checkSeal(boolean test) throws GLException {
@@ -354,22 +359,22 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
   }
 
   protected void init(String name, int index, int comps, int dataType, boolean normalized, int stride, Buffer data, 
-                      int initialSize, boolean isVertexAttribute, GLArrayHandler handler,
+                      int initialElementCount, boolean isVertexAttribute, GLArrayHandler handler,
                       int vboName, long vboOffset, int vboUsage, int vboTarget, boolean usesGLSL)
     throws GLException
   {
     super.init(name, index, comps, dataType, normalized, stride, data, isVertexAttribute,
                vboName, vboOffset, vboUsage, vboTarget);
 
-    this.initialSize = initialSize;
+    this.initialElementCount = initialElementCount;
     this.glArrayHandler = handler;
     this.usesGLSL = usesGLSL;
     this.sealed=false;
     this.bufferEnabled=false;
     this.enableBufferAlways=false;
     this.bufferWritten=false;
-    if(null==buffer && initialSize>0) {
-        growBuffer(initialSize);
+    if(null==buffer && initialElementCount>0) {
+        growBuffer(initialElementCount);
     }
   }
 
@@ -389,7 +394,7 @@ public class GLArrayDataClient extends GLArrayDataWrapper implements GLArrayData
   protected boolean bufferWritten;
   protected boolean enableBufferAlways;
 
-  protected int initialSize;
+  protected int initialElementCount;
 
   protected GLArrayHandler glArrayHandler;
   protected boolean usesGLSL;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java
index 8d9d839..c9dd987 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataServer.java
@@ -60,7 +60,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
 
   /**
    * Create a VBO, using a predefined fixed function array index
-   * and starting with a new created Buffer object with initialSize size
+   * and starting with a new created Buffer object with initialElementCount size
    *
    * On profiles GL2 and ES1 the fixed function pipeline behavior is as expected.
    * On profile ES2 the fixed function emulation will transform these calls to 
@@ -74,39 +74,39 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
    * @param comps The array component number
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize
+   * @param initialElementCount
    * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW}
    *
    * @see javax.media.opengl.GLContext#getPredefinedArrayIndexName(int)
    */
-  public static GLArrayDataServer createFixed(int index, int comps, int dataType, boolean normalized, int initialSize, 
+  public static GLArrayDataServer createFixed(int index, int comps, int dataType, boolean normalized, int initialElementCount, 
                                               int vboUsage)
     throws GLException
   {
     GLArrayDataServer ads = new GLArrayDataServer();
     GLArrayHandler glArrayHandler = new GLFixedArrayHandler(ads);
-    ads.init(null, index, comps, dataType, normalized, 0, null, initialSize, false, glArrayHandler,
+    ads.init(null, index, comps, dataType, normalized, 0, null, initialElementCount, false, glArrayHandler,
              0, 0, vboUsage, GL.GL_ARRAY_BUFFER, false);
     return ads;
   }
 
   /**
    * Create a VBO, using a custom GLSL array attribute name
-   * and starting with a new created Buffer object with initialSize size
+   * and starting with a new created Buffer object with initialElementCount size
    * @param name  The custom name for the GL attribute    
    * @param comps The array component number
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize
+   * @param initialElementCount
    * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW}
    */
   public static GLArrayDataServer createGLSL(String name, int comps,
-                                             int dataType, boolean normalized, int initialSize, int vboUsage) 
+                                             int dataType, boolean normalized, int initialElementCount, int vboUsage) 
     throws GLException 
   {
     GLArrayDataServer ads = new GLArrayDataServer();
     GLArrayHandler glArrayHandler = new GLSLArrayHandler(ads);
-    ads.init(name, -1, comps, dataType, normalized, 0, null, initialSize,
+    ads.init(name, -1, comps, dataType, normalized, 0, null, initialElementCount,
              true, glArrayHandler, 0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true);
     return ads;
   }  
@@ -133,7 +133,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
              0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true);
     return ads;
   }
-
+  
   /**
    * Create a VBO data object for any target w/o render pipeline association, ie {@link GL#GL_ELEMENT_ARRAY_BUFFER}.
    * 
@@ -165,17 +165,17 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
    * 
    * @param comps The array component number
    * @param dataType The array index GL data type
-   * @param initialSize
+   * @param initialElementCount
    * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW}
    * @param vboTarget {@link GL#GL_ELEMENT_ARRAY_BUFFER}, ..
    */
-  public static GLArrayDataServer createData(int comps, int dataType, int initialSize, 
+  public static GLArrayDataServer createData(int comps, int dataType, int initialElementCount, 
                                              int vboUsage, int vboTarget)
     throws GLException
   {
     GLArrayDataServer ads = new GLArrayDataServer();
     GLArrayHandler glArrayHandler = new GLDataArrayHandler(ads);
-    ads.init(null, -1, comps, dataType, false, 0, null, initialSize, false, glArrayHandler,
+    ads.init(null, -1, comps, dataType, false, 0, null, initialElementCount, false, glArrayHandler,
              0, 0, vboUsage, vboTarget, false);
     return ads;
   }
@@ -183,22 +183,22 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
   
   /**
    * Create a VBO for fixed function interleaved array data
-   * starting with a new created Buffer object with initialSize size.
+   * starting with a new created Buffer object with initialElementCount size.
    * <p>User needs to <i>configure</i> the interleaved segments via {@link #addFixedSubArray(int, int, int)}.</p>
    * 
    * @param comps The total number of all interleaved components.
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize 
+   * @param initialElementCount 
    * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW}
    */
-  public static GLArrayDataServer createFixedInterleaved(int comps, int dataType, boolean normalized, int initialSize, 
+  public static GLArrayDataServer createFixedInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, 
                                               int vboUsage)
     throws GLException
   {
     GLArrayDataServer ads = new GLArrayDataServer();
     GLArrayHandler glArrayHandler = new GLArrayHandlerInterleaved(ads);
-    ads.init(GLPointerFuncUtil.mgl_InterleaveArray, -1, comps, dataType, false, 0, null, initialSize, false, glArrayHandler,
+    ads.init(GLPointerFuncUtil.mgl_InterleaveArray, -1, comps, dataType, false, 0, null, initialElementCount, false, glArrayHandler,
              0, 0, vboUsage, GL.GL_ARRAY_BUFFER, false);
     return ads;
   }
@@ -239,22 +239,22 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
   
   /**
    * Create a VBO for GLSL interleaved array data
-   * starting with a new created Buffer object with initialSize size.
+   * starting with a new created Buffer object with initialElementCount size.
    * <p>User needs to <i>configure</i> the interleaved segments via {@link #addGLSLSubArray(int, int, int)}.</p>
    * 
    * @param comps The total number of all interleaved components.
    * @param dataType The array index GL data type
    * @param normalized Whether the data shall be normalized
-   * @param initialSize 
+   * @param initialElementCount 
    * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW}
    */
-  public static GLArrayDataServer createGLSLInterleaved(int comps, int dataType, boolean normalized, int initialSize, 
+  public static GLArrayDataServer createGLSLInterleaved(int comps, int dataType, boolean normalized, int initialElementCount, 
                                               int vboUsage)
     throws GLException
   {
     GLArrayDataServer ads = new GLArrayDataServer();
     GLArrayHandler glArrayHandler = new GLSLArrayHandlerInterleaved(ads);
-    ads.init(GLPointerFuncUtil.mgl_InterleaveArray, -1, comps, dataType, false, 0, null, initialSize, false, glArrayHandler,
+    ads.init(GLPointerFuncUtil.mgl_InterleaveArray, -1, comps, dataType, false, 0, null, initialElementCount, false, glArrayHandler,
              0, 0, vboUsage, GL.GL_ARRAY_BUFFER, true);
     return ads;
   }
@@ -283,7 +283,7 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
       final GLArrayDataWrapper ad = GLArrayDataWrapper.createGLSL(
               name, comps, getComponentType(), 
               getNormalized(), getStride(), getBuffer(), 
-              getVBOName(), interleavedOffset, getVBOUsage(), vboTarget);     
+              getVBOName(), interleavedOffset, getVBOUsage(), vboTarget);      
       ad.setVBOEnabled(isVBO());
       interleavedOffset += comps * getComponentSizeInBytes();
       if(GL.GL_ARRAY_BUFFER == vboTarget) { 
@@ -301,10 +301,13 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
   //
 
   public void destroy(GL gl) {
+    // super.destroy(gl):
+    // - GLArrayDataClient.destroy(gl): disables & clears client-side buffer
+    //   - GLArrayDataWrapper.destroy(gl) (clears all values 'vboName' ..)
+    int _vboName = vboName;
     super.destroy(gl);
-    if(vboName!=0) {
-        int[] tmp = new int[1];
-        tmp[0] = vboName;
+    if(_vboName!=0) {
+        final int[] tmp = new int[] { _vboName } ;
         gl.glDeleteBuffers(1, tmp, 0);
         vboName = 0;
     }
@@ -329,17 +332,17 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
                        ", index "+index+
                        ", location "+location+
                        ", isVertexAttribute "+isVertexAttribute+
-                       ", dataType "+componentType+ 
+                       ", dataType 0x"+Integer.toHexString(componentType)+ 
                        ", bufferClazz "+componentClazz+ 
                        ", elements "+getElementCount()+
                        ", components "+components+ 
                        ", stride "+strideB+"b "+strideL+"c"+
-                       ", initialSize "+initialSize+
+                       ", initialElementCount "+initialElementCount+
                        ", vboEnabled "+vboEnabled+ 
                        ", vboName "+vboName+ 
                        ", vboUsage 0x"+Integer.toHexString(vboUsage)+ 
                        ", vboTarget 0x"+Integer.toHexString(vboTarget)+ 
-                       ", vboOffset 0x"+Long.toHexString(vboOffset)+                        
+                       ", vboOffset "+vboOffset+                        
                        ", sealed "+sealed+ 
                        ", bufferEnabled "+bufferEnabled+ 
                        ", bufferWritten "+bufferWritten+ 
@@ -353,12 +356,12 @@ public class GLArrayDataServer extends GLArrayDataClient implements GLArrayDataE
   //
 
   protected void init(String name, int index, int comps, int dataType, boolean normalized, 
-                      int stride, Buffer data, int initialSize, boolean isVertexAttribute,
+                      int stride, Buffer data, int initialElementCount, boolean isVertexAttribute,
                       GLArrayHandler glArrayHandler,
                       int vboName, long vboOffset, int vboUsage, int vboTarget, boolean usesGLSL)
     throws GLException
   {
-    super.init(name, index, comps, dataType, normalized, stride, data, initialSize, isVertexAttribute, glArrayHandler,
+    super.init(name, index, comps, dataType, normalized, stride, data, initialElementCount, isVertexAttribute, glArrayHandler,
                vboName, vboOffset, vboUsage, vboTarget, usesGLSL);
 
     vboEnabled=true;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java
index 4ca3825..bade0a3 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java
@@ -1,14 +1,24 @@
 
 package com.jogamp.opengl.util;
 
-import javax.media.opengl.*;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
+import java.nio.ShortBuffer;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES1;
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLArrayData;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
 import javax.media.opengl.fixedfunc.GLPointerFuncUtil;
 
-import jogamp.opengl.util.glsl.fixedfunc.*;
-
-import java.nio.*;
+import jogamp.opengl.Debug;
 
 public class GLArrayDataWrapper implements GLArrayData {
+  public static final boolean DEBUG = Debug.debug("GLArrayData");
 
   /**
    * Create a VBO, using a predefined fixed function array index, wrapping the given data.
@@ -28,8 +38,7 @@ public class GLArrayDataWrapper implements GLArrayData {
    * @throws GLException
    */
   public static GLArrayDataWrapper createFixed(int index, int comps, int dataType, boolean normalized, int stride, 
-                                               Buffer buffer, int vboName,
-                                               long vboOffset, int vboUsage, int vboTarget)
+                                               Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget)
     throws GLException
   {
       GLArrayDataWrapper adc = new GLArrayDataWrapper();
@@ -55,8 +64,7 @@ public class GLArrayDataWrapper implements GLArrayData {
    * @throws GLException
    */
   public static GLArrayDataWrapper createGLSL(String name, int comps, int dataType, boolean normalized, int stride, 
-                                             Buffer buffer, int vboName,                                             
-                                             long vboOffset, int vboUsage, int vboTarget)
+                                             Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget)
     throws GLException
   {
       GLArrayDataWrapper adc = new GLArrayDataWrapper();
@@ -149,7 +157,7 @@ public class GLArrayDataWrapper implements GLArrayData {
                        ", index "+index+
                        ", location "+location+
                        ", isVertexAttribute "+isVertexAttribute+
-                       ", dataType "+componentType+ 
+                       ", dataType 0x"+Integer.toHexString(componentType)+ 
                        ", bufferClazz "+componentClazz+ 
                        ", elements "+getElementCount()+
                        ", components "+components+ 
@@ -159,7 +167,7 @@ public class GLArrayDataWrapper implements GLArrayData {
                        ", vboName "+vboName+ 
                        ", vboUsage 0x"+Integer.toHexString(vboUsage)+ 
                        ", vboTarget 0x"+Integer.toHexString(vboTarget)+ 
-                       ", vboOffset 0x"+Long.toHexString(vboOffset)+ 
+                       ", vboOffset "+vboOffset+ 
                        ", alive "+alive+                       
                        "]";
   }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java
index 4ab6035..32391c6 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/GLBuffers.java
@@ -431,7 +431,7 @@ public class GLBuffers extends Buffers {
               break;
             case GL.GL_RGBA:
             case GL2GL3.GL_RGBA_INTEGER:
-            case GL2GL3.GL_BGRA:
+            case GL.GL_BGRA:
             case GL2GL3.GL_BGRA_INTEGER:
             case GL2.GL_ABGR_EXT:
               elements = 4;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java
index e5cf7d0..368cbc0 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/GLReadBufferUtil.java
@@ -53,7 +53,7 @@ public class GLReadBufferUtil {
     protected TextureData readTextureData = null;
 
     /**
-     * @param alpha true for RGBA readPixels, otherwise RGB readPixels 
+     * @param alpha true for RGBA readPixels, otherwise RGB readPixels. Disclaimer: Alpha maybe forced on ES platforms! 
      * @param write2Texture true if readPixel's TextureData shall be written to a 2d Texture
      */
     public GLReadBufferUtil(boolean alpha, boolean write2Texture) {
@@ -110,17 +110,31 @@ public class GLReadBufferUtil {
      * 
      * @see #GLReadBufferUtil(boolean, boolean)
      */
-    public void readPixels(GL gl, GLDrawable drawable, boolean flip) {
-        final int textureInternalFormat, textureDataFormat;
-        final int textureDataType = GL.GL_UNSIGNED_BYTE;
-        if(4 == components) {
-            textureInternalFormat=GL.GL_RGBA;
-            textureDataFormat=GL.GL_RGBA;
-        } else {
+    public boolean readPixels(GL gl, GLDrawable drawable, boolean flip) {
+        final int textureInternalFormat, textureDataFormat, textureDataType;
+        final int[] glImplColorReadVals = new int[] { 0, 0 };
+        
+        if(gl.isGL2GL3() && 3 == components) {
             textureInternalFormat=GL.GL_RGB;
             textureDataFormat=GL.GL_RGB;
+            textureDataType = GL.GL_UNSIGNED_BYTE;            
+        } else if(gl.isGLES2Compatible() || gl.isExtensionAvailable("GL_OES_read_format")) {
+            gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_FORMAT, glImplColorReadVals, 0);
+            gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_TYPE, glImplColorReadVals, 1);            
+            textureInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB;
+            textureDataFormat = glImplColorReadVals[0];
+            textureDataType = glImplColorReadVals[1];
+        } else {
+            // RGBA read is safe for all GL profiles 
+            textureInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB;
+            textureDataFormat=GL.GL_RGBA;
+            textureDataType = GL.GL_UNSIGNED_BYTE;
         }
-        final int readPixelSize = drawable.getWidth() * drawable.getHeight() * components ;
+        
+        final int tmp[] = new int[1];
+        final int readPixelSize = GLBuffers.sizeof(gl, tmp, textureDataFormat, textureDataType, 
+                                                   drawable.getWidth(), drawable.getHeight(), 1, true);
+        
         boolean newData = false;
         if(readPixelSize>readPixelSizeLast) {
             readPixelBuffer = Buffers.newDirectByteBuffer(readPixelSize);
@@ -144,13 +158,30 @@ public class GLReadBufferUtil {
                 readPixelSizeLast = 0;
                 throw new RuntimeException("can not fetch offscreen texture", e);
             }
+        } else {
+            readTextureData.setInternalFormat(textureInternalFormat);
+            readTextureData.setWidth(drawable.getWidth());
+            readTextureData.setHeight(drawable.getHeight());
+            readTextureData.setPixelFormat(textureDataFormat);
+            readTextureData.setPixelType(textureDataType);
         }
-        if(null!=readPixelBuffer) {
+        boolean res = null!=readPixelBuffer;
+        if(res) {
             psm.setAlignment(gl, alignment, alignment);
             readPixelBuffer.clear();
             gl.glReadPixels(0, 0, drawable.getWidth(), drawable.getHeight(), textureDataFormat, textureDataType, readPixelBuffer);
-            readPixelBuffer.rewind();
-            if(null != readTexture) {
+            readPixelBuffer.position(readPixelSize);
+            readPixelBuffer.flip();
+            final int glerr1 = gl.glGetError();
+            if(GL.GL_NO_ERROR != glerr1) {
+                System.err.println("GLReadBufferUtil.readPixels: readPixels error 0x"+Integer.toHexString(glerr1)+
+                                   " "+drawable.getWidth()+"x"+drawable.getHeight()+
+                                   ", fmt 0x"+Integer.toHexString(textureDataFormat)+", type 0x"+Integer.toHexString(textureDataType)+
+                                   ", impl-fmt 0x"+Integer.toHexString(glImplColorReadVals[0])+", impl-type 0x"+Integer.toHexString(glImplColorReadVals[1])+
+                                   ", "+readPixelBuffer+", sz "+readPixelSize);
+                res = false;                
+            }
+            if(res && null != readTexture) {
                 if(newData) {
                     readTexture.updateImage(gl, readTextureData);
                 } else {
@@ -163,6 +194,7 @@ public class GLReadBufferUtil {
             }
             psm.restore(gl);
         }
+        return res;
     }
 
     public void dispose(GL gl) {  
@@ -178,4 +210,3 @@ public class GLReadBufferUtil {
     }
 
 }
-
diff --git a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java
index 681cf7c..3b817af 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/ImmModeSink.java
@@ -6,6 +6,7 @@ import com.jogamp.opengl.util.glsl.ShaderState;
 
 import javax.media.opengl.*;
 import javax.media.opengl.fixedfunc.*;
+
 import java.nio.*;
 import java.util.Iterator;
 import java.util.ArrayList;
@@ -22,12 +23,12 @@ public class ImmModeSink {
   /**
    * Uses a GL2ES1, or ES2 fixed function emulation immediate mode sink
    */
-  public static ImmModeSink createFixed(GL gl, int glBufferUsage, int initialSize,
+  public static ImmModeSink createFixed(GL gl, int glBufferUsage, int initialElementCount,
                                         int vComps, int vDataType,
                                         int cComps, int cDataType, 
                                         int nComps, int nDataType, 
                                         int tComps, int tDataType) {
-    return new ImmModeSink(gl, glBufferUsage, initialSize, 
+    return new ImmModeSink(gl, glBufferUsage, initialElementCount, 
                            vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, false);
   }
 
@@ -40,12 +41,12 @@ public class ImmModeSink {
    * @see com.jogamp.opengl.util.glsl.ShaderState#useProgram(GL2ES2, boolean)
    * @see com.jogamp.opengl.util.glsl.ShaderState#getCurrentShaderState()
    */
-  public static ImmModeSink createGLSL(GL gl, int glBufferUsage, int initialSize,
+  public static ImmModeSink createGLSL(GL gl, int glBufferUsage, int initialElementCount,
                                        int vComps, int vDataType,
                                        int cComps, int cDataType, 
                                        int nComps, int nDataType, 
                                        int tComps, int tDataType) {
-    return new ImmModeSink(gl, glBufferUsage, initialSize, 
+    return new ImmModeSink(gl, glBufferUsage, initialElementCount, 
                            vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, true);
   }
 
@@ -69,11 +70,11 @@ public class ImmModeSink {
   }
 
   public String toString() {
-    StringBuffer sb = new StringBuffer("ImmModeSink[");
+    StringBuilder sb = new StringBuilder("ImmModeSink[");
     sb.append(",\n\tVBO list: "+vboSetList.size()+" [");
-    for(Iterator i=vboSetList.iterator(); i.hasNext() ; ) {
+    for(Iterator<VBOSet> i=vboSetList.iterator(); i.hasNext() ; ) {
         sb.append("\n\t");
-        sb.append( (VBOSet)i.next() );
+        sb.append( i.next() );
     }
     if(vboSetList.size()>0) {
         sb.append("\n\t],\nVBO current: NOP]");
@@ -91,8 +92,8 @@ public class ImmModeSink {
         e.printStackTrace();
     }
     int n=0;
-    for(Iterator i=vboSetList.iterator(); i.hasNext() ; n++) {
-        ((VBOSet)i.next()).draw(gl, null, disableBufferAfterDraw, n);
+    for(Iterator<VBOSet> i=vboSetList.iterator(); i.hasNext() ; n++) {
+        i.next().draw(gl, null, disableBufferAfterDraw, n);
     }
   }
 
@@ -102,8 +103,8 @@ public class ImmModeSink {
         e.printStackTrace();
     }
     int n=0;
-    for(Iterator i=vboSetList.iterator(); i.hasNext() ; n++) {
-        ((VBOSet)i.next()).draw(gl, indices, disableBufferAfterDraw, n);
+    for(Iterator<VBOSet> i=vboSetList.iterator(); i.hasNext() ; n++) {
+        i.next().draw(gl, indices, disableBufferAfterDraw, n);
     }
   }
 
@@ -255,7 +256,7 @@ public class ImmModeSink {
     vboSet.glTexCoord3b(x,y,z);
   }
 
-  protected ImmModeSink(GL gl, int glBufferUsage, int initialSize,
+  protected ImmModeSink(GL gl, int glBufferUsage, int initialElementCount,
                         int vComps, int vDataType,
                         int cComps, int cDataType, 
                         int nComps, int nDataType, 
@@ -263,31 +264,31 @@ public class ImmModeSink {
     if(useGLSL && !gl.hasGLSL()) {
         throw new GLException("ImmModeSink GLSL usage not supported: "+gl);
     }
-    vboSet = new  VBOSet(gl, glBufferUsage, initialSize, 
+    vboSet = new  VBOSet(gl, glBufferUsage, initialElementCount, 
                          vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, useGLSL);
-    this.vboSetList   = new ArrayList();
+    this.vboSetList   = new ArrayList<VBOSet>();
   }
 
   private void destroyList(GL gl) {
-    for(Iterator i=vboSetList.iterator(); i.hasNext() ; ) {
-        ((VBOSet)i.next()).destroy(gl);
+    for(Iterator<VBOSet> i=vboSetList.iterator(); i.hasNext() ; ) {
+        i.next().destroy(gl);
     }
     vboSetList.clear();
   }
 
   private VBOSet vboSet;
-  private ArrayList vboSetList;
+  private ArrayList<VBOSet> vboSetList;
   private static boolean vboUsage = true;
 
   protected static class VBOSet {
-    protected VBOSet (GL gl, int glBufferUsage, int initialSize,
+    protected VBOSet (GL gl, int glBufferUsage, int initialElementCount,
                       int vComps, int vDataType,
                       int cComps, int cDataType, 
                       int nComps, int nDataType, 
                       int tComps, int tDataType, boolean useGLSL) {
         this.gl=gl;
         this.glBufferUsage=glBufferUsage;
-        this.initialSize=initialSize;
+        this.initialElementCount=initialElementCount;
         this.vDataType=vDataType;
         this.vComps=vComps;
         this.cDataType=cDataType;
@@ -298,7 +299,7 @@ public class ImmModeSink {
         this.tComps=tComps;
         this.useGLSL=useGLSL;
 
-        allocateBuffer(initialSize);
+        allocateBuffer(initialElementCount);
         rewind();
 
         this.sealed=false;
@@ -310,7 +311,7 @@ public class ImmModeSink {
     }
 
     protected final VBOSet regenerate() {
-        return new VBOSet(gl, glBufferUsage, initialSize, 
+        return new VBOSet(gl, glBufferUsage, initialElementCount, 
                           vComps, vDataType, cComps, cDataType, nComps, nDataType, tComps, tDataType, useGLSL);
     }
 
@@ -341,7 +342,7 @@ public class ImmModeSink {
             if(null==indices) {
                 glf.glDrawArrays(mode, 0, count);
             } else {
-                Class clazz = indices.getClass();
+                Class<?> clazz = indices.getClass();
                 int type=-1;
                 if(ReflectionUtil.instanceOf(clazz, ByteBuffer.class.getName())) {
                     type =  GL.GL_UNSIGNED_BYTE;
@@ -713,35 +714,35 @@ public class ImmModeSink {
         }
 
         if(vComps>0) {
-           glf.glEnableClientState(glf.GL_VERTEX_ARRAY);
+           glf.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
            glf.glVertexPointer(vArrayData);
         }
         if(cComps>0) {
-           glf.glEnableClientState(glf.GL_COLOR_ARRAY);
+           glf.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
            glf.glColorPointer(cArrayData);
         }
         if(nComps>0) {
-           glf.glEnableClientState(glf.GL_NORMAL_ARRAY);
+           glf.glEnableClientState(GLPointerFunc.GL_NORMAL_ARRAY);
            glf.glNormalPointer(nArrayData);
         }
         if(tComps>0) {
-           glf.glEnableClientState(glf.GL_TEXTURE_COORD_ARRAY);
+           glf.glEnableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);
            glf.glTexCoordPointer(tArrayData);
         }
 
         gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
     } else {
         if(vComps>0) {
-           glf.glDisableClientState(glf.GL_VERTEX_ARRAY);
+           glf.glDisableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
         }
         if(cComps>0) {
-           glf.glDisableClientState(glf.GL_COLOR_ARRAY);
+           glf.glDisableClientState(GLPointerFunc.GL_COLOR_ARRAY);
         }
         if(nComps>0) {
-           glf.glDisableClientState(glf.GL_NORMAL_ARRAY);
+           glf.glDisableClientState(GLPointerFunc.GL_NORMAL_ARRAY);
         }
         if(tComps>0) {
-           glf.glDisableClientState(glf.GL_TEXTURE_COORD_ARRAY);
+           glf.glDisableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);
         }
     }
   }
@@ -810,13 +811,13 @@ public class ImmModeSink {
 
     // non public matters
 
-    protected void allocateBuffer(int elements) {
+    protected void allocateBuffer(int elementCount) {
         int vWidth = vComps * GLBuffers.sizeOfGLType(vDataType);
         int cWidth = cComps * GLBuffers.sizeOfGLType(cDataType);
         int nWidth = nComps * GLBuffers.sizeOfGLType(nDataType);
         int tWidth = tComps * GLBuffers.sizeOfGLType(tDataType);
 
-        count  = elements;
+        count  = elementCount;
         bSize  = count * ( vWidth + cWidth + nWidth + tWidth ) ;
 
         buffer = GLBuffers.newDirectByteBuffer(bSize);
@@ -890,7 +891,7 @@ public class ImmModeSink {
 
     protected final boolean growBufferIfNecessary(int type, int spare) {
         if(buffer==null || count < spare) { 
-            growBuffer(type, initialSize);
+            growBuffer(type, initialElementCount);
             return true;
         }
         return false;
@@ -901,7 +902,6 @@ public class ImmModeSink {
 
         // save olde values ..
         Buffer _vertexArray=vertexArray, _colorArray=colorArray, _normalArray=normalArray, _textCoordArray=textCoordArray;
-        ByteBuffer _buffer = buffer;
 
         allocateBuffer(count+additional);
 
@@ -951,7 +951,7 @@ public class ImmModeSink {
     }
 
     protected int mode, modeOrig;
-    protected int glBufferUsage, initialSize;
+    protected int glBufferUsage, initialElementCount;
 
     protected ByteBuffer buffer;
     protected int bSize, count, vboName;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java
index a86a2f4..fc6ef3e 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/PMVMatrix.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2009 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2011 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -33,16 +34,21 @@
 
 package com.jogamp.opengl.util;
 
-import com.jogamp.common.nio.Buffers;
-import jogamp.opengl.ProjectFloat;
-
-import java.nio.*;
+import java.nio.Buffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.media.opengl.*;
+import javax.media.opengl.GL;
+import javax.media.opengl.GLException;
 import javax.media.opengl.fixedfunc.GLMatrixFunc;
 
+import jogamp.opengl.ProjectFloat;
+
+import com.jogamp.opengl.FloatUtil;
+import com.jogamp.common.nio.Buffers;
+
 public class PMVMatrix implements GLMatrixFunc {
 
     protected final float[] matrixBufferArray;
@@ -64,13 +70,13 @@ public class PMVMatrix implements GLMatrixFunc {
      *                        In most Java implementations, direct NIO buffers have no backing array
      *                        and hence the Java computation will be throttled down by direct IO get/put 
      *                        operations.</p> 
-     *                        <p>Depending on the application, ie. weather the Java computation or
+     *                        <p>Depending on the application, ie. whether the Java computation or
      *                        JNI invocation and hence native data transfer part is heavier, 
      *                        this flag shall be set to <code>true</code> or <code>false</code></p>.
      */
     public PMVMatrix(boolean useBackingArray) {
-          projectFloat = new ProjectFloat();
-
+          this.usesBackingArray = useBackingArray;
+          
           // I    Identity
           // T    Texture
           // P    Projection
@@ -78,29 +84,30 @@ public class PMVMatrix implements GLMatrixFunc {
           // Mvi  Modelview-Inverse
           // Mvit Modelview-Inverse-Transpose
           if(useBackingArray) {
-              matrixBufferArray = new float[6*16];
+              matrixBufferArray = new float[ 6*16 + ProjectFloat.getRequiredFloatBufferSize() ];
               matrixBuffer = null;
-              // matrixBuffer = FloatBuffer.wrap(new float[12*16]);
           } else {
               matrixBufferArray = null;
-              matrixBuffer = Buffers.newDirectByteBuffer(6*16 * Buffers.SIZEOF_FLOAT);
+              matrixBuffer = Buffers.newDirectByteBuffer( ( 6*16 + ProjectFloat.getRequiredFloatBufferSize() ) * Buffers.SIZEOF_FLOAT );
               matrixBuffer.mark();
           }
           
-          matrixIdent   = slice2Float(matrixBuffer, matrixBufferArray,  0*16, 1*16);  //  I
-          matrixTex     = slice2Float(matrixBuffer, matrixBufferArray,  1*16, 1*16);  //      T
-          matrixPMvMvit = slice2Float(matrixBuffer, matrixBufferArray,  2*16, 4*16);  //          P  + Mv + Mvi + Mvit          
-          matrixPMvMvi  = slice2Float(matrixBuffer, matrixBufferArray,  2*16, 3*16);  //          P  + Mv + Mvi
-          matrixPMv     = slice2Float(matrixBuffer, matrixBufferArray,  2*16, 2*16);  //          P  + Mv
-          matrixP       = slice2Float(matrixBuffer, matrixBufferArray,  2*16, 1*16);  //          P
-          matrixMv      = slice2Float(matrixBuffer, matrixBufferArray,  3*16, 1*16);  //               Mv
-          matrixMvi     = slice2Float(matrixBuffer, matrixBufferArray,  4*16, 1*16);  //                    Mvi
-          matrixMvit    = slice2Float(matrixBuffer, matrixBufferArray,  5*16, 1*16);  //                          Mvit
+          matrixIdent   = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  0*16, 1*16);  //  I
+          matrixTex     = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  1*16, 1*16);  //      T
+          matrixPMvMvit = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  2*16, 4*16);  //          P  + Mv + Mvi + Mvit          
+          matrixPMvMvi  = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  2*16, 3*16);  //          P  + Mv + Mvi
+          matrixPMv     = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  2*16, 2*16);  //          P  + Mv
+          matrixP       = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  2*16, 1*16);  //          P
+          matrixMv      = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  3*16, 1*16);  //               Mv
+          matrixMvi     = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  4*16, 1*16);  //                    Mvi
+          matrixMvit    = Buffers.slice2Float(matrixBuffer, matrixBufferArray,  5*16, 1*16);  //                          Mvit
+          
+          projectFloat  = new ProjectFloat(matrixBuffer, matrixBufferArray, 6*16);
           
           if(null != matrixBuffer) {
               matrixBuffer.reset();
           }          
-          ProjectFloat.gluMakeIdentityf(matrixIdent);
+          FloatUtil.makeIdentityf(matrixIdent);
           
           vec3f         = new float[3];
           matrixMult    = new float[16];
@@ -109,11 +116,11 @@ public class PMVMatrix implements GLMatrixFunc {
           matrixScale   = new float[16];
           matrixOrtho   = new float[16];
           matrixFrustum = new float[16];
-          ProjectFloat.gluMakeIdentityf(matrixTrans, 0);
-          ProjectFloat.gluMakeIdentityf(matrixRot, 0);
-          ProjectFloat.gluMakeIdentityf(matrixScale, 0);
-          ProjectFloat.gluMakeIdentityf(matrixOrtho, 0);
-          ProjectFloat.gluMakeZero(matrixFrustum, 0);
+          FloatUtil.makeIdentityf(matrixTrans, 0);
+          FloatUtil.makeIdentityf(matrixRot, 0);
+          FloatUtil.makeIdentityf(matrixScale, 0);
+          FloatUtil.makeIdentityf(matrixOrtho, 0);
+          FloatUtil.makeZero(matrixFrustum, 0);
 
           matrixPStack = new ArrayList<float[]>();
           matrixMvStack= new ArrayList<float[]>();
@@ -129,6 +136,8 @@ public class PMVMatrix implements GLMatrixFunc {
           update();
     }
 
+    public final boolean usesBackingArray() { return usesBackingArray; }          
+    
     public void destroy() {
         if(null!=projectFloat) {
             projectFloat.destroy(); projectFloat=null;
@@ -161,43 +170,6 @@ public class PMVMatrix implements GLMatrixFunc {
     }
 
 
-    /**
-     * Slices a ByteBuffer to a FloatBuffer at the given position with the given size
-     * in float-space. Using a ByteBuffer as the source guarantees 
-     * keeping the source native order programmatically.  
-     * This works around <a href="http://code.google.com/p/android/issues/detail?id=16434">Honeycomb / Android 3.0 Issue 16434</a>. 
-     * This bug is resolved at least in Android 3.2.
-     * 
-     * @param buf source ByteBuffer
-     * @param backing source float array
-     * @param posFloat {@link Buffers#SIZEOF_FLOAT} position
-     * @param lenFloat {@link Buffers#SIZEOF_FLOAT} size 
-     * @return FloatBuffer w/ native byte order as given ByteBuffer
-     */
-    private static FloatBuffer slice2Float(Buffer buf, float[] backing, int posFloat, int lenFloat) {
-        if(buf instanceof ByteBuffer) {
-            ByteBuffer bb = (ByteBuffer) buf;
-            bb.position( posFloat * Buffers.SIZEOF_FLOAT );
-            bb.limit( (posFloat + lenFloat) * Buffers.SIZEOF_FLOAT );
-            FloatBuffer fb = bb.slice().order(bb.order()).asFloatBuffer(); // slice and duplicate may change byte order
-            fb.mark();
-            return fb;
-        } else if(null != backing) {
-            FloatBuffer fb  = FloatBuffer.wrap(backing, posFloat, lenFloat);
-            fb.mark();
-            return fb;
-        } else if(buf instanceof FloatBuffer) {
-            FloatBuffer fb = (FloatBuffer) buf;
-            fb.position( posFloat );
-            fb.limit( posFloat + lenFloat );
-            FloatBuffer fb0 = fb.slice(); // slice and duplicate may change byte order
-            fb0.mark();
-            return fb0;
-        } else {
-            throw new InternalError("XXX");
-        }
-    }
-
     public static final boolean isMatrixModeName(final int matrixModeName) {
         switch(matrixModeName) {
             case GL_MODELVIEW_MATRIX:
@@ -356,38 +328,6 @@ public class PMVMatrix implements GLMatrixFunc {
         }
     }
 
-    public final void gluPerspective(final float fovy, final float aspect, final float zNear, final float zFar) {
-      float top=(float)Math.tan(fovy*((float)Math.PI)/360.0f)*zNear;
-      float bottom=-1.0f*top;
-      float left=aspect*bottom;
-      float right=aspect*top;
-      glFrustumf(left, right, bottom, top, zNear, zFar);
-    }
-
-    public static final void glMultMatrixf(final FloatBuffer a, final FloatBuffer b, FloatBuffer d) {
-       final int aP = a.position(); 
-       final int bP = b.position();
-       final int dP = d.position();
-       for (int i = 0; i < 4; i++) {
-          final float ai0=a.get(aP+i+0*4),  ai1=a.get(aP+i+1*4),  ai2=a.get(aP+i+2*4),  ai3=a.get(aP+i+3*4);
-          d.put(dP+i+0*4 , ai0 * b.get(bP+0+0*4) + ai1 * b.get(bP+1+0*4) + ai2 * b.get(bP+2+0*4) + ai3 * b.get(bP+3+0*4) );
-          d.put(dP+i+1*4 , ai0 * b.get(bP+0+1*4) + ai1 * b.get(bP+1+1*4) + ai2 * b.get(bP+2+1*4) + ai3 * b.get(bP+3+1*4) );
-          d.put(dP+i+2*4 , ai0 * b.get(bP+0+2*4) + ai1 * b.get(bP+1+2*4) + ai2 * b.get(bP+2+2*4) + ai3 * b.get(bP+3+2*4) );
-          d.put(dP+i+3*4 , ai0 * b.get(bP+0+3*4) + ai1 * b.get(bP+1+3*4) + ai2 * b.get(bP+2+3*4) + ai3 * b.get(bP+3+3*4) );
-       }
-    }
-    public static final void glMultMatrixf(final FloatBuffer a, final float[] b, int b_off, FloatBuffer d) {
-       final int aP = a.position(); 
-       final int dP = d.position();
-       for (int i = 0; i < 4; i++) {
-          final float ai0=a.get(aP+i+0*4),  ai1=a.get(aP+i+1*4),  ai2=a.get(aP+i+2*4),  ai3=a.get(aP+i+3*4);
-          d.put(dP+i+0*4 , ai0 * b[b_off+0+0*4] + ai1 * b[b_off+1+0*4] + ai2 * b[b_off+2+0*4] + ai3 * b[b_off+3+0*4] );
-          d.put(dP+i+1*4 , ai0 * b[b_off+0+1*4] + ai1 * b[b_off+1+1*4] + ai2 * b[b_off+2+1*4] + ai3 * b[b_off+3+1*4] );
-          d.put(dP+i+2*4 , ai0 * b[b_off+0+2*4] + ai1 * b[b_off+1+2*4] + ai2 * b[b_off+2+2*4] + ai3 * b[b_off+3+2*4] );
-          d.put(dP+i+3*4 , ai0 * b[b_off+0+3*4] + ai1 * b[b_off+1+3*4] + ai2 * b[b_off+2+3*4] + ai3 * b[b_off+3+3*4] );
-       }
-    }
-
     // 
     // MatrixIf
     //
@@ -524,26 +464,26 @@ public class PMVMatrix implements GLMatrixFunc {
 
     public final void glMultMatrixf(final FloatBuffer m) {
         if(matrixMode==GL_MODELVIEW) {
-            glMultMatrixf(matrixMv, m, matrixMv);
+            FloatUtil.multMatrixf(matrixMv, m, matrixMv);
             modified |= DIRTY_MODELVIEW ;
         } else if(matrixMode==GL_PROJECTION) {
-            glMultMatrixf(matrixP, m, matrixP);
+            FloatUtil.multMatrixf(matrixP, m, matrixP);
             modified |= DIRTY_PROJECTION ;
         } else if(matrixMode==GL.GL_TEXTURE) {
-            glMultMatrixf(matrixTex, m, matrixTex);
+            FloatUtil.multMatrixf(matrixTex, m, matrixTex);
             modified |= DIRTY_TEXTURE ;
         } 
     }
 
     public void glMultMatrixf(float[] m, int m_offset) {
         if(matrixMode==GL_MODELVIEW) {
-            glMultMatrixf(matrixMv, m, m_offset, matrixMv);
+            FloatUtil.multMatrixf(matrixMv, m, m_offset, matrixMv);
             modified |= DIRTY_MODELVIEW ;
         } else if(matrixMode==GL_PROJECTION) {
-            glMultMatrixf(matrixP, m, m_offset, matrixP);
+            FloatUtil.multMatrixf(matrixP, m, m_offset, matrixP);
             modified |= DIRTY_PROJECTION ;
         } else if(matrixMode==GL.GL_TEXTURE) {
-            glMultMatrixf(matrixTex, m, m_offset, matrixTex);
+            FloatUtil.multMatrixf(matrixTex, m, m_offset, matrixTex);
             modified |= DIRTY_TEXTURE ;
         } 
     }
@@ -567,13 +507,13 @@ public class PMVMatrix implements GLMatrixFunc {
         final float s = (float)Math.sin(angrad);
 
         vec3f[0]=x; vec3f[1]=y; vec3f[2]=z;
-        ProjectFloat.normalize(vec3f);
+        FloatUtil.normalize(vec3f);
         x = vec3f[0]; y = vec3f[1]; z = vec3f[2];
 
         // Rotation matrix:
-        //      xx(1−c)+c  xy(1−c)+zs xz(1−c)-ys 0
-        //      xy(1−c)-zs yy(1−c)+c  yz(1−c)+xs 0
-        //      xz(1−c)+ys yz(1−c)-xs zz(1−c)+c  0
+        //      xx(1-c)+c  xy(1-c)+zs xz(1-c)-ys 0
+        //      xy(1-c)-zs yy(1-c)+c  yz(1-c)+xs 0
+        //      xz(1-c)+ys yz(1-c)-xs zz(1-c)+c  0
         //      0          0          0          1
         final float xy = x*y;
         final float xz = x*z;
@@ -632,6 +572,14 @@ public class PMVMatrix implements GLMatrixFunc {
         glMultMatrixf(matrixOrtho, 0);
     }
 
+    public final void gluPerspective(final float fovy, final float aspect, final float zNear, final float zFar) {
+      float top=(float)Math.tan(fovy*((float)Math.PI)/360.0f)*zNear;
+      float bottom=-1.0f*top;
+      float left=aspect*bottom;
+      float right=aspect*top;
+      glFrustumf(left, right, bottom, top, zNear, zFar);
+    }
+
     public final void glFrustumf(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar) {
         if(zNear<=0.0f||zFar<0.0f) {
             throw new GLException("GL_INVALID_VALUE: zNear and zFar must be positive, and zNear>0");
@@ -643,7 +591,7 @@ public class PMVMatrix implements GLMatrixFunc {
         //  2*zNear/dx   0          A  0
         //  0            2*zNear/dy B  0
         //  0            0          C  D
-        //  0            0         −1  0
+        //  0            0         -1  0
         final float zNear2 = 2.0f*zNear;
         final float dx=right-left;
         final float dy=top-bottom;
@@ -666,6 +614,78 @@ public class PMVMatrix implements GLMatrixFunc {
         glMultMatrixf(matrixFrustum, 0);
     }
 
+    public void gluLookAt(float eyex, float eyey, float eyez,
+                          float centerx, float centery, float centerz,
+                          float upx, float upy, float upz) {
+        projectFloat.gluLookAt(this, eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz);
+    }
+
+    /**
+     * Uses this instance {@link #glGetMvMatrixf()} and {@link #glGetPMatrixf()}
+     * 
+     * @param objx
+     * @param objy
+     * @param objz
+     * @param viewport
+     * @param viewport_offset
+     * @param win_pos
+     * @param win_pos_offset
+     * @return
+     */
+    public boolean gluProject(float objx, float objy, float objz,
+                            int[] viewport, int viewport_offset,
+                            float[] win_pos, int win_pos_offset ) {
+        if(usesBackingArray) {
+            return projectFloat.gluProject(objx, objy, objz,
+                                           matrixMv.array(), 0,
+                                           matrixP.array(), 0,
+                                           viewport, viewport_offset, 
+                                           win_pos, win_pos_offset);
+        } else {
+            return projectFloat.gluProject(objx, objy, objz,
+                                           matrixMv,
+                                           matrixP,
+                                           viewport, viewport_offset, 
+                                           win_pos, win_pos_offset);
+        }
+    }
+
+    /**
+     * Uses this instance {@link #glGetMvMatrixf()} and {@link #glGetPMatrixf()}
+     * 
+     * @param winx
+     * @param winy
+     * @param winz
+     * @param viewport
+     * @param viewport_offset
+     * @param obj_pos
+     * @param obj_pos_offset
+     * @return
+     */
+    public boolean gluUnProject(float winx, float winy, float winz,
+                              int[] viewport, int viewport_offset,
+                              float[] obj_pos, int obj_pos_offset) {
+        if(usesBackingArray) {
+            return projectFloat.gluUnProject(winx, winy, winz,
+                                             matrixMv.array(), 0,
+                                             matrixP.array(), 0,
+                                             viewport, viewport_offset, 
+                                             obj_pos, obj_pos_offset);
+        } else {
+            return projectFloat.gluUnProject(winx, winy, winz,
+                                             matrixMv,
+                                             matrixP,
+                                             viewport, viewport_offset, 
+                                             obj_pos, obj_pos_offset);
+        }        
+    }
+    
+    public void gluPickMatrix(float x, float y,
+                              float deltaX, float deltaY,
+                              int[] viewport, int viewport_offset) {
+        projectFloat.gluPickMatrix(this, x, y, deltaX, deltaY, viewport, viewport_offset);
+    }
+    
     //
     // private 
     //
@@ -718,6 +738,7 @@ public class PMVMatrix implements GLMatrixFunc {
         }        
     }
 
+    protected final boolean usesBackingArray;
     protected Buffer matrixBuffer;
     protected FloatBuffer matrixIdent, matrixPMvMvit, matrixPMvMvi, matrixPMv, matrixP, matrixTex, matrixMv, matrixMvi, matrixMvit;
     protected float[] matrixMult, matrixTrans, matrixRot, matrixScale, matrixOrtho, matrixFrustum, vec3f;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java
new file mode 100644
index 0000000..3eca019
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayer.java
@@ -0,0 +1,248 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.util.av;
+
+import java.io.IOException;
+import java.net.URLConnection;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GLException;
+
+import jogamp.opengl.Debug;
+
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+/**
+ * Lifecycle of an GLMediaPlayer:
+ * <table border="1">
+ *   <tr><th>action</th>                                   <th>state before</th>        <th>state after</th></tr>
+ *   <tr><td>{@link #initGLStream(GL, URLConnection)}</td> <td>Uninitialized</td>       <td>Stopped</td></tr>
+ *   <tr><td>{@link #start()}</td>                         <td>Stopped, Paused</td>     <td>Playing</td></tr>
+ *   <tr><td>{@link #stop()}</td>                          <td>Playing, Paused</td>     <td>Stopped</td></tr>
+ *   <tr><td>{@link #pause()}</td>                         <td>Playing</td>             <td>Paused</td></tr>
+ *   <tr><td>{@link #destroy(GL)}</td>                     <td>ANY</td>                 <td>Uninitialized</td></tr>
+ * </table>
+ * <p>
+ * Current implementations (check each API doc link for details):
+ * <ul>
+ *   <li>{@link jogamp.opengl.util.av.NullGLMediaPlayer}</li>
+ *   <li>{@link jogamp.opengl.util.av.impl.OMXGLMediaPlayer}</li>
+ *   <li>{@link jogamp.opengl.util.av.impl.FFMPEGMediaPlayer}</li>
+ *   <li>{@link jogamp.opengl.android.av.AndroidGLMediaPlayerAPI14}</li> 
+ * </ul>
+ * </p>
+ * <p>
+ * Variable type, value range and dimension has been chosen to suit embedded CPUs
+ * and characteristics of audio and video streaming.
+ * Milliseconds of type integer with a maximum value of {@link Integer#MAX_VALUE} 
+ * will allow tracking time up 2,147,483.647 seconds or
+ * 24 days 20 hours 31 minutes and 23 seconds.
+ * Milliseconds granularity is also more than enough to deal with A-V synchronization,
+ * where the threshold usually lies within 100ms. 
+ * </p>
+ */
+public interface GLMediaPlayer extends TextureSequence {
+    public static final boolean DEBUG = Debug.debug("GLMediaPlayer");
+        
+    public interface GLMediaEventListener extends TexSeqEventListener<GLMediaPlayer> {
+    
+        static final int EVENT_CHANGE_SIZE   = 1<<0;
+        static final int EVENT_CHANGE_FPS    = 1<<1;
+        static final int EVENT_CHANGE_BPS    = 1<<2;
+        static final int EVENT_CHANGE_LENGTH = 1<<3;
+        static final int EVENT_CHANGE_CODEC  = 1<<3;
+    
+        /**
+         * @param mp the event source 
+         * @param event_mask the changes attributes
+         * @param when system time in msec. 
+         */
+        public void attributesChanges(GLMediaPlayer mp, int event_mask, long when);    
+    }
+    
+    public enum State {
+        Uninitialized(0), Stopped(1), Playing(2), Paused(3); 
+        
+        public final int id;
+
+        State(int id){
+            this.id = id;
+        }
+    }
+    
+    public int getTextureCount();
+    
+    /** Defaults to 0 */
+    public void setTextureUnit(int u);
+    /** Sets the texture min-mag filter, defaults to {@link GL#GL_NEAREST}. */
+    public void setTextureMinMagFilter(int[] minMagFilter);
+    /** Sets the texture min-mag filter, defaults to {@link GL#GL_CLAMP_TO_EDGE}. */
+    public void setTextureWrapST(int[] wrapST);
+    
+    /** 
+     * Sets the stream to be used. Initializes all stream related states inclusive OpenGL ones,
+     * if <code>gl</code> is not null.
+     * <p>
+     * Uninitialized -> Stopped
+     * </p>
+     * @param gl current GL object. If null, no video output and textures will be available.
+     * @param urlConn the stream connection
+     * @return the new state
+     * 
+     * @throws IllegalStateException if not invoked in state Uninitialized 
+     * @throws IOException in case of difficulties to open or process the stream
+     * @throws GLException in case of difficulties to initialize the GL resources
+     */
+    public State initGLStream(GL gl, URLConnection urlConn) throws IllegalStateException, GLException, IOException;
+    
+    /**
+     * Releases the GL and stream resources.
+     * <p>
+     * <code>ANY</code> -> Uninitialized
+     * </p>
+     */
+    public State destroy(GL gl);
+
+    public void setPlaySpeed(float rate);
+
+    public float getPlaySpeed();
+
+    /**
+     * Stopped/Paused -> Playing
+     */
+    public State start();
+
+    /**
+     * Playing -> Paused
+     */
+    public State pause();
+
+    /**
+     * Playing/Paused -> Stopped
+     */
+    public State stop();
+    
+    /**
+     * @return the current state, either Uninitialized, Stopped, Playing, Paused
+     */
+    public State getState();
+    
+    /**
+     * @return time current position in milliseconds 
+     **/
+    public int getCurrentPosition();
+
+    /**
+     * Allowed in state Stopped, Playing and Paused, otherwise ignored.
+     * 
+     * @param msec absolute desired time position in milliseconds 
+     * @return time current position in milliseconds, after seeking to the desired position  
+     **/
+    public int seek(int msec);
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public TextureSequence.TextureFrame getLastTexture() throws IllegalStateException;
+
+    /**
+     * {@inheritDoc}
+     * 
+     * <p>
+     * In case the current state is not {@link State#Playing}, {@link #getLastTexture()} is returned.
+     * </p>
+     * 
+     * @see #addEventListener(GLMediaEventListener)
+     * @see GLMediaEventListener#newFrameAvailable(GLMediaPlayer, long)
+     */
+    @Override
+    public TextureSequence.TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException;
+    
+    public URLConnection getURLConnection();
+
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the code of the video stream, if available 
+     */
+    public String getVideoCodec();
+
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the code of the audio stream, if available 
+     */
+    public String getAudioCodec();
+
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the total number of video frames
+     */
+    public long getTotalFrames();
+
+    /**
+     * @return total duration of stream in msec.
+     */
+    public int getDuration();
+    
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the overall bitrate of the stream.  
+     */
+    public long getStreamBitrate();
+
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return video bitrate  
+     */
+    public int getVideoBitrate();
+    
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the audio bitrate  
+     */
+    public int getAudioBitrate();
+    
+    /**
+     * <i>Warning:</i> Optional information, may not be supported by implementation.
+     * @return the framerate of the video
+     */
+    public float getFramerate();
+
+    public int getWidth();
+
+    public int getHeight();
+
+    public String toString();
+
+    public void addEventListener(GLMediaEventListener l);
+
+    public void removeEventListener(GLMediaEventListener l);
+
+    public GLMediaEventListener[] getEventListeners();    
+
+}
diff --git a/src/newt/classes/jogamp/newt/driver/android/MD.java b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java
similarity index 53%
copy from src/newt/classes/jogamp/newt/driver/android/MD.java
copy to src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java
index 06f7872..6fcf20e 100644
--- a/src/newt/classes/jogamp/newt/driver/android/MD.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/av/GLMediaPlayerFactory.java
@@ -1,5 +1,5 @@
 /**
- * Copyright 2011 JogAmp Community. All rights reserved.
+ * Copyright 2012 JogAmp Community. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without modification, are
  * permitted provided that the following conditions are met:
@@ -25,41 +25,31 @@
  * authors and should not be interpreted as representing official policies, either expressed
  * or implied, of JogAmp Community.
  */
-package jogamp.newt.driver.android;
+package com.jogamp.opengl.util.av;
 
-import java.util.List;
+import jogamp.opengl.util.av.NullGLMediaPlayer;
 
-import javax.media.opengl.GLDrawableFactory;
-import javax.media.opengl.GLProfile;
-
-import com.jogamp.common.GlueGenVersion;
+import com.jogamp.common.os.AndroidVersion;
 import com.jogamp.common.os.Platform;
-import com.jogamp.common.util.VersionUtil;
-import com.jogamp.opengl.JoglVersion;
+import com.jogamp.common.util.ReflectionUtil;
 
-public class MD {
-   public static final String TAG = "JogAmp.NEWT";
-   
-   public static String getInfo() { 
-       
-        StringBuffer sb = new StringBuffer();
-        
-        sb.append(VersionUtil.getPlatformInfo()).append(Platform.NEWLINE)
-              .append(GlueGenVersion.getInstance()).append(Platform.NEWLINE)
-              .append(JoglVersion.getInstance()).append(Platform.NEWLINE)
-              .append(Platform.NEWLINE);
-              
-        final GLDrawableFactory factory = GLDrawableFactory.getEGLFactory();
-        final List/*<GLCapabilitiesImmutable>*/ availCaps = factory.getAvailableCapabilities(null);
-        for(int i=0; i<availCaps.size(); i++) {
-            sb.append(availCaps.get(i)).append(Platform.NEWLINE);
+public class GLMediaPlayerFactory {
+    private static final String AndroidGLMediaPlayerAPI14ClazzName = "jogamp.opengl.android.av.AndroidGLMediaPlayerAPI14";
+    private static final String FFMPEGMediaPlayerClazzName = "jogamp.opengl.util.av.impl.FFMPEGMediaPlayer";
+    private static final String isAvailableMethodName = "isAvailable";
+    
+    public static GLMediaPlayer create() {
+        final ClassLoader cl = GLMediaPlayerFactory.class.getClassLoader();
+        if(Platform.OS_TYPE.equals(Platform.OSType.ANDROID)) {
+            if(AndroidVersion.SDK_INT >= 14) {
+                if(((Boolean)ReflectionUtil.callStaticMethod(AndroidGLMediaPlayerAPI14ClazzName, isAvailableMethodName, null, null, cl)).booleanValue()) {
+                    return (GLMediaPlayer) ReflectionUtil.createInstance(AndroidGLMediaPlayerAPI14ClazzName, cl);
+                }
+            }
+        }
+        if(((Boolean)ReflectionUtil.callStaticMethod(FFMPEGMediaPlayerClazzName, isAvailableMethodName, null, null, cl)).booleanValue()) {
+            return (GLMediaPlayer) ReflectionUtil.createInstance(FFMPEGMediaPlayerClazzName, cl);
         }
-       
-       return sb.toString();       
-   }
-   
-    public static void main(String args[]) {
-        
-        System.err.println(getInfo());
+        return new NullGLMediaPlayer();
     }
 }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/av/package.html b/src/jogl/classes/com/jogamp/opengl/util/av/package.html
new file mode 100644
index 0000000..249db7d
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/util/av/package.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>Public Audio/Video Utility Package</title>
+</head>
+  <body>
+   
+<h2>Public <i>Audio/Video</i> Utility Package</h2>
+   
+<h3>Disclaimer</h3>
+  <p>
+  We are currently refining and completing this new API and it's implementation.
+  Feel free to comment and help using our public channels.
+  </p>
+<h3>Revision History<br>
+  </h3>
+   
+<ul>
+<li> Early Draft Review, April 17th 2012</li>
+</ul>
+  <br>
+  <br>
+ <br>
+</body>
+</html>
diff --git a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java
index de28dc7..622ee1b 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/awt/TextRenderer.java
@@ -40,7 +40,7 @@
 package com.jogamp.opengl.util.awt;
 
 import com.jogamp.common.nio.Buffers;
-import jogamp.opengl.Debug;
+
 import com.jogamp.opengl.util.*;
 import com.jogamp.opengl.util.packrect.*;
 import com.jogamp.opengl.util.texture.*;
@@ -66,12 +66,12 @@ import java.text.*;
 
 import java.util.*;
 
-import java.security.*;
-
 import javax.media.opengl.*;
 import javax.media.opengl.glu.*;
 import javax.media.opengl.awt.*;
 
+import jogamp.opengl.Debug;
+
 
 /** Renders bitmapped Java 2D text into an OpenGL window with high
     performance, full Unicode support, and a simple API. Performs
@@ -127,7 +127,7 @@ import javax.media.opengl.awt.*;
     @author Kenneth Russell
 */
 public class TextRenderer {
-    private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.TextRenderer", true, AccessController.getContext());
+    private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.TextRenderer", true); 
 
     // These are occasionally useful for more in-depth debugging
     private static final boolean DISABLE_GLYPH_CACHE = false;
@@ -1603,7 +1603,7 @@ public class TextRenderer {
                 } else {
                     // Assemble a run of characters that don't fit in
                     // the cache
-                    StringBuffer buf = new StringBuffer();
+                    StringBuilder buf = new StringBuilder();
                     while (i < lengthInGlyphs &&
                            getGlyph(inString, fullRunGlyphVector.getGlyphMetrics(i), i) == null) {
                         buf.append(inString.charAt(i++));
diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java
index cc75b89..f6b686d 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderCode.java
@@ -28,30 +28,70 @@
 
 package com.jogamp.opengl.util.glsl;
 
-import com.jogamp.common.nio.Buffers;
-import com.jogamp.common.util.IOUtil;
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.io.StringReader;
+import java.net.URLConnection;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.IntBuffer;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLES2;
+import javax.media.opengl.GLException;
 
-import javax.media.opengl.*;
 import jogamp.opengl.Debug;
 
-import java.util.*;
-import java.nio.*;
-import java.io.*;
-import java.net.*;
-import java.security.*;
+import com.jogamp.common.nio.Buffers;
+import com.jogamp.common.util.IOUtil;
 
+/**
+ * Convenient shader code class to use and instantiate vertex or fragment programs.
+ * <p>
+ * A documented example of how to use this code is available
+ * {@link #create(GL2ES2, int, Class, String, String, String, boolean) here} and
+ * {@link #create(GL2ES2, int, int, Class, String, String[], String, String) here}.
+ * </p>  
+ */
 public class ShaderCode {
     public static final boolean DEBUG = Debug.debug("GLSLCode");
-    public static final boolean DEBUG_CODE = Debug.isPropertyDefined("jogl.debug.GLSLCode", true, AccessController.getContext());
+    public static final boolean DEBUG_CODE = Debug.isPropertyDefined("jogl.debug.GLSLCode", true);
 
+    /** Unique resource suffix for {@link GL2ES2#GL_VERTEX_SHADER} in source code: <code>vp</code> */
     public static final String SUFFIX_VERTEX_SOURCE   =  "vp" ;
+    
+    /** Unique resource suffix for {@link GL2ES2#GL_VERTEX_SHADER} in binary: <code>bvp</code> */
     public static final String SUFFIX_VERTEX_BINARY   = "bvp" ;
+    
+    /** Unique resource suffix for {@link GL2ES2#GL_FRAGMENT_SHADER} in source code: <code>fp</code> */
     public static final String SUFFIX_FRAGMENT_SOURCE =  "fp" ;
+    
+    /** Unique resource suffix for {@link GL2ES2#GL_FRAGMENT_SHADER} in binary: <code>bfp</code> */
     public static final String SUFFIX_FRAGMENT_BINARY = "bfp" ;
     
+    /** Unique relative path for binary shader resources for {@link GLES2#GL_NVIDIA_PLATFORM_BINARY_NV NVIDIA}: <code>nvidia</code> */
     public static final String SUB_PATH_NVIDIA = "nvidia" ;
 
-    public ShaderCode(int type, int number, String[][] source) {
+    /**
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param count number of shaders
+     * @param source CharSequence array containing the shader sources, organized as <code>source[count][strings-per-shader]</code>.
+     *               May be either an immutable <code>String</code> - or mutable <code>StringBuilder</code> array.
+     * 
+     * @throws IllegalArgumentException if <code>count</count> and <code>source.length</code> do not match
+     */
+    public ShaderCode(int type, int count, CharSequence[][] source) {
+        if(source.length != count) {
+            throw new IllegalArgumentException("shader number ("+count+") and sourceFiles array ("+source.length+") of different lenght.");
+        }
         switch (type) {
             case GL2ES2.GL_VERTEX_SHADER:
             case GL2ES2.GL_FRAGMENT_SHADER:
@@ -63,7 +103,7 @@ public class ShaderCode {
         shaderBinaryFormat = -1;
         shaderBinary = null;
         shaderType   = type;
-        shader = Buffers.newDirectIntBuffer(number);
+        shader = Buffers.newDirectIntBuffer(count);
         id = getNextID();
 
         if(DEBUG_CODE) {
@@ -72,7 +112,12 @@ public class ShaderCode {
         }
     }
 
-    public ShaderCode(int type, int number, int binFormat, Buffer binary) {
+    /**
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param count number of shaders
+     * @param binary binary buffer containing the shader binaries, 
+     */
+    public ShaderCode(int type, int count, int binFormat, Buffer binary) {
         switch (type) {
             case GL2ES2.GL_VERTEX_SHADER:
             case GL2ES2.GL_FRAGMENT_SHADER:
@@ -84,18 +129,44 @@ public class ShaderCode {
         shaderBinaryFormat = binFormat;
         shaderBinary = binary;
         shaderType   = type;
-        shader = Buffers.newDirectIntBuffer(number);
+        shader = Buffers.newDirectIntBuffer(count);
         id = getNextID();
     }
 
-    public static ShaderCode create(GL2ES2 gl, int type, int number, Class<?> context, String[] sourceFiles) {
-        if(!ShaderUtil.isShaderCompilerAvailable(gl)) return null;
+    /**
+     * Creates a complete {@link ShaderCode} object while reading all shader source of <code>sourceFiles</code>,
+     * which location is resolved using the <code>context</code> class, see {@link #readShaderSource(Class, String)}.
+     * 
+     * @param gl current GL object to determine whether a shader compiler is available. If null, no validation is performed.
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param count number of shaders
+     * @param context class used to help resolving the source location
+     * @param sourceFiles array of source locations, organized as <code>sourceFiles[count]</code>
+     * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance
+     *                        which can be edited later on at the costs of a String conversion when passing to 
+     *                        {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}.
+     *                        If <code>false</code> method returns an immutable <code>String</code> instance,
+     *                        which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}
+     *                        at no additional costs.
+     * 
+     * @throws IllegalArgumentException if <code>count</count> and <code>sourceFiles.length</code> do not match
+     * @see #readShaderSource(Class, String)
+     */
+    public static ShaderCode create(GL2ES2 gl, int type, int count, Class<?> context, String[] sourceFiles, boolean mutableStringBuilder) {
+        if(null != gl && !ShaderUtil.isShaderCompilerAvailable(gl)) {
+            return null;
+        }
 
-        String[][] shaderSources = null;
+        CharSequence[][] shaderSources = null;
         if(null!=sourceFiles) {
-            shaderSources = new String[sourceFiles.length][1];
-            for(int i=0; null!=shaderSources && i<sourceFiles.length; i++) {
-                shaderSources[i][0] = readShaderSource(context, sourceFiles[i]);
+            // sourceFiles.length and count is validated in ctor
+            shaderSources = new CharSequence[sourceFiles.length][1];
+            for(int i=0; i<sourceFiles.length; i++) {
+                try {
+                    shaderSources[i][0] = readShaderSource(context, sourceFiles[i], mutableStringBuilder);
+                } catch (IOException ioe) {
+                    throw new RuntimeException("readShaderSource("+sourceFiles[i]+") error: ", ioe);
+                }
                 if(null == shaderSources[i][0]) {
                     shaderSources = null;
                 }
@@ -104,13 +175,30 @@ public class ShaderCode {
         if(null==shaderSources) {
             return null;
         }
-        return new ShaderCode(type, number, shaderSources);
+        return new ShaderCode(type, count, shaderSources);
     }
 
-    public static ShaderCode create(int type, int number, Class<?> context, int binFormat, String binaryFile) {
+    /**
+     * Creates a complete {@link ShaderCode} object while reading the shader binary of <code>binaryFile</code>,
+     * which location is resolved using the <code>context</code> class, see {@link #readShaderBinary(Class, String)}.
+     * 
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param count number of shaders
+     * @param context class used to help resolving the source location
+     * @param binFormat a valid native binary format as they can be queried by {@link ShaderUtil#getShaderBinaryFormats(GL)}.
+     * @param sourceFiles array of source locations, organized as <code>sourceFiles[count]</code>
+     * 
+     * @see #readShaderBinary(Class, String)
+     * @see ShaderUtil#getShaderBinaryFormats(GL)
+     */    
+    public static ShaderCode create(int type, int count, Class<?> context, int binFormat, String binaryFile) {
         ByteBuffer shaderBinary = null;
         if(null!=binaryFile && 0<=binFormat) {
-            shaderBinary = readShaderBinary(context, binaryFile);
+            try {
+                shaderBinary = readShaderBinary(context, binaryFile);
+            } catch (IOException ioe) {
+                throw new RuntimeException("readShaderBinary("+binaryFile+") error: ", ioe);
+            }
             if(null == shaderBinary) {
                 binFormat = -1;
             }
@@ -118,9 +206,26 @@ public class ShaderCode {
         if(null==shaderBinary) {
             return null;
         }
-        return new ShaderCode(type, number, binFormat, shaderBinary);
+        return new ShaderCode(type, count, binFormat, shaderBinary);
     }
 
+    /**
+     * Returns a unique suffix for shader resources as follows:
+     * <ul>
+     *   <li>Source<ul>
+     *     <li>{@link GL2ES2#GL_VERTEX_SHADER vertex}: {@link #SUFFIX_VERTEX_SOURCE}</li>
+     *     <li>{@link GL2ES2#GL_FRAGMENT_SHADER fragment}: {@link #SUFFIX_FRAGMENT_SOURCE}</li></ul></li>
+     *   <li>Binary<ul>
+     *     <li>{@link GL2ES2#GL_VERTEX_SHADER vertex}: {@link #SUFFIX_VERTEX_BINARY}</li>
+     *     <li>{@link GL2ES2#GL_FRAGMENT_SHADER fragment}: {@link #SUFFIX_FRAGMENT_BINARY}</li></ul></li>
+     * </ul> 
+     * @param binary true for a binary resource, false for a source resource 
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * 
+     * @throws GLException if <code>type</code> is not supported
+     * 
+     * @see #create(GL2ES2, int, Class, String, String, String, boolean)
+     */
     public static String getFileSuffix(boolean binary, int type) {
         switch (type) {
             case GL2ES2.GL_VERTEX_SHADER:
@@ -132,6 +237,16 @@ public class ShaderCode {
         }
     }
 
+    /** 
+     * Returns a unique relative path for binary shader resources as follows:
+     * <ul>
+     *   <li>{@link GLES2#GL_NVIDIA_PLATFORM_BINARY_NV NVIDIA}: {@link #SUB_PATH_NVIDIA}</li>
+     * </ul>
+     * 
+     * @throws GLException if <code>binFormat</code> is not supported
+     * 
+     * @see #create(GL2ES2, int, Class, String, String, String, boolean)
+     */    
     public static String getBinarySubPath(int binFormat) {
         switch (binFormat) {
             case GLES2.GL_NVIDIA_PLATFORM_BINARY_NV:
@@ -141,39 +256,183 @@ public class ShaderCode {
         }
     }
 
-    public static ShaderCode create(GL2ES2 gl, int type, int number, Class<?> context, 
-                                    String srcRoot, String binRoot, String basename) {
+    /**
+     * Convenient creation method for instantiating a complete {@link ShaderCode} object 
+     * either from source code using {@link #create(GL2ES2, int, int, Class, String[])}, 
+     * or from a binary code using {@link #create(int, int, Class, int, String)},
+     * whatever is available first.
+     * <p>
+     * The source and binary location names are expected w/o suffixes which are 
+     * resolved and appended using {@link #getFileSuffix(boolean, int)}.
+     * </p>
+     * <p>
+     * Additionally, the binary resource is expected within a subfolder of <code>binRoot</code>
+     * which reflects the vendor specific binary format, see {@link #getBinarySubPath(int)}.
+     * All {@link ShaderUtil#getShaderBinaryFormats(GL)} are being iterated
+     * using the binary subfolder, the first existing resource is being used. 
+     * </p>
+     * 
+     * Example:
+     * <pre>
+     *   Your std JVM layout (plain or within a JAR):
+     *   
+     *      org/test/glsl/MyShaderTest.class
+     *      org/test/glsl/shader/vertex.vp
+     *      org/test/glsl/shader/fragment.fp
+     *      org/test/glsl/shader/bin/nvidia/vertex.bvp
+     *      org/test/glsl/shader/bin/nvidia/fragment.bfp
+     *      
+     *   Your Android APK layout:
+     *   
+     *      classes.dex
+     *      assets/org/test/glsl/shader/vertex.vp
+     *      assets/org/test/glsl/shader/fragment.fp
+     *      assets/org/test/glsl/shader/bin/nvidia/vertex.bvp
+     *      assets/org/test/glsl/shader/bin/nvidia/fragment.bfp
+     *      ...
+     *   
+     *   Your invocation in org/test/glsl/MyShaderTest.java:
+     *   
+     *      ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(),
+     *                                         "shader", new String[] { "vertex" }, "shader/bin", "vertex");
+     *      ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(),
+     *                                         "shader", new String[] { "vertex" }, "shader/bin", "fragment");
+     *      ShaderProgram sp0 = new ShaderProgram();
+     *      sp0.add(gl, vp0, System.err);
+     *      sp0.add(gl, fp0, System.err);
+     *      st.attachShaderProgram(gl, sp0, true);
+     * </pre>
+     * A simplified entry point is {@link #create(GL2ES2, int, Class, String, String, String, boolean)}.
+     * 
+     * <p>
+     * The location is finally being resolved using the <code>context</code> class, see {@link #readShaderBinary(Class, String)}.
+     * </p>
+     * 
+     * @param gl current GL object to determine whether a shader compiler is available (if <code>source</code> is used),
+     *           or to determine the shader binary format (if <code>binary</code> is used).
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param count number of shaders
+     * @param context class used to help resolving the source and binary location
+     * @param srcRoot relative <i>root</i> path for <code>srcBasenames</code>
+     * @param srcBasenames basenames w/o path or suffix relative to <code>srcRoot</code> for the shader's source code
+     * @param binRoot relative <i>root</i> path for <code>binBasenames</code>
+     * @param binBasename basename w/o path or suffix relative to <code>binRoot</code> for the shader's binary code
+     * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance
+     *                        which can be edited later on at the costs of a String conversion when passing to 
+     *                        {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}.
+     *                        If <code>false</code> method returns an immutable <code>String</code> instance,
+     *                        which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}
+     *                        at no additional costs.
+     * 
+     * @throws IllegalArgumentException if <code>count</count> and <code>srcBasenames.length</code> do not match
+     * 
+     * @see #create(GL2ES2, int, int, Class, String[])
+     * @see #create(int, int, Class, int, String)
+     * @see #readShaderSource(Class, String)
+     * @see #getFileSuffix(boolean, int)
+     * @see ShaderUtil#getShaderBinaryFormats(GL)
+     * @see #getBinarySubPath(int)
+     */    
+    public static ShaderCode create(GL2ES2 gl, int type, int count, Class<?> context, 
+                                    String srcRoot, String[] srcBasenames, String binRoot, String binBasename,
+                                    boolean mutableStringBuilder) {
         ShaderCode res = null;
-        String srcFileName = null;
+        final String srcPath[];
+        String srcPathString = null;
         String binFileName = null;
 
-        if(ShaderUtil.isShaderCompilerAvailable(gl)) {
-            String srcPath[] = new String[1];
-            srcFileName = srcRoot + '/' + basename + "." + getFileSuffix(false, type);
-            srcPath[0] = srcFileName;
-            res = create(gl, type, number, context, srcPath);
+        if(null!=srcRoot && null!=srcBasenames && ShaderUtil.isShaderCompilerAvailable(gl)) {
+            srcPath = new String[srcBasenames.length];
+            final String srcSuffix = getFileSuffix(false, type);
+            for(int i=0; i<srcPath.length; i++) {
+                srcPath[i] = srcRoot + '/' + srcBasenames[i] + "." + srcSuffix;
+            }
+            res = create(gl, type, count, context, srcPath, mutableStringBuilder);
             if(null!=res) {
                 return res;
             }
+            srcPathString = Arrays.toString(srcPath);
+        } else {
+            srcPath = null;
         }
-        Set<Integer> binFmts = ShaderUtil.getShaderBinaryFormats(gl);
-        for(Iterator<Integer> iter=binFmts.iterator(); null==res && iter.hasNext(); ) {
-            int bFmt = iter.next().intValue();
-            String bFmtPath = getBinarySubPath(bFmt);
-            if(null==bFmtPath) continue;
-            binFileName = binRoot + '/' + bFmtPath + '/' + basename + "." + getFileSuffix(true, type);
-            res = create(type, number, context, bFmt, binFileName);
-        }
-
-        if(null==res) {
-            throw new GLException("No shader code found (source nor binary) for src: "+srcFileName+
-                                  ", bin: "+binFileName);
+        if(null!=binRoot && null!=binBasename) {
+            Set<Integer> binFmts = ShaderUtil.getShaderBinaryFormats(gl);
+            final String binSuffix = getFileSuffix(true, type);
+            for(Iterator<Integer> iter=binFmts.iterator(); iter.hasNext(); ) {
+                int bFmt = iter.next().intValue();
+                String bFmtPath = getBinarySubPath(bFmt);
+                if(null==bFmtPath) continue;
+                binFileName = binRoot + '/' + bFmtPath + '/' + binBasename + "." + binSuffix;
+                res = create(type, count, context, bFmt, binFileName);
+                if(null!=res) {
+                    return res;
+                }
+            }
         }
-
-        return res;
+        throw new GLException("No shader code found (source nor binary) for src: "+srcPathString+
+                              ", bin: "+binFileName);
     }
 
     /**
+     * Simplified variation of {@link #create(GL2ES2, int, int, Class, String, String[], String, String)}.
+     * <br>
+     * 
+     * Example:
+     * <pre>
+     *   Your std JVM layout (plain or within a JAR):
+     *   
+     *      org/test/glsl/MyShaderTest.class
+     *      org/test/glsl/shader/vertex.vp
+     *      org/test/glsl/shader/fragment.fp
+     *      org/test/glsl/shader/bin/nvidia/vertex.bvp
+     *      org/test/glsl/shader/bin/nvidia/fragment.bfp
+     *      
+     *   Your Android APK layout:
+     *   
+     *      classes.dex
+     *      assets/org/test/glsl/shader/vertex.vp
+     *      assets/org/test/glsl/shader/fragment.fp
+     *      assets/org/test/glsl/shader/bin/nvidia/vertex.bvp
+     *      assets/org/test/glsl/shader/bin/nvidia/fragment.bfp
+     *      ...
+     *   
+     *   Your invocation in org/test/glsl/MyShaderTest.java:
+     *   
+     *      ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(),
+     *                                         "shader", "shader/bin", "vertex");
+     *      ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(),
+     *                                         "shader", "shader/bin", "fragment");
+     *      ShaderProgram sp0 = new ShaderProgram();
+     *      sp0.add(gl, vp0, System.err);
+     *      sp0.add(gl, fp0, System.err);
+     *      st.attachShaderProgram(gl, sp0, true);
+     * </pre>
+     * 
+     * @param gl current GL object to determine whether a shader compiler is available (if <code>source</code> is used),
+     *           or to determine the shader binary format (if <code>binary</code> is used).
+     * @param type either {@link GL2ES2#GL_VERTEX_SHADER} or {@link GL2ES2#GL_FRAGMENT_SHADER}
+     * @param context class used to help resolving the source and binary location
+     * @param srcRoot relative <i>root</i> path for <code>basename</code>
+     * @param binRoot relative <i>root</i> path for <code>basename</code>
+     * @param mutableStringBuilder TODO
+     * @param basenames basename w/o path or suffix relative to <code>srcRoot</code> and <code>binRoot</code>
+     *                  for the shader's source and binary code.
+     * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance
+     *                        which can be edited later on at the costs of a String conversion when passing to 
+     *                        {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}.
+     *                        If <code>false</code> method returns an immutable <code>String</code> instance,
+     *                        which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}
+     *                        at no additional costs.
+     * @throws IllegalArgumentException if <code>count</count> is not 1
+     * 
+     * @see #create(GL2ES2, int, int, Class, String, String[], String, String)
+     */    
+    public static ShaderCode create(GL2ES2 gl, int type, Class<?> context, 
+                                    String srcRoot, String binRoot, String basename, boolean mutableStringBuilder) {
+        return create(gl, type, 1, context, srcRoot, new String[] { basename }, binRoot, basename, mutableStringBuilder );        
+    }
+    
+    /**
      * returns the uniq shader id as an integer
      */
     public int id() { return id; }
@@ -191,9 +450,9 @@ public class ShaderCode {
         return "UNKNOWN_SHADER";
     }
 
-    public int        shaderBinaryFormat() { return shaderBinaryFormat; }
-    public Buffer     shaderBinary() { return shaderBinary; }
-    public String[][] shaderSource() { return shaderSource; }
+    public int shaderBinaryFormat() { return shaderBinaryFormat; }
+    public Buffer shaderBinary() { return shaderBinary; }
+    public CharSequence[][] shaderSource() { return shaderSource; }
 
     public boolean    isValid() { return valid; }
 
@@ -207,6 +466,9 @@ public class ShaderCode {
 
         // Create & Compile the vertex/fragment shader objects
         if(null!=shaderSource) {
+            if(DEBUG_CODE) {
+                dumpShaderSource(System.err);
+            }
             valid=ShaderUtil.createAndCompileShader(gl, shader, shaderType,
                                                     shaderSource, verboseOut);
         } else if(null!=shaderBinary) {
@@ -246,7 +508,7 @@ public class ShaderCode {
         return id;
     }
     public String toString() {
-        StringBuffer buf = new StringBuffer("ShaderCode[id="+id+", type="+shaderTypeStr()+", valid="+valid+", shader: ");
+        StringBuilder buf = new StringBuilder("ShaderCode[id="+id+", type="+shaderTypeStr()+", valid="+valid+", shader: ");
         for(int i=0; i<shader.remaining(); i++) {
             buf.append(" "+shader.get(i));
         }
@@ -263,97 +525,284 @@ public class ShaderCode {
             out.println("<no shader source>");
             return;
         }
-        int sourceNum = (null!=shaderSource)?shaderSource.length:0;
-        int shaderNum = (null!=shader)?shader.capacity():0;
-        for(int i=0; i<shaderNum; i++) {
+        final int sourceCount = (null!=shaderSource)?shaderSource.length:0;
+        final int shaderCount = (null!=shader)?shader.capacity():0;
+        for(int i=0; i<shaderCount; i++) {
             out.println("");
-            out.println("Shader #"+i+"/"+shaderNum+" name "+shader.get(i));
+            out.println("Shader #"+i+"/"+shaderCount+" name "+shader.get(i));
             out.println("--------------------------------------------------------------");
-            if(i>=sourceNum) {
+            if(i>=sourceCount) {
                 out.println("<no shader source>");
             } else {
-                String[] src = shaderSource[i];
+                CharSequence[] src = shaderSource[i];
+                int lineno=0;
+                
                 for(int j=0; j<src.length; j++) {
-                    out.println("Segment "+j+"/"+src.length+" :");
-                    out.println(src[j]);
-                    out.println("");
+                    out.printf("%4d: // Segment %d/%d: \n", lineno, j, src.length);
+                    final BufferedReader reader = new BufferedReader(new StringReader(src[j].toString()));
+                    String line = null;
+                    try {
+                        while ((line = reader.readLine()) != null) {
+                            lineno++;
+                            out.printf("%4d: %s\n", lineno, line);
+                        }
+                    } catch (IOException e) { /* impossible .. StringReader */ }
                 }
             }
             out.println("--------------------------------------------------------------");
         }
     }
+    
+    /**
+     * Adds <code>data</code> after the line containing <code>tag</code>.
+     * <p>
+     * Note: The shader source to be edit must be created using a mutable StringBuilder.
+     * </p>
+     *  
+     * @param shaderIdx the shader index to be used.
+     * @param tag search string
+     * @param fromIndex start search <code>tag</code> begininig with this index
+     * @param data the text to be inserted. Shall end with an EOL '\n' character.
+     * @return index after the inserted <code>data</code>
+     * 
+     * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type <code>StringBuilder</code>
+     */
+    public int insertShaderSource(int shaderIdx, String tag, int fromIndex, CharSequence data) {
+        if(null==shaderSource) {
+            throw new IllegalStateException("no shader source");
+        }
+        final int shaderCount = (null!=shader)?shader.capacity():0;
+        if(0>shaderIdx || shaderIdx>=shaderCount) {
+            throw new IndexOutOfBoundsException("shaderIdx not within shader bounds [0.."+(shaderCount-1)+"]: "+shaderIdx);
+        }
+        final int sourceCount = (null!=shaderSource)?shaderSource.length:0;
+        if(shaderIdx>=sourceCount) {
+            throw new IndexOutOfBoundsException("shaderIdx not within source bounds [0.."+(sourceCount-1)+"]: "+shaderIdx);
+        }        
+        final CharSequence[] src = shaderSource[shaderIdx];
+        int curEndIndex = 0;
+        for(int j=0; j<src.length; j++) {
+            if( !(src[j] instanceof StringBuilder) ) {
+                throw new IllegalStateException("shader source not a mutable StringBuilder, but CharSequence of type: "+src[j].getClass().getName());
+            }
+            final StringBuilder sb = (StringBuilder)src[j];
+            curEndIndex += sb.length(); 
+            if(fromIndex < curEndIndex) { 
+                int insertIdx = sb.indexOf(tag, fromIndex);
+                if(0<=insertIdx) {
+                    insertIdx += tag.length();
+                    int eol = sb.indexOf("\n", insertIdx); // eol: covers \n and \r\n
+                    if(0>eol) {
+                        eol = sb.indexOf("\r", insertIdx); // eol: covers \r 'only'
+                    }
+                    if(0<eol) {
+                        insertIdx = eol+1;  // eol found
+                    } else {
+                        sb.insert(insertIdx, "\n"); // add eol
+                        insertIdx++;
+                    }
+                    sb.insert(insertIdx, data);
+                    return insertIdx+data.length();
+                }
+            }
+        }
+        return -1;
+    }
 
-    private static int readShaderSource(Class<?> context, URL url, StringBuffer result, int lineno) {
-        try {
-            if(DEBUG_CODE) {
-                System.err.printf("%3d: // %s\n", lineno, url);
+    /**
+     * Replaces <code>oldName</code> with <code>newName</code> in all shader sources.
+     * <p>
+     * In case <code>oldName</code> and <code>newName</code> are equal, no action is performed.
+     * </p> 
+     * <p>
+     * Note: The shader source to be edit must be created using a mutable StringBuilder.
+     * </p>
+     *  
+     * @param oldName the to be replace string
+     * @param newName the replacement string
+     * @return the number of replacements
+     * 
+     * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type <code>StringBuilder</code>
+     */
+    public int replaceInShaderSource(String oldName, String newName) {
+        if(null==shaderSource) {
+            throw new IllegalStateException("no shader source");
+        }
+        if(oldName == newName || oldName.equals(newName)) {
+            return 0;
+        }
+        final int oldNameLen = oldName.length();
+        final int newNameLen = newName.length();
+        int num = 0;
+        final int sourceCount = (null!=shaderSource)?shaderSource.length:0;
+        for(int shaderIdx = 0; shaderIdx<sourceCount; shaderIdx++) {
+            final CharSequence[] src = shaderSource[shaderIdx];
+            for(int j=0; j<src.length; j++) {
+                if( !(src[j] instanceof StringBuilder) ) {
+                    throw new IllegalStateException("shader source not a mutable StringBuilder, but CharSequence of type: "+src[j].getClass().getName());
+                }
+                final StringBuilder sb = (StringBuilder)src[j];
+                int curPos = 0;
+                while(curPos<sb.length()-oldNameLen+1) {
+                    int startIdx = sb.indexOf(oldName, curPos);
+                    if(0<=startIdx) {
+                        int endIdx = startIdx + oldNameLen;
+                        sb.replace(startIdx, endIdx, newName);
+                        curPos = startIdx + newNameLen;
+                        num++;
+                    } else {
+                        curPos = sb.length();
+                    }
+                }
+            }
+        }
+        return num;
+    }
+    
+    /**
+     * Adds <code>data</code> at <code>offset</code> in shader source for shader <code>shaderIdx</code>.
+     * <p>
+     * Note: The shader source to be edit must be created using a mutable StringBuilder.
+     * </p>
+     *  
+     * @param shaderIdx the shader index to be used.
+     * @param position in shader source segments of shader <code>shaderIdx</code>
+     * @param data the text to be inserted. Shall end with an EOL '\n' character.
+     * @return index after the inserted <code>data</code>
+     * 
+     * @throws IllegalStateException if the shader source's CharSequence is immutable, i.e. not of type <code>StringBuilder</code>
+     */
+    public int insertShaderSource(int shaderIdx, int position, CharSequence data) {
+        if(null==shaderSource) {
+            throw new IllegalStateException("no shader source");
+        }
+        final int shaderCount = (null!=shader)?shader.capacity():0;
+        if(0>shaderIdx || shaderIdx>=shaderCount) {
+            throw new IndexOutOfBoundsException("shaderIdx not within shader bounds [0.."+(shaderCount-1)+"]: "+shaderIdx);
+        }
+        final int sourceCount = (null!=shaderSource)?shaderSource.length:0;
+        if(shaderIdx>=sourceCount) {
+            throw new IndexOutOfBoundsException("shaderIdx not within source bounds [0.."+(sourceCount-1)+"]: "+shaderIdx);
+        }        
+        final CharSequence[] src = shaderSource[shaderIdx];
+        int curEndIndex = 0;
+        for(int j=0; j<src.length; j++) {
+            if( !(src[j] instanceof StringBuilder) ) {
+                throw new IllegalStateException("shader source not a mutable StringBuilder, but CharSequence of type: "+src[j].getClass().getName());
+            }
+            final StringBuilder sb = (StringBuilder)src[j];
+            curEndIndex += sb.length(); 
+            if(position < curEndIndex) { 
+                sb.insert(position, data);
+                return position+data.length();
+            }
+        }
+        return -1;
+    }
+
+    private static int readShaderSource(Class<?> context, URLConnection conn, StringBuilder result, int lineno) throws IOException  {
+        if(DEBUG_CODE) {
+            if(0 == lineno) {
+                result.append("// "+conn.getURL().toExternalForm()+"\n");
+            } else {
+                result.append("// included @ line "+lineno+": "+conn.getURL().toExternalForm()+"\n");
             }
-            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
+        }
+        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+        try {
             String line = null;
             while ((line = reader.readLine()) != null) {
                 lineno++;
-                if(DEBUG_CODE) {
-                    System.err.printf("%3d: %s\n", lineno, line);
-                }
                 if (line.startsWith("#include ")) {
                     String includeFile = line.substring(9).trim();
-                    URL nextURL = null;
+                    URLConnection nextConn = null;
                     
-                    // Try relative path first
-                    String next = IOUtil.getRelativeOf(url, includeFile);
-                    if(null != next) {
-                        nextURL = IOUtil.getResource(context, next);        
-                    }
-                    if (nextURL == null) {
-                        // Try absolute path
-                        nextURL = IOUtil.getResource(context, includeFile);        
+                    // Try relative of current shader location
+                    nextConn = IOUtil.openURL(IOUtil.getRelativeOf(conn.getURL(), includeFile), "ShaderCode.relativeOf ");
+                    if (nextConn == null) {
+                        // Try relative of class and absolute
+                        nextConn = IOUtil.getResource(context, includeFile);        
                     }
-                    if (nextURL == null) {
+                    if (nextConn == null) {
                         // Fail
                         throw new FileNotFoundException("Can't find include file " + includeFile);
                     }
-                    lineno = readShaderSource(context, nextURL, result, lineno);
+                    lineno = readShaderSource(context, nextConn, result, lineno);
                 } else {
                     result.append(line + "\n");
                 }
             }
-        } catch (IOException e) {
-            throw new RuntimeException(e);
+        } finally {
+            IOUtil.close(reader, false);
         }
         return lineno;
     }
+
+    /**
+     * 
+     * @param context
+     * @param conn
+     * @param result
+     * @throws IOException
+     */
+    public static void readShaderSource(Class<?> context, URLConnection conn, StringBuilder result) throws IOException {
+        readShaderSource(context, conn, result, 0);
+    }
     
-    public static void readShaderSource(Class<?> context, URL url, StringBuffer result) {
-        if(DEBUG_CODE) {
-            System.err.println();
-            System.err.println("// -----------------------------------------------------------");
-        }
-        readShaderSource(context, url, result, 0);
-        if(DEBUG_CODE) {
-            System.err.println("// -----------------------------------------------------------");
-            System.err.println();
+    /**
+     * Reads shader source located in <code>path</code>,
+     * either relative to the <code>context</code> class or absolute <i>as-is</i>.
+     * <p>
+     * Final location lookup is performed via {@link ClassLoader#getResource(String)} and {@link ClassLoader#getSystemResource(String)},
+     * see {@link IOUtil#getResource(Class, String)}.
+     * </p>
+     *  
+     * @param context class used to help resolve the source location
+     * @param path location of shader source
+     * @param mutableStringBuilder if <code>true</code> method returns a mutable <code>StringBuilder</code> instance
+     *                        which can be edited later on at the costs of a String conversion when passing to 
+     *                        {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}.
+     *                        If <code>false</code> method returns an immutable <code>String</code> instance,
+     *                        which can be passed to {@link GL2ES2#glShaderSource(int, int, String[], IntBuffer)}
+     *                        at no additional costs.
+     * @throws IOException 
+     * 
+     * @see IOUtil#getResource(Class, String)
+     */    
+    public static CharSequence readShaderSource(Class<?> context, String path, boolean mutableStringBuilder) throws IOException {
+        URLConnection conn = IOUtil.getResource(context, path);        
+        if (conn == null) {
+            return null;
         }
+        StringBuilder result = new StringBuilder();
+        readShaderSource(context, conn, result);
+        return mutableStringBuilder ? result : result.toString();
     }
 
-    public static String readShaderSource(Class<?> context, String path) {
-        URL url = IOUtil.getResource(context, path);        
-        if (url == null) {
+    /**
+     * Reads shader binary located in <code>path</code>, 
+     * either relative to the <code>context</code> class or absolute <i>as-is</i>.
+     * <p>
+     * Final location lookup is perfomed via {@link ClassLoader#getResource(String)} and {@link ClassLoader#getSystemResource(String)},
+     * see {@link IOUtil#getResource(Class, String)}.
+     * </p>
+     *  
+     * @param context class used to help resolve the source location
+     * @param path location of shader binary
+     * @throws IOException 
+     * 
+     * @see IOUtil#getResource(Class, String)
+     */
+    public static ByteBuffer readShaderBinary(Class<?> context, String path) throws IOException {
+        final URLConnection conn = IOUtil.getResource(context, path);
+        if (conn == null) {
             return null;
         }
-        StringBuffer result = new StringBuffer();
-        readShaderSource(context, url, result);
-        return result.toString();
-    }
-
-    public static ByteBuffer readShaderBinary(Class<?> context, String path) {
+        final BufferedInputStream bis = new BufferedInputStream( conn.getInputStream() );
         try {
-            URL url = IOUtil.getResource(context, path);
-            if (url == null) {
-                return null;
-            }
-            return IOUtil.copyStream2ByteBuffer( new BufferedInputStream( url.openStream() ) );
-        } catch (IOException e) {
-            throw new RuntimeException(e);
+            return IOUtil.copyStream2ByteBuffer( bis );
+        } finally {
+            IOUtil.close(bis, false);
         }
     }
 
@@ -361,7 +810,7 @@ public class ShaderCode {
     // Internals only below this point
     //
 
-    protected String[][] shaderSource = null;
+    protected CharSequence[][] shaderSource = null;
     protected Buffer     shaderBinary = null;
     protected int        shaderBinaryFormat = -1;
     protected IntBuffer  shader = null;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java
index 8dd09ff..14ea7d2 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderProgram.java
@@ -69,7 +69,8 @@ public class ShaderProgram {
     }
 
     /**
-     * Detaches all shader codes and deletes the program.
+     * Detaches all shader codes and deletes the program,
+     * but leaves the shader code intact.
      * Calls release(gl, false)
      *
      * @see #release(GL2ES2, boolean)
@@ -80,16 +81,16 @@ public class ShaderProgram {
 
     /**
      * Detaches all shader codes and deletes the program.
-     * If releaseShaderToo is true, destroys the shader codes as well.
+     * If <code>destroyShaderCode</code> is true it destroys the shader codes as well.
      */
-    public synchronized void release(GL2ES2 gl, boolean releaseShaderToo) {
+    public synchronized void release(GL2ES2 gl, boolean destroyShaderCode) {
         useProgram(gl, false);
         for(Iterator<ShaderCode> iter=allShaderCode.iterator(); iter.hasNext(); ) {
             ShaderCode shaderCode = iter.next();
             if(attachedShaderCode.remove(shaderCode)) {
                 ShaderUtil.detachShader(gl, shaderProgram, shaderCode.shader());
             }
-            if(releaseShaderToo) {
+            if(destroyShaderCode) {
                 shaderCode.destroy(gl);
             }
         }
@@ -213,7 +214,7 @@ public class ShaderProgram {
         
         gl.glLinkProgram(shaderProgram);
         
-        programLinked = ShaderUtil.isProgramValid(gl, shaderProgram, System.err);
+        programLinked = ShaderUtil.isProgramLinkStatusValid(gl, shaderProgram, System.err);
         if ( programLinked && shaderWasInUse )  {
             useProgram(gl, true);
         }
@@ -249,7 +250,7 @@ public class ShaderProgram {
         // Link the program
         gl.glLinkProgram(shaderProgram);
 
-        programLinked = ShaderUtil.isProgramValid(gl, shaderProgram, System.err);
+        programLinked = ShaderUtil.isProgramLinkStatusValid(gl, shaderProgram, System.err);
 
         return programLinked;
     }
@@ -283,9 +284,17 @@ public class ShaderProgram {
         return toString(null).toString();
     }
 
+    /**
+     * Performs {@link GL2ES2#glValidateProgram(int)} via {@link ShaderUtil#isProgramExecStatusValid(GL, int, PrintStream)}.
+     * @see ShaderUtil#isProgramExecStatusValid(GL, int, PrintStream)
+     **/
+    public synchronized boolean validateProgram(GL2ES2 gl, PrintStream verboseOut) {
+        return ShaderUtil.isProgramExecStatusValid(gl, shaderProgram, verboseOut);
+    }
+    
     public synchronized void useProgram(GL2ES2 gl, boolean on) {
-        if(!programLinked) throw new GLException("Program is not linked");
-        if(programInUse==on) return;
+        if(!programLinked) { throw new GLException("Program is not linked"); }
+        if(programInUse==on) { return; }
         gl.glUseProgram(on?shaderProgram:0);
         programInUse = on;
     }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java
index 2ef977e..62082aa 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderState.java
@@ -28,10 +28,8 @@
 
 package com.jogamp.opengl.util.glsl;
 
-import java.security.AccessController;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Iterator;
 
 import javax.media.opengl.GL;
@@ -48,7 +46,7 @@ import com.jogamp.common.util.IntObjectHashMap;
 import com.jogamp.opengl.util.GLArrayDataEditable;
 
 public class ShaderState {
-    public static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.GLSLState", true, AccessController.getContext());
+    public static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.GLSLState", true);
     private static final String currentStateKey = "jogamp.opengl.glsl.ShaderState" ;
     
     public ShaderState() {
@@ -197,18 +195,18 @@ public class ShaderState {
      * as well as switching to another program on the fly,
      * while managing all attribute and uniform data.</p>
      * 
-     * <p>[Re]sets all data and use program in case of a program switch.<br> 
-     * Use program if linked in case of a 1st time attachment.</p>
+     * <p>[Re]sets all data and use program in case of a program switch.</p>
+     *  
+     * <p>Use program, {@link #useProgram(GL2ES2, boolean)},
+     * if <code>enable</code> is <code>true</code>.</p>
      * 
      * @throws GLException if program was not linked and linking fails
      */
-    public synchronized void attachShaderProgram(GL2ES2 gl, ShaderProgram prog) throws GLException {
-        boolean prgInUse = false; // earmarked state
-
+    public synchronized void attachShaderProgram(GL2ES2 gl, ShaderProgram prog, boolean enable) throws GLException {
         if(DEBUG) {
             int curId = (null!=shaderProgram)?shaderProgram.id():-1;
             int newId = (null!=prog)?prog.id():-1;
-            System.err.println("Info: attachShaderProgram: "+curId+" -> "+newId+"\n\t"+shaderProgram+"\n\t"+prog);
+            System.err.println("Info: attachShaderProgram: "+curId+" -> "+newId+" (enable: "+enable+")\n\t"+shaderProgram+"\n\t"+prog);
             if(verbose) {
                 Throwable tX = new Throwable("Info: attachShaderProgram: Trace");
                 tX.printStackTrace();
@@ -222,15 +220,12 @@ public class ShaderState {
                 }
                 return;
             }
-            prgInUse = shaderProgram.inUse();
-            
-            if(prgInUse) {
-                // only disable if in use
-                if(null != prog) {
+            if(shaderProgram.inUse()) {
+                if(null != prog && enable) {
                     // new program will issue glUseProgram(..)
                     shaderProgram.programInUse = false;
                 } else {
-                    // no new program - disable
+                    // no new 'enabled' program - disable
                     useProgram(gl, false);
                 }
             }
@@ -243,9 +238,9 @@ public class ShaderState {
         if(null!=shaderProgram) {
             // [re]set all data and use program if switching program, 
             // or  use program if program is linked
-            if(shaderProgram.linked() || resetAllShaderData) {
+            if(resetAllShaderData || enable) {
                 useProgram(gl, true); // may reset all data
-                if(!prgInUse) {
+                if(!enable) {
                     useProgram(gl, false);
                 }
             }
@@ -286,7 +281,7 @@ public class ShaderState {
      * @see #glReleaseAllUniforms
      * @see ShaderProgram#release(GL2ES2, boolean)
      */
-    public synchronized void release(GL2ES2 gl, boolean destroyBoundAttributes, boolean releaseProgramToo, boolean releaseShaderToo) {
+    public synchronized void release(GL2ES2 gl, boolean destroyBoundAttributes, boolean destroyShaderProgram, boolean destroyShaderCode) {
         if(null!=shaderProgram) {            
             shaderProgram.useProgram(gl, false);
         }
@@ -297,10 +292,8 @@ public class ShaderState {
         }
         releaseAllAttributes(gl);
         releaseAllUniforms(gl);
-        if(null!=shaderProgram) {
-            if(releaseProgramToo) {
-                shaderProgram.release(gl, releaseShaderToo);
-            } 
+        if(null!=shaderProgram && destroyShaderProgram) {
+            shaderProgram.release(gl, destroyShaderCode);
         }
     }
 
@@ -320,7 +313,7 @@ public class ShaderState {
      * @see GL2ES2#glGetAttribLocation(int, String)
      */
     public int getCachedAttribLocation(String name) {
-        Integer idx = (Integer) activeAttribLocationMap.get(name);
+        Integer idx = activeAttribLocationMap.get(name);
         return (null!=idx)?idx.intValue():-1;
     }
     
@@ -340,7 +333,7 @@ public class ShaderState {
      * @see ShaderProgram#glReplaceShader
      */
     public GLArrayData getAttribute(String name) {
-        return (GLArrayData) activeAttribDataMap.get(name);
+        return activeAttribDataMap.get(name);
     }
     
     /**
@@ -488,7 +481,8 @@ public class ShaderState {
      * @return true if the named attribute is enable
      */
     public final boolean isVertexAttribArrayEnabled(String name) {
-        return enabledAttributes.contains(name);
+        final Boolean v = activedAttribEnabledMap.get(name);
+        return null != v && v.booleanValue();
     }
     
     /**
@@ -499,7 +493,7 @@ public class ShaderState {
     }
     
     private boolean enableVertexAttribArray(GL2ES2 gl, String name, int location) {
-        enabledAttributes.add(name);
+        activedAttribEnabledMap.put(name, Boolean.TRUE);
         if(0>location) {
             location = getAttribLocation(gl, name);
             if(0>location) {
@@ -572,7 +566,7 @@ public class ShaderState {
     }
     
     private boolean disableVertexAttribArray(GL2ES2 gl, String name, int location) {
-        enabledAttributes.remove(name);
+        activedAttribEnabledMap.put(name, Boolean.FALSE);
         if(0>location) {
             location = getAttribLocation(gl, name);
             if(0>location) {
@@ -690,18 +684,14 @@ public class ShaderState {
     public void releaseAllAttributes(GL2ES2 gl) {
         if(null!=shaderProgram) {
             for(Iterator<GLArrayData> iter = activeAttribDataMap.values().iterator(); iter.hasNext(); ) {
-                if(!disableVertexAttribArray(gl, iter.next())) {
-                    throw new GLException("Internal Error: mapped vertex attribute couldn't be disabled");
-                }
+                disableVertexAttribArray(gl, iter.next());
             }
-            for(Iterator<String> iter = enabledAttributes.iterator(); iter.hasNext(); ) {
-                if(!disableVertexAttribArray(gl, iter.next())) {
-                    throw new GLException("Internal Error: prev enabled vertex attribute couldn't be disabled");
-                }
+            for(Iterator<String> iter = activedAttribEnabledMap.keySet().iterator(); iter.hasNext(); ) {
+                disableVertexAttribArray(gl, iter.next());
             }
         }
         activeAttribDataMap.clear();
-        enabledAttributes.clear();
+        activedAttribEnabledMap.clear();
         activeAttribLocationMap.clear();
         managedAttributes.clear();        
     }
@@ -724,10 +714,10 @@ public class ShaderState {
      * @see ShaderProgram#glReplaceShader
      */
     public void disableAllVertexAttributeArrays(GL2ES2 gl, boolean removeFromState) {
-        for(Iterator<String> iter = enabledAttributes.iterator(); iter.hasNext(); ) {
+        for(Iterator<String> iter = activedAttribEnabledMap.keySet().iterator(); iter.hasNext(); ) {
             final String name = iter.next();
             if(removeFromState) {
-                enabledAttributes.remove(name);
+                activedAttribEnabledMap.remove(name);
             }
             final int index = getAttribLocation(gl, name);
             if(0<=index) {
@@ -743,7 +733,7 @@ public class ShaderState {
         attribute.setLocation(loc);
 
         if(0<=loc) {
-            if(enabledAttributes.contains(name)) {
+            if(isVertexAttribArrayEnabled(name)) {
                 // enable attrib, VBO and pass location/data
                 gl.glEnableVertexAttribArray(loc);
             }
@@ -790,7 +780,7 @@ public class ShaderState {
         if(0<=loc) {
             this.bindAttribLocation(gl, loc, name);
             
-            if(enabledAttributes.contains(name)) {
+            if(isVertexAttribArrayEnabled(name)) {
                 // enable attrib, VBO and pass location/data
                 gl.glEnableVertexAttribArray(loc);
             }
@@ -1009,8 +999,12 @@ public class ShaderState {
             sb.append("ShaderProgram: null");
         }
         sb.append(Platform.getNewline()).append(" enabledAttributes [");
-        for(Iterator<String> iter = enabledAttributes.iterator(); iter.hasNext(); ) {
-            sb.append(Platform.getNewline()).append("  ").append(iter.next());
+        {
+            Iterator<String> names = activedAttribEnabledMap.keySet().iterator();
+            Iterator<Boolean> values = activedAttribEnabledMap.values().iterator();
+            while( names.hasNext() ) {
+                sb.append(Platform.getNewline()).append("  ").append(names.next()).append(": ").append(values.next());
+            }
         }
         sb.append(Platform.getNewline()).append(" ],").append(" activeAttributes [");
         for(Iterator<GLArrayData> iter = activeAttribDataMap.values().iterator(); iter.hasNext(); ) {
@@ -1040,7 +1034,7 @@ public class ShaderState {
     private boolean verbose = DEBUG ? true : false;
     private ShaderProgram shaderProgram=null;
     
-    private HashSet<String> enabledAttributes = new HashSet<String>();
+    private HashMap<String, Boolean> activedAttribEnabledMap = new HashMap<String, Boolean>();
     private HashMap<String, Integer> activeAttribLocationMap = new HashMap<String, Integer>();
     private HashMap<String, GLArrayData> activeAttribDataMap = new HashMap<String, GLArrayData>();
     private ArrayList<GLArrayData> managedAttributes = new ArrayList<GLArrayData>();
diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java
index 747dd5c..40c0524 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/ShaderUtil.java
@@ -42,433 +42,337 @@ import javax.media.opengl.*;
 import com.jogamp.common.nio.Buffers;
 
 public class ShaderUtil {
-    static abstract class Impl {
-        public abstract String getShaderInfoLog(GL gl, int shaderObj);
-        public abstract String getProgramInfoLog(GL gl, int programObj);
-        public abstract boolean isShaderStatusValid(GL gl, int shaderObj, int name);
-        public abstract boolean isShaderStatusValid(GL gl, int shaderObj, int name, PrintStream verboseOut);
-        public abstract boolean isShaderStatusValid(GL gl, IntBuffer shaders, int name);
-        public abstract boolean isShaderStatusValid(GL gl, IntBuffer shaders, int name, PrintStream verboseOut);
-        public abstract boolean isProgramStatusValid(GL gl, int programObj, int name);
-        public abstract boolean isProgramValid(GL gl, int programObj);
-        public abstract boolean isProgramValid(GL gl, int programObj, PrintStream verboseOut);
-        public abstract void createShader(GL gl, int type, IntBuffer shaders);
-        public abstract Set<Integer> getShaderBinaryFormats(GL gl);
-        public abstract boolean isShaderCompilerAvailable(GL gl);
-        public abstract void shaderSource(GL gl, int shader, java.lang.String[] source);
-        public abstract void shaderSource(GL gl, IntBuffer shaders, java.lang.String[][] sources);
-        public abstract void shaderBinary(GL gl, IntBuffer shaders, int binFormat, java.nio.Buffer bin);
-        public abstract void compileShader(GL gl, IntBuffer shaders);
-        public abstract void attachShader(GL gl, int program, IntBuffer shaders);
-        public abstract void detachShader(GL gl, int program, IntBuffer shaders);
-        public abstract void deleteShader(GL gl, IntBuffer shaders);
-
-        public abstract boolean createAndLoadShader(GL gl, IntBuffer shader, int shaderType,
-                                                    int binFormat, java.nio.Buffer bin,
-                                                    PrintStream verboseOut);
-
-        public abstract boolean createAndCompileShader(GL gl, IntBuffer shader, int shaderType,
-                                                       java.lang.String[][] sources, 
-                                                       PrintStream verboseOut);
-    }
-
-    static class GL2ES2Impl extends Impl {
-        public String getShaderInfoLog(GL _gl, int shaderObj) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int[] infoLogLength=new int[1];
-            gl.glGetShaderiv(shaderObj, GL2ES2.GL_INFO_LOG_LENGTH, infoLogLength, 0);
-
-            if(infoLogLength[0]==0) {
-                return "(no info log)";
-            }
-            int[] charsWritten=new int[1];
-            byte[] infoLogBytes = new byte[infoLogLength[0]];
-            gl.glGetShaderInfoLog(shaderObj, infoLogLength[0], charsWritten, 0, infoLogBytes, 0);
+    public static String getShaderInfoLog(GL _gl, int shaderObj) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int[] infoLogLength=new int[1];
+        gl.glGetShaderiv(shaderObj, GL2ES2.GL_INFO_LOG_LENGTH, infoLogLength, 0);
 
-            return new String(infoLogBytes, 0, charsWritten[0]);
+        if(infoLogLength[0]==0) {
+            return "(no info log)";
         }
+        int[] charsWritten=new int[1];
+        byte[] infoLogBytes = new byte[infoLogLength[0]];
+        gl.glGetShaderInfoLog(shaderObj, infoLogLength[0], charsWritten, 0, infoLogBytes, 0);
 
-        public String getProgramInfoLog(GL _gl, int programObj) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int[] infoLogLength=new int[1];
-            gl.glGetProgramiv(programObj, GL2ES2.GL_INFO_LOG_LENGTH, infoLogLength, 0);
-
-            if(infoLogLength[0]==0) {
-                return "(no info log)";
-            }
-            int[] charsWritten=new int[1];
-            byte[] infoLogBytes = new byte[infoLogLength[0]];
-            gl.glGetProgramInfoLog(programObj, infoLogLength[0], charsWritten, 0, infoLogBytes, 0);
+        return new String(infoLogBytes, 0, charsWritten[0]);
+    }
 
-            return new String(infoLogBytes, 0, charsWritten[0]);
-        }
+    public static String getProgramInfoLog(GL _gl, int programObj) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int[] infoLogLength=new int[1];
+        gl.glGetProgramiv(programObj, GL2ES2.GL_INFO_LOG_LENGTH, infoLogLength, 0);
 
-        public boolean isShaderStatusValid(GL _gl, int shaderObj, int name) {
-            return isShaderStatusValid(_gl, shaderObj, name, null);
+        if(infoLogLength[0]==0) {
+            return "(no info log)";
         }
+        int[] charsWritten=new int[1];
+        byte[] infoLogBytes = new byte[infoLogLength[0]];
+        gl.glGetProgramInfoLog(programObj, infoLogLength[0], charsWritten, 0, infoLogBytes, 0);
 
-        public boolean isShaderStatusValid(GL _gl, int shaderObj, int name, PrintStream verboseOut) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int[] ires = new int[1];
-            gl.glGetShaderiv(shaderObj, name, ires, 0);
+        return new String(infoLogBytes, 0, charsWritten[0]);
+    }
 
-            boolean res = ires[0]==1;
-            if(!res && null!=verboseOut) {
-                verboseOut.println("Shader status invalid: "+ getShaderInfoLog(gl, shaderObj));
-            }
-            return res;
-        }
+    public static boolean isShaderStatusValid(GL _gl, int shaderObj, int name, PrintStream verboseOut) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int[] ires = new int[1];
+        gl.glGetShaderiv(shaderObj, name, ires, 0);
 
-        public boolean isShaderStatusValid(GL _gl, IntBuffer shaders, int name) {
-            return isShaderStatusValid(_gl, shaders, name, null);
+        boolean res = ires[0]==1;
+        if(!res && null!=verboseOut) {
+            verboseOut.println("Shader status invalid: "+ getShaderInfoLog(gl, shaderObj));
         }
+        return res;
+    }
 
-        public boolean isShaderStatusValid(GL _gl, IntBuffer shaders, int name, PrintStream verboseOut) {
-            boolean res = true;
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                res = isShaderStatusValid(_gl, shaders.get(i), name, verboseOut) && res;
-            }
-            return res;
+    public static boolean isShaderStatusValid(GL _gl, IntBuffer shaders, int name, PrintStream verboseOut) {
+        boolean res = true;
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            res = isShaderStatusValid(_gl, shaders.get(i), name, verboseOut) && res;
         }
+        return res;
+    }
 
-        public boolean isProgramStatusValid(GL _gl, int programObj, int name) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int[] ires = new int[1];
-            gl.glGetProgramiv(programObj, name, ires, 0);
-
-            return ires[0]==1;
-        }
+    public static boolean isProgramStatusValid(GL _gl, int programObj, int name) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int[] ires = new int[1];
+        gl.glGetProgramiv(programObj, name, ires, 0);
 
-        public boolean isProgramValid(GL _gl, int programObj) {
-            return isProgramValid(_gl, programObj, null);
-        }
+        return ires[0]==1;
+    }
 
-        public boolean isProgramValid(GL _gl, int programObj, PrintStream verboseOut) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            if(!gl.glIsProgram(programObj)) {
-                if(null!=verboseOut) {
-                    verboseOut.println("Program name invalid: "+programObj);
-                }
-                return false;
+    public static boolean isProgramLinkStatusValid(GL _gl, int programObj, PrintStream verboseOut) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        if(!gl.glIsProgram(programObj)) {
+            if(null!=verboseOut) {
+                verboseOut.println("Program name invalid: "+programObj);
             }
-            if(!isProgramStatusValid(gl, programObj, GL2ES2.GL_LINK_STATUS)) {
-                if(null!=verboseOut) {
-                    verboseOut.println("Program link failed: "+programObj+"\n\t"+ getProgramInfoLog(gl, programObj));
-                }
-                return false;
+            return false;
+        }
+        if(!isProgramStatusValid(gl, programObj, GL2ES2.GL_LINK_STATUS)) {
+            if(null!=verboseOut) {
+                verboseOut.println("Program link failed: "+programObj+"\n\t"+ getProgramInfoLog(gl, programObj));
             }
-            if ( !gl.isGLES2() || isShaderCompilerAvailable(gl) ) {
-                // failed on APX2500 (ES2.0, no compiler) for valid programs
-                gl.glValidateProgram(programObj);
-                if(!isProgramStatusValid(gl, programObj, GL2ES2.GL_VALIDATE_STATUS)) {
-                    if(null!=verboseOut) {
-                        verboseOut.println("Program validation failed: "+programObj+"\n\t"+ getProgramInfoLog(gl, programObj));
-                    }
-                    return false;
-                }
+            return false;
+        }
+        return true;
+    }
+    
+    /**
+     * Performs {@link GL2ES2#glValidateProgram(int)}
+     * <p>
+     * One shall only call this method while debugging and only if all required 
+     * resources by the shader are set.
+     * </p>
+     * <p>
+     * Note: It is possible that a working shader program will fail validation.
+     * This has been experienced on NVidia APX2500 and Tegra2.
+     * </p>
+     * @see GL2ES2#glValidateProgram(int)
+     **/
+    public static boolean isProgramExecStatusValid(GL _gl, int programObj, PrintStream verboseOut) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        gl.glValidateProgram(programObj);
+        if(!isProgramStatusValid(gl, programObj, GL2ES2.GL_VALIDATE_STATUS)) {
+            if(null!=verboseOut) {
+                verboseOut.println("Program validation failed: "+programObj+"\n\t"+ getProgramInfoLog(gl, programObj));
             }
-            return true;
+            return false;
         }
+        return true;
+    }
 
-        public void createShader(GL _gl, int type, IntBuffer shaders) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                shaders.put(i, gl.glCreateShader(type));
-            }
+    public static void createShader(GL _gl, int type, IntBuffer shaders) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            shaders.put(i, gl.glCreateShader(type));
         }
+    }
 
-        private Boolean shaderCompilerAvailable = null;
-        private Set<Integer> shaderBinaryFormats = null;
-
-        public Set<Integer> getShaderBinaryFormats(GL _gl) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            if(null==shaderBinaryFormats) {
-                gl.getContext().validateCurrent();
-
-                int[] param = new int[1];
-                shaderBinaryFormats = new HashSet<Integer>();
-
-                if (gl.isGLES2()) {
-                    gl.glGetIntegerv(GL2ES2.GL_NUM_SHADER_BINARY_FORMATS, param, 0);
-                    int numFormats = param[0];
-                    if(numFormats>0) {
-                        int[] formats = new int[numFormats];
-                        gl.glGetIntegerv(GL2ES2.GL_SHADER_BINARY_FORMATS, formats, 0);
-                        for(int i=0; i<numFormats; i++) {
-                            shaderBinaryFormats.add(new Integer(formats[i]));
-                        }
+    /**
+     * If supported, queries the natively supported shader binary formats using 
+     * {@link GL2ES2#GL_NUM_SHADER_BINARY_FORMATS} and {@link GL2ES2#GL_SHADER_BINARY_FORMATS}
+     * via {@link GL2ES2#glGetIntegerv(int, int[], int)}.
+     */
+    public static Set<Integer> getShaderBinaryFormats(GL _gl) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        final ProfileInformation info = getProfileInformation(gl);
+        if(null == info.shaderBinaryFormats) {
+            info.shaderBinaryFormats = new HashSet<Integer>();
+            if (gl.isGLES2Compatible()) {
+                final int[] param = new int[1];
+                gl.glGetIntegerv(GL2ES2.GL_NUM_SHADER_BINARY_FORMATS, param, 0);
+                int numFormats = param[0];
+                if(numFormats>0) {
+                    int[] formats = new int[numFormats];
+                    gl.glGetIntegerv(GL2ES2.GL_SHADER_BINARY_FORMATS, formats, 0);
+                    for(int i=0; i<numFormats; i++) {
+                        info.shaderBinaryFormats.add(new Integer(formats[i]));
                     }
                 }
             }
-            return shaderBinaryFormats;
         }
+        return info.shaderBinaryFormats;
+    }
 
-
-        public boolean isShaderCompilerAvailable(GL _gl) {
-            GL2ES2 gl = _gl.getGL2ES2();
-            if(null==shaderCompilerAvailable) {
-                gl.getContext().validateCurrent();
-                Set<Integer> bfs = getShaderBinaryFormats(gl);
-                if(gl.isGLES2()) {
-                    byte[] param = new byte[1];
-                    gl.glGetBooleanv(GL2ES2.GL_SHADER_COMPILER, param, 0);
-                    boolean v = param[0]!=(byte)0x00;
-                    if(!v && bfs.size()==0) {
+    /** Returns true if a hader compiler is available, otherwise false. */
+    public static boolean isShaderCompilerAvailable(GL _gl) {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        final ProfileInformation info = getProfileInformation(gl);
+        if(null==info.shaderCompilerAvailable) {
+            if(gl.isGLES2()) {
+                final byte[] param = new byte[1];
+                gl.glGetBooleanv(GL2ES2.GL_SHADER_COMPILER, param, 0);
+                boolean v = param[0]!=(byte)0x00;
+                if(!v) {
+                    final Set<Integer> bfs = getShaderBinaryFormats(gl);
+                    if(bfs.size()==0) {
                         // no supported binary formats, hence a compiler must be available!
                         v = true;
                     }
-                    shaderCompilerAvailable = new Boolean(v);
-                } else if( gl.isGL2ES2() ) {
-                    shaderCompilerAvailable = new Boolean(true);
-                } else {
-                    throw new GLException("Invalid OpenGL profile");
                 }
+                info.shaderCompilerAvailable = new Boolean(v);
+            } else if( gl.isGL2ES2() ) {
+                info.shaderCompilerAvailable = new Boolean(true);
+            } else {
+                throw new GLException("Invalid OpenGL profile");
             }
-            return shaderCompilerAvailable.booleanValue();
         }
+        return info.shaderCompilerAvailable.booleanValue();
+    }
 
-        public void shaderSource(GL _gl, int shader, java.lang.String[] source)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            if(!isShaderCompilerAvailable(_gl)) {
-                throw new GLException("No compiler is available");
-            }
-
-            int count = (null!=source)?source.length:0;
-            if(count==0) {
-                throw new GLException("No sources specified");
-            }
-
-            IntBuffer lengths = Buffers.newDirectIntBuffer(count);
-            for(int i=0; i<count; i++) {
-                lengths.put(i, source[i].length());
-            }
-            gl.glShaderSource(shader, count, source, lengths);
+    public static void shaderSource(GL _gl, int shader, CharSequence[] source)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        if(!isShaderCompilerAvailable(_gl)) {
+            throw new GLException("No compiler is available");
         }
 
-        public void shaderSource(GL _gl, IntBuffer shaders, java.lang.String[][] sources)
-        {
-            int sourceNum = (null!=sources)?sources.length:0;
-            int shaderNum = (null!=shaders)?shaders.remaining():0;
-            if(shaderNum<=0 || sourceNum<=0 || shaderNum!=sourceNum) {
-                throw new GLException("Invalid number of shaders and/or sources: shaders="+
-                                      shaderNum+", sources="+sourceNum);
-            }
-            for(int i=0; i<sourceNum; i++) {
-                shaderSource(_gl, shaders.get(shaders.position() + i), sources[i]);
-            }
+        int count = (null!=source)?source.length:0;
+        if(count==0) {
+            throw new GLException("No sources specified");
         }
 
-        public void shaderBinary(GL _gl, IntBuffer shaders, int binFormat, java.nio.Buffer bin)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            if(getShaderBinaryFormats(gl).size()<=0) {
-                throw new GLException("No binary formats are supported");
-            }
-
-            int shaderNum = shaders.remaining();
-            if(shaderNum<=0) {
-                throw new GLException("No shaders specified");
-            }
-            if(null==bin) {
-                throw new GLException("Null shader binary");
-            }
-            int binLength = bin.remaining();
-            if(0>=binLength) {
-                throw new GLException("Empty shader binary (remaining == 0)");
+        IntBuffer lengths = Buffers.newDirectIntBuffer(count);
+        for(int i=0; i<count; i++) {
+            lengths.put(i, source[i].length());
+        }        
+        if(source instanceof String[]) {
+            // rare case ..
+            gl.glShaderSource(shader, count, (String[])source, lengths);
+        } else {
+            final String[] tmp = new String[source.length];
+            for(int i = source.length - 1; i>=0; i--) {
+                final CharSequence csq = source[i];
+                if(csq instanceof String) {
+                    // if ShaderCode.create(.. mutableStringBuffer == false )
+                    tmp[i] = (String) csq;
+                } else {
+                    // if ShaderCode.create(.. mutableStringBuffer == true )
+                    tmp[i] = source[i].toString();
+                }
             }
-            gl.glShaderBinary(shaderNum, shaders, binFormat, bin, binLength);
+            gl.glShaderSource(shader, count, tmp, lengths);
         }
+    }
 
-        public void compileShader(GL _gl, IntBuffer shaders)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                gl.glCompileShader(shaders.get(i));
-            }
+    public static void shaderSource(GL _gl, IntBuffer shaders, CharSequence[][] sources)
+    {
+        int sourceNum = (null!=sources)?sources.length:0;
+        int shaderNum = (null!=shaders)?shaders.remaining():0;
+        if(shaderNum<=0 || sourceNum<=0 || shaderNum!=sourceNum) {
+            throw new GLException("Invalid number of shaders and/or sources: shaders="+
+                                  shaderNum+", sources="+sourceNum);
         }
-
-        public void attachShader(GL _gl, int program, IntBuffer shaders)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                gl.glAttachShader(program, shaders.get(i));
-            }
+        for(int i=0; i<sourceNum; i++) {
+            shaderSource(_gl, shaders.get(shaders.position() + i), sources[i]);
         }
+    }
 
-        public void detachShader(GL _gl, int program, IntBuffer shaders)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                gl.glDetachShader(program, shaders.get(i));
-            }
+    public static void shaderBinary(GL _gl, IntBuffer shaders, int binFormat, java.nio.Buffer bin)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        if(getShaderBinaryFormats(gl).size()<=0) {
+            throw new GLException("No binary formats are supported");
         }
 
-        public void deleteShader(GL _gl, IntBuffer shaders)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            for (int i = shaders.position(); i < shaders.limit(); i++) {
-                gl.glDeleteShader(shaders.get(i));
-
-            }
+        int shaderNum = shaders.remaining();
+        if(shaderNum<=0) {
+            throw new GLException("No shaders specified");
         }
-
-        public boolean createAndLoadShader(GL _gl, IntBuffer shader, int shaderType,
-                                           int binFormat, java.nio.Buffer bin,
-                                           PrintStream verboseOut)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int err = gl.glGetError(); // flush previous errors ..
-            if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
-                verboseOut.println("createAndLoadShader: Pre GL Error: 0x"+Integer.toHexString(err));
-            }
-
-            createShader(gl, shaderType, shader);
-            err = gl.glGetError(); 
-            if(err!=GL.GL_NO_ERROR) {
-                throw new GLException("createAndLoadShader: CreateShader failed, GL Error: 0x"+Integer.toHexString(err));
-            }
-
-
-            shaderBinary(gl, shader, binFormat, bin);
-
-            err = gl.glGetError();
-            if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
-                verboseOut.println("createAndLoadShader: ShaderBinary failed, GL Error: 0x"+Integer.toHexString(err));
-            }
-            return err == GL.GL_NO_ERROR;
+        if(null==bin) {
+            throw new GLException("Null shader binary");
         }
-
-        public boolean createAndCompileShader(GL _gl, IntBuffer shader, int shaderType,
-                                              java.lang.String[][] sources, 
-                                              PrintStream verboseOut)
-        {
-            GL2ES2 gl = _gl.getGL2ES2();
-            int err = gl.glGetError(); // flush previous errors ..
-            if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
-                verboseOut.println("createAndCompileShader: Pre GL Error: 0x"+Integer.toHexString(err));
-            }
-
-            createShader(gl, shaderType, shader);
-            err = gl.glGetError(); 
-            if(err!=GL.GL_NO_ERROR) {
-                throw new GLException("createAndCompileShader: CreateShader failed, GL Error: 0x"+Integer.toHexString(err));
-            }
-
-            shaderSource(gl, shader, sources);
-            err = gl.glGetError(); 
-            if(err!=GL.GL_NO_ERROR) {
-                throw new GLException("createAndCompileShader: ShaderSource failed, GL Error: 0x"+Integer.toHexString(err));
-            }
-
-            compileShader(gl, shader);
-            err = gl.glGetError(); 
-            if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
-                verboseOut.println("createAndCompileShader: CompileShader failed, GL Error: 0x"+Integer.toHexString(err));
-            }
-
-            return isShaderStatusValid(gl, shader, GL2ES2.GL_COMPILE_STATUS, verboseOut) && err == GL.GL_NO_ERROR;
+        int binLength = bin.remaining();
+        if(0>=binLength) {
+            throw new GLException("Empty shader binary (remaining == 0)");
         }
-
-    }
-
-    public static String getShaderInfoLog(GL gl, int shaderObj) {
-        return getImpl(gl).getShaderInfoLog(gl, shaderObj);
-    }
-
-    public static String getProgramInfoLog(GL gl, int programObj) {
-        return getImpl(gl).getProgramInfoLog(gl, programObj);
-    }
-
-    public static boolean isShaderStatusValid(GL gl, int shaderObj, int name) {
-        return getImpl(gl).isShaderStatusValid(gl, shaderObj, name);
-    }
-
-    public static boolean isShaderStatusValid(GL gl, int shaderObj, int name, PrintStream verboseOut) {
-        return getImpl(gl).isShaderStatusValid(gl, shaderObj, name, verboseOut);
-    }
-
-    public static boolean isShaderStatusValid(GL gl, IntBuffer shaders, int name) {
-        return getImpl(gl).isShaderStatusValid(gl, shaders, name);
+        gl.glShaderBinary(shaderNum, shaders, binFormat, bin, binLength);
     }
 
-    public static boolean isShaderStatusValid(GL gl, IntBuffer shaders, int name, PrintStream verboseOut) {
-        return getImpl(gl).isShaderStatusValid(gl, shaders, name, verboseOut);
-    }
-
-    public static boolean isProgramStatusValid(GL gl, int programObj, int name) {
-        return getImpl(gl).isProgramStatusValid(gl, programObj, name);
-    }
-
-    public static boolean isProgramValid(GL gl, int programObj) {
-        return getImpl(gl).isProgramValid(gl, programObj);
+    public static void compileShader(GL _gl, IntBuffer shaders)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            gl.glCompileShader(shaders.get(i));
+        }
     }
 
-    public static boolean isProgramValid(GL gl, int programObj, PrintStream verboseOut) {
-        return getImpl(gl).isProgramValid(gl, programObj, verboseOut);
+    public static void attachShader(GL _gl, int program, IntBuffer shaders)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            gl.glAttachShader(program, shaders.get(i));
+        }
     }
 
-    public static void createShader(GL gl, int type, IntBuffer shaders) {
-        getImpl(gl).createShader(gl, type, shaders);
+    public static void detachShader(GL _gl, int program, IntBuffer shaders)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            gl.glDetachShader(program, shaders.get(i));
+        }
     }
 
-    public static Set<Integer> getShaderBinaryFormats(GL gl) {
-        return getImpl(gl).getShaderBinaryFormats(gl);
-    }
+    public static void deleteShader(GL _gl, IntBuffer shaders)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        for (int i = shaders.position(); i < shaders.limit(); i++) {
+            gl.glDeleteShader(shaders.get(i));
 
-    public static boolean isShaderCompilerAvailable(GL gl) {
-        return getImpl(gl).isShaderCompilerAvailable(gl);
+        }
     }
 
-    public static void shaderSource(GL gl, int shader, java.lang.String[] source) {
-        getImpl(gl).shaderSource(gl, shader, source);
-    }
+    public static boolean createAndLoadShader(GL _gl, IntBuffer shader, int shaderType,
+                                              int binFormat, java.nio.Buffer bin,
+                                              PrintStream verboseOut)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int err = gl.glGetError(); // flush previous errors ..
+        if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
+            verboseOut.println("createAndLoadShader: Pre GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static void shaderSource(GL gl, IntBuffer shaders, java.lang.String[][] sources) {
-        getImpl(gl).shaderSource(gl, shaders, sources);
-    }
+        createShader(gl, shaderType, shader);
+        err = gl.glGetError(); 
+        if(err!=GL.GL_NO_ERROR) {
+            throw new GLException("createAndLoadShader: CreateShader failed, GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static void shaderBinary(GL gl, IntBuffer shaders, int binFormat, java.nio.Buffer bin) {
-        getImpl(gl).shaderBinary(gl, shaders, binFormat, bin);
-    }
+        shaderBinary(gl, shader, binFormat, bin);
 
-    public static void compileShader(GL gl, IntBuffer shaders) {
-        getImpl(gl).compileShader(gl, shaders);
+        err = gl.glGetError();
+        if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
+            verboseOut.println("createAndLoadShader: ShaderBinary failed, GL Error: 0x"+Integer.toHexString(err));
+        }
+        return err == GL.GL_NO_ERROR;
     }
 
-    public static void attachShader(GL gl, int program, IntBuffer shaders) {
-        getImpl(gl).attachShader(gl, program, shaders);
-    }
+    public static boolean createAndCompileShader(GL _gl, IntBuffer shader, int shaderType,
+                                                 CharSequence[][] sources, 
+                                                 PrintStream verboseOut)
+    {
+        final GL2ES2 gl = _gl.getGL2ES2();
+        int err = gl.glGetError(); // flush previous errors ..
+        if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
+            verboseOut.println("createAndCompileShader: Pre GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static void detachShader(GL gl, int program, IntBuffer shaders) {
-        getImpl(gl).detachShader(gl, program, shaders);
-    }
+        createShader(gl, shaderType, shader);
+        err = gl.glGetError(); 
+        if(err!=GL.GL_NO_ERROR) {
+            throw new GLException("createAndCompileShader: CreateShader failed, GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static void deleteShader(GL gl, IntBuffer shaders) {
-        getImpl(gl).deleteShader(gl, shaders);
-    }
+        shaderSource(gl, shader, sources);
+        err = gl.glGetError(); 
+        if(err!=GL.GL_NO_ERROR) {
+            throw new GLException("createAndCompileShader: ShaderSource failed, GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static boolean createAndLoadShader(GL gl, IntBuffer shader, int shaderType,
-                                              int binFormat, java.nio.Buffer bin,
-                                              PrintStream verboseOut) {
-        return getImpl(gl).createAndLoadShader(gl, shader, shaderType, binFormat, bin, verboseOut);
-    }
+        compileShader(gl, shader);
+        err = gl.glGetError(); 
+        if(err!=GL.GL_NO_ERROR && null!=verboseOut) {
+            verboseOut.println("createAndCompileShader: CompileShader failed, GL Error: 0x"+Integer.toHexString(err));
+        }
 
-    public static boolean createAndCompileShader(GL gl, IntBuffer shader, int shaderType,
-                                                 java.lang.String[][] sources, 
-                                                 PrintStream verboseOut) {
-        return getImpl(gl).createAndCompileShader(gl, shader, shaderType, sources, verboseOut);
+        return isShaderStatusValid(gl, shader, GL2ES2.GL_COMPILE_STATUS, verboseOut) && err == GL.GL_NO_ERROR;
     }
-
-    private static Impl getImpl(GL _gl) {
-        GL2ES2 gl = _gl.getGL2ES2();
-        GLContext context = gl.getContext();
-        Impl impl = (Impl) context.getAttachedObject(implObjectKey);
-        if (impl == null) {
-            impl = new GL2ES2Impl();
-            context.attachObject(implObjectKey, impl);
+    
+    private static final String implObjectKey = "com.jogamp.opengl.util.glsl.ShaderUtil" ;
+    
+    private static class ProfileInformation {
+        Boolean shaderCompilerAvailable = null;
+        Set<Integer> shaderBinaryFormats = null;
+    }    
+
+    private static ProfileInformation getProfileInformation(GL gl) {
+        final GLContext context = gl.getContext();
+        context.validateCurrent();
+        ProfileInformation data = (ProfileInformation) context.getAttachedObject(implObjectKey);
+        if (data == null) {
+            data = new ProfileInformation();
+            context.attachObject(implObjectKey, data);
         }
-        return impl;
+        return data;
     }
-    private static final String implObjectKey = "jogamp.opengl.glsl.ShaderUtilImpl" ;
 }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java
index 1f79890..a5b1c66 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/glsl/sdk/CompileShader.java
@@ -3,7 +3,6 @@ package com.jogamp.opengl.util.glsl.sdk;
 import com.jogamp.common.util.IOUtil;
 
 import javax.media.opengl.*;
-import com.jogamp.opengl.util.*;
 import com.jogamp.opengl.util.glsl.*;
 
 import java.io.*;
@@ -53,7 +52,7 @@ public abstract class CompileShader {
         String justName = basename(resourceName);
         outName = justName.substring(0, justName.length() - suffixLen) +
                   ShaderCode.getFileSuffix(true, type);
-        URL resourceURL = IOUtil.getResource(null, resourceName);
+        URL resourceURL = IOUtil.getResource(null, resourceName).getURL();
         String dirName = dirname(resourceURL.getPath());
 
         outName = dirName + File.separator + "bin" + File.separator + 
@@ -65,10 +64,10 @@ public abstract class CompileShader {
     public void processOneShader(String resourceName, String outName, int type)
         throws IOException, UnsupportedEncodingException, InterruptedException
     {
-        URL resourceURL = IOUtil.getResource(null, resourceName);
+        URL resourceURL = IOUtil.getResource(null, resourceName).getURL();
         String dirName = dirname(resourceURL.getPath());
 
-        String shader = ShaderCode.readShaderSource(null, resourceName);
+        CharSequence shader = ShaderCode.readShaderSource(null, resourceName, false);
         if(null==shader) {
             System.err.println("Can't find shader source " + resourceName + " - ignored");
             return;
@@ -93,7 +92,7 @@ public abstract class CompileShader {
         tmpDir.mkdirs();
         File tmpFile = new File(tmpDir, justName);
         Writer writer = new BufferedWriter(new FileWriter(tmpFile));
-        writer.write(shader, 0, shader.length());
+        writer.write(shader.toString(), 0, shader.length());
         writer.flush();
         writer.close();
         System.err.println("Preprocessed: "+ tmpFile.getAbsolutePath());
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java
index 7f3aa8a..a94b1f8 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/Texture.java
@@ -37,12 +37,13 @@
 package com.jogamp.opengl.util.texture;
 
 import java.nio.*;
-import java.security.*;
 
 import javax.media.opengl.*;
 import javax.media.opengl.glu.*;
 import javax.media.nativewindow.NativeWindowFactory;
+
 import jogamp.opengl.*;
+
 import com.jogamp.opengl.util.texture.spi.*;
 
 /**
@@ -168,14 +169,12 @@ public class Texture {
     /** An estimate of the amount of texture memory this texture consumes. */
     private int estimatedMemorySize;
 
-    private static final AccessControlContext localACC = AccessController.getContext();
-
     private static final boolean DEBUG = Debug.debug("Texture");
     private static final boolean VERBOSE = Debug.verbose();
 
     // For testing alternate code paths on more capable hardware
-    private static final boolean disableNPOT    = Debug.isPropertyDefined("jogl.texture.nonpot", true, localACC);
-    private static final boolean disableTexRect = Debug.isPropertyDefined("jogl.texture.notexrect", true, localACC);
+    private static final boolean disableNPOT    = Debug.isPropertyDefined("jogl.texture.nonpot", true);
+    private static final boolean disableTexRect = Debug.isPropertyDefined("jogl.texture.notexrect", true);
 
     public Texture(GL gl, TextureData data) throws GLException {
         texID = 0;
@@ -198,6 +197,7 @@ public class Texture {
         this.mustFlipVertically = mustFlipVertically;
         this.texWidth = texWidth;
         this.texHeight = texHeight;
+        aspectRatio = (float) imgWidth / (float) imgHeight;
         setImageSize(imgWidth, imgHeight, target);
     }
 
@@ -208,15 +208,23 @@ public class Texture {
      <pre>
      gl.glEnable(texture.getTarget());
      </pre>
-     *
+     * 
+     * <p>
+     * Call is ignored if {@link #getTarget()} is {@link GLES2#GL_TEXTURE_EXTERNAL_OES}.
+     * </p>
+     * <p>
      * See the <a href="#perftips">performance tips</a> above for hints
      * on how to maximize performance when using many Texture objects.
+     * </p>
+     * @param gl the current GL object
      *
      * @throws GLException if no OpenGL context was current or if any
      * OpenGL-related errors occurred
      */
     public void enable(GL gl) throws GLException {
-        gl.glEnable(target);
+        if(GLES2.GL_TEXTURE_EXTERNAL_OES != target) {
+            gl.glEnable(target);
+        }
     }
     
     /**
@@ -227,15 +235,22 @@ public class Texture {
      gl.glDisable(texture.getTarget());
      </pre>
      *
+     * <p>
+     * Call is ignored if {@link #getTarget()} is {@link GLES2#GL_TEXTURE_EXTERNAL_OES}.
+     * </p>
+     * <p>
      * See the <a href="#perftips">performance tips</a> above for hints
      * on how to maximize performance when using many Texture objects.
-     * @param gl TODO
+     * </p>
+     * @param gl the current GL object
      *
      * @throws GLException if no OpenGL context was current or if any
      * OpenGL-related errors occurred
      */
     public void disable(GL gl) throws GLException {
-        gl.glDisable(target); 
+        if(GLES2.GL_TEXTURE_EXTERNAL_OES != target) {
+            gl.glDisable(target);
+        }
     }
     
     /**
@@ -420,7 +435,7 @@ public class Texture {
      * 
      * @throws GLException if any OpenGL-related errors occurred
      */
-    public void updateImage(GL gl, TextureData data, int target) throws GLException {
+    public void updateImage(GL gl, TextureData data, int targetOverride) throws GLException {
         validateTexID(gl, true);
 
         imgWidth = data.getWidth();
@@ -539,10 +554,10 @@ public class Texture {
         texParamTarget = texTarget;
         setImageSize(imgWidth, imgHeight, texTarget);
 
-        if (target != 0) {
+        if (targetOverride != 0) {
             // Allow user to override auto detection and skip bind step (for
             // cubemap construction)
-            texTarget = target;
+            texTarget = targetOverride;
             if (this.target == 0) {
                 throw new GLException("Override of target failed; no target specified yet");
             }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java
index 8d8b367..3964703 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureCoords.java
@@ -61,6 +61,22 @@ public class TextureCoords {
         this.top = top;
     }
 
+    /** Transfers <code>{s * ss, t * ts}</code> from this object into the given <code>float[8+d_off]</code> in the following order:
+     * <pre>
+     *   left,  bottom
+     *   right, bottom
+     *   left,  top
+     *   right  top
+     * </pre>
+     */
+    public float[] getST_LB_RB_LT_RT(float[] d, int d_off, float ss, float ts) {
+        d[0+d_off] = left  *ss;  d[1+d_off] = bottom*ts;
+        d[2+d_off] = right *ss;  d[3+d_off] = bottom*ts;
+        d[4+d_off] = left  *ss;  d[5+d_off] = top   *ts;
+        d[6+d_off] = right *ss;  d[7+d_off] = top   *ts;
+        return d;
+    }
+    
     /** Returns the leftmost (x) texture coordinate of this
         rectangle. */
     public float left() { return left; }
@@ -76,4 +92,6 @@ public class TextureCoords {
     /** Returns the topmost (y) texture coordinate of this
         rectangle. */
     public float top() { return top; }
+    
+    public String toString() { return "TexCoord[h: "+left+" - "+right+", v: "+bottom+" - "+top+"]"; }
 }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java
index 149a2d4..928f91c 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureData.java
@@ -355,7 +355,7 @@ public class TextureData {
     }
 
     public String toString() {
-        return "TextureData["+width+"x"+height+", internFormat "+internalFormat+", pixelFormat "+pixelFormat+", pixelType "+pixelType+", border "+border+", estSize "+estimatedMemorySize+", alignment "+alignment+", rowlen "+rowLength;
+        return "TextureData["+width+"x"+height+", internFormat 0x"+Integer.toHexString(internalFormat)+", pixelFormat 0x"+Integer.toHexString(pixelFormat)+", pixelType 0x"+Integer.toHexString(pixelType)+", border "+border+", estSize "+estimatedMemorySize+", alignment "+alignment+", rowlen "+rowLength;
     }
 
     //----------------------------------------------------------------------
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java
index 5be7f92..d722100 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureIO.java
@@ -54,6 +54,7 @@ import java.util.List;
 
 import javax.media.opengl.GL;
 import javax.media.opengl.GL2;
+import javax.media.opengl.GL2GL3;
 import javax.media.opengl.GLContext;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
@@ -63,6 +64,7 @@ import jogamp.opengl.Debug;
 import com.jogamp.common.util.IOUtil;
 import com.jogamp.opengl.util.texture.spi.DDSImage;
 import com.jogamp.opengl.util.texture.spi.NetPbmTextureWriter;
+import com.jogamp.opengl.util.texture.spi.PNGImage;
 import com.jogamp.opengl.util.texture.spi.SGIImage;
 import com.jogamp.opengl.util.texture.spi.TGAImage;
 import com.jogamp.opengl.util.texture.spi.TextureProvider;
@@ -423,7 +425,7 @@ public class TextureIO {
 
     /** 
      * Creates an OpenGL texture object from the specified TextureData
-     * using the current OpenGL context.
+     * using the given OpenGL context.
      *
      * @param data the texture data to turn into an OpenGL texture
      * @throws GLException if no OpenGL context is current or if an
@@ -607,10 +609,10 @@ public class TextureIO {
 
         // First fetch the texture data
         GL _gl = GLContext.getCurrentGL();
-        if (!_gl.isGL2()) {
-            throw new GLException("Only GL2 supports fetching compressed images, GL: " + _gl);
+        if (!_gl.isGL2GL3()) {
+            throw new GLException("Implementation only supports GL2GL3 (Use GLReadBufferUtil and the TextureData variant), have: " + _gl);
         }
-        GL2 gl = _gl.getGL2();
+        GL2GL3 gl = _gl.getGL2();
 
         texture.bind(gl);
         int internalFormat = glGetTexLevelParameteri(gl, GL.GL_TEXTURE_2D, 0, GL2.GL_TEXTURE_INTERNAL_FORMAT);
@@ -639,7 +641,7 @@ public class TextureIO {
                 fetchedFormat = GL.GL_RGB;
                 break;
             case GL.GL_RGBA:
-            case GL2.GL_BGRA:
+            case GL.GL_BGRA:
             case GL2.GL_ABGR_EXT:
             case GL.GL_RGBA8:
                 bytesPerPixel = 4;
@@ -650,11 +652,11 @@ public class TextureIO {
             }
 
             // Fetch using glGetTexImage
-            int packAlignment  = glGetInteger(GL.GL_PACK_ALIGNMENT);
-            int packRowLength  = glGetInteger(GL2.GL_PACK_ROW_LENGTH);
-            int packSkipRows   = glGetInteger(GL2.GL_PACK_SKIP_ROWS);
-            int packSkipPixels = glGetInteger(GL2.GL_PACK_SKIP_PIXELS);
-            int packSwapBytes  = glGetInteger(GL2.GL_PACK_SWAP_BYTES);
+            int packAlignment  = glGetInteger(gl, GL.GL_PACK_ALIGNMENT);
+            int packRowLength  = glGetInteger(gl, GL2.GL_PACK_ROW_LENGTH);
+            int packSkipRows   = glGetInteger(gl, GL2.GL_PACK_SKIP_ROWS);
+            int packSkipPixels = glGetInteger(gl, GL2.GL_PACK_SKIP_PIXELS);
+            int packSwapBytes  = glGetInteger(gl, GL2.GL_PACK_SWAP_BYTES);
 
             gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1);
             gl.glPixelStorei(GL2.GL_PACK_ROW_LENGTH, 0);
@@ -690,8 +692,8 @@ public class TextureIO {
     }
   
     public static void write(TextureData data, File file) throws IOException, GLException {
-        for (Iterator iter = textureWriters.iterator(); iter.hasNext(); ) {
-            TextureWriter writer = (TextureWriter) iter.next();
+        for (Iterator<TextureWriter> iter = textureWriters.iterator(); iter.hasNext(); ) {
+            TextureWriter writer = iter.next();
             if (writer.write(file, data)) {
                 return;
             }
@@ -755,8 +757,8 @@ public class TextureIO {
     // Internals only below this point
     //
 
-    private static List/*<TextureProvider>*/ textureProviders = new ArrayList/*<TextureProvider>*/();
-    private static List/*<TextureWriter>*/   textureWriters   = new ArrayList/*<TextureWriter>*/();
+    private static List<TextureProvider> textureProviders = new ArrayList<TextureProvider>();
+    private static List<TextureWriter>   textureWriters   = new ArrayList<TextureWriter>();
 
     static {
         // ImageIO provider, the fall-back, must be the first one added
@@ -777,6 +779,7 @@ public class TextureIO {
         addTextureProvider(new DDSTextureProvider());
         addTextureProvider(new SGITextureProvider());
         addTextureProvider(new TGATextureProvider());
+        addTextureProvider(new PNGTextureProvider());
 
         // ImageIO writer, the fall-back, must be the first one added
         if(GLProfile.isAWTAvailable()) {
@@ -801,6 +804,7 @@ public class TextureIO {
         addTextureWriter(new SGITextureWriter());
         addTextureWriter(new TGATextureWriter());
         addTextureWriter(new NetPbmTextureWriter());
+        addTextureWriter(new PNGTextureWriter());
     }
 
     // Implementation methods
@@ -815,8 +819,8 @@ public class TextureIO {
 
         fileSuffix = toLowerCase(fileSuffix);
 
-        for (Iterator iter = textureProviders.iterator(); iter.hasNext(); ) {
-            TextureProvider provider = (TextureProvider) iter.next();
+        for (Iterator<TextureProvider> iter = textureProviders.iterator(); iter.hasNext(); ) {
+            TextureProvider provider = iter.next();
             TextureData data = provider.newTextureData(glp, file,
                                                        internalFormat,
                                                        pixelFormat,
@@ -846,8 +850,8 @@ public class TextureIO {
             stream = new BufferedInputStream(stream);
         }
 
-        for (Iterator iter = textureProviders.iterator(); iter.hasNext(); ) {
-            TextureProvider provider = (TextureProvider) iter.next();
+        for (Iterator<TextureProvider> iter = textureProviders.iterator(); iter.hasNext(); ) {
+            TextureProvider provider = iter.next();
             TextureData data = provider.newTextureData(glp, stream,
                                                        internalFormat,
                                                        pixelFormat,
@@ -872,8 +876,8 @@ public class TextureIO {
 
         fileSuffix = toLowerCase(fileSuffix);
 
-        for (Iterator iter = textureProviders.iterator(); iter.hasNext(); ) {
-            TextureProvider provider = (TextureProvider) iter.next();
+        for (Iterator<TextureProvider> iter = textureProviders.iterator(); iter.hasNext(); ) {
+            TextureProvider provider = iter.next();
             TextureData data = provider.newTextureData(glp, url,
                                                        internalFormat,
                                                        pixelFormat,
@@ -1096,13 +1100,49 @@ public class TextureIO {
                                           boolean mipmap,
                                           String fileSuffix) throws IOException {
             if (TGA.equals(fileSuffix)) {
-                TGAImage image = TGAImage.read(stream);
+                TGAImage image = TGAImage.read(glp, stream);
+                if (pixelFormat == 0) {
+                    pixelFormat = image.getGLFormat();
+                }
+                if (internalFormat == 0) {
+                    if(glp.isGL2GL3()) {
+                        internalFormat = GL.GL_RGBA8;
+                    } else {
+                        internalFormat = (image.getBytesPerPixel()==4)?GL.GL_RGBA:GL.GL_RGB;
+                    }
+                }
+                return new TextureData(glp, internalFormat,
+                                       image.getWidth(),
+                                       image.getHeight(),
+                                       0,
+                                       pixelFormat,
+                                       GL.GL_UNSIGNED_BYTE,
+                                       mipmap,
+                                       false,
+                                       false,
+                                       image.getData(),
+                                       null);
+            }
+
+            return null;
+        }
+    }
+
+    //----------------------------------------------------------------------
+    // PNG image provider
+    static class PNGTextureProvider extends StreamBasedTextureProvider {
+        public TextureData newTextureData(GLProfile glp, InputStream stream,
+                                          int internalFormat,
+                                          int pixelFormat,
+                                          boolean mipmap,
+                                          String fileSuffix) throws IOException {
+            if (PNG.equals(fileSuffix)) {
+                PNGImage image = PNGImage.read(/*glp, */ stream);
                 if (pixelFormat == 0) {
                     pixelFormat = image.getGLFormat();
                 }
                 if (internalFormat == 0) {
-                    GL gl = GLContext.getCurrentGL();
-                    if(gl.isGL2()) {
+                    if(glp.isGL2GL3()) {
                         internalFormat = GL.GL_RGBA8;
                     } else {
                         internalFormat = (image.getBytesPerPixel()==4)?GL.GL_RGBA:GL.GL_RGB;
@@ -1229,33 +1269,38 @@ public class TextureIO {
                 int pixelFormat = data.getPixelFormat();
                 int pixelType   = data.getPixelType();
                 if ((pixelFormat == GL.GL_RGB ||
-                     pixelFormat == GL.GL_RGBA) &&
+                     pixelFormat == GL.GL_RGBA || 
+                     pixelFormat == GL2.GL_BGR ||
+                     pixelFormat == GL.GL_BGRA ) &&
                     (pixelType == GL.GL_BYTE ||
                      pixelType == GL.GL_UNSIGNED_BYTE)) {
-                    ByteBuffer buf = ((data.getBuffer() != null) ?
-                                      (ByteBuffer) data.getBuffer() :
-                                      (ByteBuffer) data.getMipmapData()[0]);
-                    // Must reverse order of red and blue channels to get correct results
-                    int skip = ((pixelFormat == GL.GL_RGB) ? 3 : 4);
-                    for (int i = 0; i < buf.remaining(); i += skip) {
-                        byte red  = buf.get(i + 0);
-                        byte blue = buf.get(i + 2);
-                        buf.put(i + 0, blue);
-                        buf.put(i + 2, red);
+                    
+                    ByteBuffer buf = (ByteBuffer) data.getBuffer();
+                    if (null == buf) {
+                        buf = (ByteBuffer) data.getMipmapData()[0];
+                    }
+                    buf.rewind();
+                    
+                    if( pixelFormat == GL.GL_RGB || pixelFormat == GL.GL_RGBA ) { 
+                        // Must reverse order of red and blue channels to get correct results
+                        int skip = ((pixelFormat == GL.GL_RGB) ? 3 : 4);
+                        for (int i = 0; i < buf.remaining(); i += skip) {
+                            byte red  = buf.get(i + 0);
+                            byte blue = buf.get(i + 2);
+                            buf.put(i + 0, blue);
+                            buf.put(i + 2, red);
+                        }
                     }
 
                     TGAImage image = TGAImage.createFromData(data.getWidth(),
                                                              data.getHeight(),
-                                                             (pixelFormat == GL.GL_RGBA),
-                                                             false,
-                                                             ((data.getBuffer() != null) ?
-                                                              (ByteBuffer) data.getBuffer() :
-                                                              (ByteBuffer) data.getMipmapData()[0]));
+                                                             (pixelFormat == GL.GL_RGBA || pixelFormat == GL.GL_BGRA),
+                                                             false, buf);
                     image.write(file);
                     return true;
                 }
-
-                throw new IOException("TGA writer doesn't support this pixel format / type (only GL_RGB/A + bytes)");
+                throw new IOException("TGA writer doesn't support this pixel format 0x"+Integer.toHexString(pixelFormat)+
+                                      " / type 0x"+Integer.toHexString(pixelFormat)+" (only GL_RGB/A, GL_BGR/A + bytes)");
             }
 
             return false;
@@ -1263,17 +1308,71 @@ public class TextureIO {
     }
 
     //----------------------------------------------------------------------
+    // PNG texture writer
+  
+    static class PNGTextureWriter implements TextureWriter {
+        public boolean write(File file, TextureData data) throws IOException {
+            if (PNG.equals(IOUtil.getFileSuffix(file))) {
+                // See whether the PNG writer can handle this TextureData
+                int pixelFormat = data.getPixelFormat();
+                int pixelType   = data.getPixelType();
+                boolean reversedChannels;
+                int bytesPerPixel;
+                switch(pixelFormat) {
+                    case GL.GL_RGB:
+                        reversedChannels=false;
+                        bytesPerPixel=3;
+                        break;
+                    case GL.GL_RGBA:
+                        reversedChannels=false;
+                        bytesPerPixel=4;
+                        break;
+                    case GL2.GL_BGR:
+                        reversedChannels=true;
+                        bytesPerPixel=3;
+                        break;
+                    case GL.GL_BGRA:
+                        reversedChannels=true;
+                        bytesPerPixel=4;
+                        break;
+                    default:
+                        reversedChannels=false;
+                        bytesPerPixel=-1;
+                        break;
+                }
+                if ( 1 < bytesPerPixel &&
+                    (pixelType == GL.GL_BYTE ||
+                     pixelType == GL.GL_UNSIGNED_BYTE)) {
+                    
+                    ByteBuffer buf = (ByteBuffer) data.getBuffer();
+                    if (null == buf) {
+                        buf = (ByteBuffer) data.getMipmapData()[0];
+                    }
+                    buf.rewind();
+                    
+                    PNGImage image = PNGImage.createFromData(data.getWidth(), data.getHeight(), -1f, -1f,
+                                                             bytesPerPixel, reversedChannels, buf);
+                    image.write(file, true);
+                    return true;
+                }
+                throw new IOException("PNG writer doesn't support this pixel format 0x"+Integer.toHexString(pixelFormat)+
+                                      " / type 0x"+Integer.toHexString(pixelFormat)+" (only GL_RGB/A, GL_BGR/A + bytes)");
+            }
+            return false;
+        }    
+    }
+    
+    //----------------------------------------------------------------------
     // Helper routines
     //
 
-    private static int glGetInteger(int pname) {
+    private static int glGetInteger(GL gl, int pname) {
         int[] tmp = new int[1];
-        GL gl = GLContext.getCurrentGL();
         gl.glGetIntegerv(pname, tmp, 0);
         return tmp[0];
     }
 
-    private static int glGetTexLevelParameteri(GL2 gl, int target, int level, int pname) {
+    private static int glGetTexLevelParameteri(GL2GL3 gl, int target, int level, int pname) {
         int[] tmp = new int[1];
         gl.glGetTexLevelParameteriv(target, 0, pname, tmp, 0);
         return tmp[0];
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java
new file mode 100644
index 0000000..5ee2104
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/TextureSequence.java
@@ -0,0 +1,221 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.util.texture;
+
+import javax.media.opengl.GL;
+
+/**
+ * Protocol for texture sequences, like animations, movies, etc.
+ * <p>
+ * Ensure to respect the texture coordinates provided by 
+ * {@link TextureFrame}.{@link TextureFrame#getTexture() getTexture()}.{@link Texture#getImageTexCoords() getImageTexCoords()}.
+ * </p>
+ * The user's shader shall be fitted for this implementation. 
+ * Assuming we use a base shader code w/o headers using </code>ShaderCode</code>.
+ * (Code copied from unit test / demo <code>TexCubeES2</code>)
+ * <pre>
+ * 
+    static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" };
+    static final String gl2_prelude = "#version 110\n";
+    static final String shaderBasename = "texsequence_xxx";  // the base shader code w/o headers
+    static final String myTextureLookupName = "myTexture2D"; // the desired texture lookup function    
+    
+    private void initShader(GL2ES2 gl, TextureSequence texSeq) {
+        // Create & Compile the shader objects
+        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, TexCubeES2.class, 
+                                            "shader", "shader/bin", shaderBasename, true);
+        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, TexCubeES2.class, 
+                                            "shader", "shader/bin", shaderBasename, true);
+        
+        // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ]
+        int rsFpPos;
+        if(gl.isGLES2()) {
+            // insert ES2 version string in beginning
+            rsVp.insertShaderSource(0, 0, es2_prelude[0]);
+            rsFpPos = rsFp.insertShaderSource(0, 0, es2_prelude[0]);
+        } else {
+            // insert GL2 version string in beginning
+            rsVp.insertShaderSource(0, 0, gl2_prelude);
+            rsFpPos = rsFp.insertShaderSource(0, 0, gl2_prelude);
+        }
+        // insert required extensions as determined by TextureSequence implementation.
+        rsFpPos = rsFp.insertShaderSource(0, rsFpPos, texSeq.getRequiredExtensionsShaderStub());
+        if(gl.isGLES2()) {
+            // insert ES2 default precision declaration
+            rsFpPos = rsFp.insertShaderSource(0, rsFpPos, es2_prelude[1]);
+        }        
+        // negotiate the texture lookup function name
+        final String texLookupFuncName = texSeq.getTextureLookupFunctionName(myTextureLookupName);
+        
+        // in case a fixed lookup function is being chosen, replace the name in our code        
+        rsFp.replaceInShaderSource(myTextureLookupName, texLookupFuncName);
+        
+        // Cache the TextureSequence shader details in StringBuffer:
+        final StringBuilder sFpIns = new StringBuilder();
+        
+        // .. declaration of the texture sampler using the implementation specific type
+        sFpIns.append("uniform ").append(texSeq.getTextureSampler2DType()).append(" mgl_ActiveTexture;\n");
+        
+        // .. the actual texture lookup function, maybe null in case a built-in function is being used
+        sFpIns.append(texSeq.getTextureLookupFragmentShaderImpl());
+        
+        // Now insert the TextureShader details in our shader after the given tag:
+        rsFp.insertShaderSource(0, "TEXTURE-SEQUENCE-CODE-BEGIN", 0, sFpIns);
+        
+        // Create & Link the shader program
+        ShaderProgram sp = new ShaderProgram();
+        sp.add(rsVp);
+        sp.add(rsFp);
+        if(!sp.link(gl, System.err)) {
+            throw new GLException("Couldn't link program: "+sp);
+        }
+        ...
+ * </pre>
+ * The above procedure might look complicated, however, it allows most flexibility and
+ * workarounds to also deal with GLSL bugs.
+ *  
+ */
+public interface TextureSequence {
+    public static final String GL_OES_EGL_image_external_Required_Prelude = "#extension GL_OES_EGL_image_external : enable\n";
+    public static final String GL_OES_EGL_image_external = "GL_OES_EGL_image_external";
+    public static final String samplerExternalOES = "samplerExternalOES";
+    public static final String sampler2D = "sampler2D";
+    
+    /** 
+     * Texture holder interface, maybe specialized by implementation
+     * to associated related data. 
+     */
+    public static class TextureFrame {
+        public TextureFrame(Texture t) {
+            texture = t;
+        }
+        
+        public final Texture getTexture() { return texture; }
+        
+        public String toString() {
+            return "TextureFrame[" + texture + "]";
+        }
+        protected final Texture texture;
+    }
+
+    public interface TexSeqEventListener<T extends TextureSequence> {
+        /** 
+         * Signaling listeners that {@link TextureSequence#getNextTexture(GL, boolean)} is able to deliver a new frame.
+         * @param ts the event source 
+         * @param when system time in msec. 
+         **/
+        public void newFrameAvailable(T ts, long when);
+    }
+    
+    /** Return the texture unit to be used with this frame. */
+    public int getTextureUnit();
+
+    public int[] getTextureMinMagFilter();
+
+    public int[] getTextureWrapST();
+
+    /**
+     * Returns the last updated texture.
+     * <p>
+     * In case the instance is just initialized, it shall return a <code>TextureFrame</code>
+     * object with valid attributes. The texture content may be undefined 
+     * until the first call of {@link #getNextTexture(GL, boolean)}.<br>
+     * </p> 
+     * Not blocking.
+     *  
+     * @throws IllegalStateException if instance is not initialized 
+     */
+    public TextureFrame getLastTexture() throws IllegalStateException ;
+
+    /**
+     * Returns the next texture to be rendered. 
+     * <p>
+     * Implementation shall block until next frame is available if <code>blocking</code> is <code>true</code>,
+     * otherwise it shall return the last frame in case a new frame is not available.
+     * </p>
+     * <p>
+     * Shall return <code>null</code> in case <i>no</i> frame is available.
+     * </p>
+     *  
+     * @throws IllegalStateException if instance is not initialized 
+     */
+    public TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException ;
+    
+    /**
+     * In case a shader extension is required, based on the implementation 
+     * and the runtime GL profile, this method returns the preprocessor macros, e.g.:
+     * <pre>
+     * #extension GL_OES_EGL_image_external : enable
+     * </pre> 
+     *  
+     * @throws IllegalStateException if instance is not initialized 
+     */
+    public String getRequiredExtensionsShaderStub() throws IllegalStateException ;
+    
+    /** 
+     * Returns either <code>sampler2D</code> or <code>samplerExternalOES</code>
+     * depending on {@link #getLastTexture()}.{@link TextureFrame#getTexture() getTexture()}.{@link Texture#getTarget() getTarget()}. 
+     *  
+     * @throws IllegalStateException if instance is not initialized 
+     **/
+    public String getTextureSampler2DType() throws IllegalStateException ;
+    
+    /**
+     * @param desiredFuncName desired lookup function name. If <code>null</code> or ignored by the implementation,
+     *                        a build-in name is returned. 
+     * @return the final lookup function name
+     *  
+     * @see {@link #getTextureLookupFragmentShaderImpl()}
+     * 
+     * @throws IllegalStateException if instance is not initialized
+     */
+    public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException ;
+    
+    /**
+     * Returns the complete texture2D lookup function code of type
+     * <pre>
+     *   vec4 <i>funcName</i>(in <i>getTextureSampler2DType()</i> image, in vec2 texCoord) {
+     *      vec4 texColor = do_something_with(image, texCoord);
+     *      return texColor;
+     *   }
+     * </pre>
+     * <p>
+     * <i>funcName</i> can be negotiated and queried via {@link #getTextureLookupFunctionName(String)}.
+     * </p>
+     * Note: This function may return an empty string in case a build-in lookup
+     * function is being chosen. If the implementation desires so, 
+     * {@link #getTextureLookupFunctionName(String)} will ignore the desired function name
+     * and returns the build-in lookup function name.
+     * </p>
+     * @see #getTextureLookupFunctionName(String)
+     * @see #getTextureSampler2DType()
+     *  
+     * @throws IllegalStateException if instance is not initialized 
+     */
+    public String getTextureLookupFragmentShaderImpl() throws IllegalStateException ;    
+}
\ No newline at end of file
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java
index 39ec74b..ad96a99 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/awt/AWTTextureData.java
@@ -180,7 +180,7 @@ public class AWTTextureData extends TextureData {
         if (glp.isGL2GL3()) {
             switch (image.getType()) {
                 case BufferedImage.TYPE_INT_RGB:
-                    pixelFormat = GL2GL3.GL_BGRA;
+                    pixelFormat = GL.GL_BGRA;
                     pixelType = GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV;
                     rowLength = scanlineStride;
                     alignment = 4;
@@ -188,7 +188,7 @@ public class AWTTextureData extends TextureData {
                     setupLazyCustomConversion(image);
                     break;
                 case BufferedImage.TYPE_INT_ARGB_PRE:
-                    pixelFormat = GL2GL3.GL_BGRA;
+                    pixelFormat = GL.GL_BGRA;
                     pixelType = GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV;
                     rowLength = scanlineStride;
                     alignment = 4;
@@ -254,7 +254,7 @@ public class AWTTextureData extends TextureData {
                     setupLazyCustomConversion(image);
                     break;
                 case BufferedImage.TYPE_USHORT_555_RGB:
-                    pixelFormat = GL2GL3.GL_BGRA;
+                    pixelFormat = GL.GL_BGRA;
                     pixelType = GL2GL3.GL_UNSIGNED_SHORT_1_5_5_5_REV;
                     rowLength = scanlineStride;
                     alignment = 2;
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java
index e309216..3f91ae9 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/DDSImage.java
@@ -39,13 +39,21 @@
 
 package com.jogamp.opengl.util.texture.spi;
 
-import java.io.*;
-import java.nio.*;
-import java.nio.channels.*;
-
-import javax.media.opengl.*;
-import com.jogamp.opengl.util.*;
-import com.jogamp.opengl.util.texture.*;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+
+import javax.media.opengl.GL;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.opengl.util.GLBuffers;
 
 /** A reader and writer for DirectDraw Surface (.dds) files, which are
     used to describe textures. These files can contain multiple mipmap
@@ -274,7 +282,7 @@ public class DDSImage {
      * @throws java.io.IOException if an I/O exception occurred
      */
     public void write(File file) throws IOException {
-        FileOutputStream stream = new FileOutputStream(file);
+        FileOutputStream stream = IOUtil.getFileOutputStream(file, true);
         FileChannel chan = stream.getChannel();
         // Create ByteBuffer for header in case the start of our
         // ByteBuffer isn't actually memory-mapped
@@ -464,7 +472,7 @@ public class DDSImage {
         @return String format code
     */
     public static String getCompressionFormatName(int compressionFormat) {
-        StringBuffer buf = new StringBuffer();
+        StringBuilder buf = new StringBuilder();
         for (int i = 0; i < 4; i++) {
             char c = (char) (compressionFormat & 0xFF);
             buf.append(c);
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java
index ae96184..c2b131b 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/NetPbmTextureWriter.java
@@ -41,6 +41,7 @@ package com.jogamp.opengl.util.texture.spi;
 
 import java.io.*;
 import java.nio.*;
+import java.nio.channels.FileChannel;
 
 import javax.media.opengl.*;
 
@@ -81,10 +82,11 @@ public class NetPbmTextureWriter implements TextureWriter {
 
     public String getSuffix() { return (magic==6)?PPM:PAM; }
 
-    public boolean write(File file,
-                         TextureData data) throws IOException {
-
-        // file suffix selection 
+    public boolean write(File file, TextureData data) throws IOException {
+        boolean res;
+        final int magic_old = magic;
+        
+        // file suffix selection        
         if (0==magic) {
             if (PPM.equals(IOUtil.getFileSuffix(file))) {
                 magic = 6;
@@ -93,24 +95,52 @@ public class NetPbmTextureWriter implements TextureWriter {
             } else {
                 return false;
             }
+        }        
+        try {
+            res = writeImpl(file, data);
+        } finally {
+            magic = magic_old;
         }
-
-        final int pixelFormat = data.getPixelFormat();
+        return res;
+    }
+    
+    private boolean writeImpl(File file, TextureData data) throws IOException {
+        int pixelFormat = data.getPixelFormat();
         final int pixelType   = data.getPixelType();
         if ((pixelFormat == GL.GL_RGB ||
-             pixelFormat == GL.GL_RGBA) &&
+             pixelFormat == GL.GL_RGBA ||
+             pixelFormat == GL2.GL_BGR ||
+             pixelFormat == GL.GL_BGRA ) &&
             (pixelType == GL.GL_BYTE ||
              pixelType == GL.GL_UNSIGNED_BYTE)) {
     
-            int comps = ( pixelFormat == GL.GL_RGBA ) ? 4 : 3 ;
+            ByteBuffer buf = (ByteBuffer) data.getBuffer();
+            if (null == buf ) {
+                buf = (ByteBuffer) data.getMipmapData()[0];
+            }
+            buf.rewind();
+            
+            int comps = ( pixelFormat == GL.GL_RGBA || pixelFormat == GL.GL_BGRA ) ? 4 : 3 ;
+            
+            if( pixelFormat == GL2.GL_BGR || pixelFormat == GL.GL_BGRA ) { 
+                // Must reverse order of red and blue channels to get correct results
+                for (int i = 0; i < buf.remaining(); i += comps) {
+                    byte red  = buf.get(i + 0);
+                    byte blue = buf.get(i + 2);
+                    buf.put(i + 0, blue);
+                    buf.put(i + 2, red);
+                }
+                pixelFormat = ( 4 == comps ) ? GL.GL_RGBA : GL.GL_RGB;
+                data.setPixelFormat(pixelFormat);
+            }
 
             if(magic==6 && comps==4) {
                 throw new IOException("NetPbmTextureWriter magic 6 (PPM) doesn't RGBA pixel format, use magic 7 (PAM)");
             }
 
-            FileOutputStream fos = new FileOutputStream(file);
-
-            StringBuffer header = new StringBuffer();
+            FileOutputStream fos = IOUtil.getFileOutputStream(file, true);
+            
+            StringBuilder header = new StringBuilder();
             header.append("P");
             header.append(magic);
             header.append("\n");
@@ -139,30 +169,16 @@ public class NetPbmTextureWriter implements TextureWriter {
             }
 
             fos.write(header.toString().getBytes());
-                
-            ByteBuffer buf = (ByteBuffer) data.getBuffer();
-            if (buf == null) {
-                buf = (ByteBuffer) data.getMipmapData()[0];
-            }
-            buf.rewind();
-
-            byte[] bufArray = null;
-
-            try {
-                bufArray = buf.array();
-            } catch (Throwable t) {}
-            if(null==bufArray) {
-                bufArray = new byte[data.getWidth()*data.getHeight()*comps];
-                buf.get(bufArray);
-                buf.rewind();
-            }
-
-            fos.write(bufArray);
+            
+            FileChannel fosc = fos.getChannel();
+            fosc.write(buf);
+            fosc.force(true);
+            fosc.close();
             fos.close();
+            buf.rewind();
 
             return true;
-        }
-      
+        }      
         throw new IOException("NetPbmTextureWriter writer doesn't support this pixel format / type (only GL_RGB/A + bytes)");
     }
 }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java
new file mode 100644
index 0000000..a89418f
--- /dev/null
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/PNGImage.java
@@ -0,0 +1,172 @@
+package com.jogamp.opengl.util.texture.spi;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+import javax.media.opengl.GL;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.ImageLine;
+import jogamp.opengl.util.pngj.PngReader;
+import jogamp.opengl.util.pngj.PngWriter;
+import jogamp.opengl.util.pngj.chunks.PngChunkTextVar;
+
+import com.jogamp.common.nio.Buffers;
+import com.jogamp.common.util.IOUtil;
+
+
+public class PNGImage {    
+    /** Creates a PNGImage from data supplied by the end user. Shares
+        data with the passed ByteBuffer. Assumes the data is already in
+        the correct byte order for writing to disk, i.e., RGB or RGBA bottom-to-top (OpenGL coord). */
+    public static PNGImage createFromData(int width, int height, double dpiX, double dpiY,
+                                          int bytesPerPixel, boolean reversedChannels, ByteBuffer data) {
+        return new PNGImage(width, height, dpiX, dpiY, bytesPerPixel, reversedChannels, data);
+    }
+    
+    /** Reads a PNG image from the specified InputStream. */
+    public static PNGImage read(InputStream in) throws IOException {
+        return new PNGImage(in);
+    }
+    
+    /** Reverse read and store, implicitly flip image to GL coords. */
+    private static final int getPixelRGBA8(ByteBuffer d, int dOff, ImageLine line, int lineOff, boolean hasAlpha) {
+        if(hasAlpha) {
+            d.put(dOff--, (byte)line.scanline[lineOff + 3]); // A
+        }
+        d.put(dOff--, (byte)line.scanline[lineOff + 2]); // B
+        d.put(dOff--, (byte)line.scanline[lineOff + 1]); // G        
+        d.put(dOff--, (byte)line.scanline[lineOff    ]); // R
+        return dOff;
+    }    
+    /** Reverse read and store, implicitly flip image from GL coords. */
+    private static int setPixelRGBA8(ImageLine line, int lineOff, ByteBuffer d, int dOff, boolean hasAlpha, boolean reversedChannels) {
+        if(reversedChannels) {
+            line.scanline[lineOff    ] = d.get(dOff--); // R, A
+            line.scanline[lineOff + 1] = d.get(dOff--); // G, B
+            line.scanline[lineOff + 2] = d.get(dOff--); // B, G
+            if(hasAlpha) {
+                line.scanline[lineOff + 3] = d.get(dOff--);// R
+            }
+        } else {
+            if(hasAlpha) {
+                line.scanline[lineOff + 3] = d.get(dOff--); // A
+            }
+            line.scanline[lineOff + 2] = d.get(dOff--); // B
+            line.scanline[lineOff + 1] = d.get(dOff--); // G
+            line.scanline[lineOff    ] = d.get(dOff--); // R
+        }
+        return dOff;
+    }
+
+    private PNGImage(int width, int height, double dpiX, double dpiY, int bytesPerPixel, boolean reversedChannels, ByteBuffer data) {
+        pixelWidth=width;
+        pixelHeight=height;
+        dpi = new double[] { dpiX, dpiY };
+        if(4 == bytesPerPixel) {
+            glFormat = GL.GL_RGBA;
+        } else if (3 == bytesPerPixel) {
+            glFormat = GL.GL_RGB;
+        } else {
+            throw new InternalError("XXX: bytesPerPixel "+bytesPerPixel);
+        }
+        this.bytesPerPixel = bytesPerPixel;
+        this.reversedChannels = reversedChannels;
+        this.data = data;        
+    }
+    
+    private PNGImage(InputStream in) {
+        final PngReader pngr = new PngReader(new BufferedInputStream(in), null);
+        final int channels = pngr.imgInfo.channels;
+        if (3 > channels || channels > 4 ) {
+            throw new RuntimeException("PNGImage can only handle RGB/RGBA images for now. Channels "+channels);
+        }
+        bytesPerPixel=pngr.imgInfo.bytesPixel;
+        if (3 > bytesPerPixel || bytesPerPixel > 4 ) {
+            throw new RuntimeException("PNGImage can only handle RGB/RGBA images for now. BytesPerPixel "+bytesPerPixel);
+        }
+        pixelWidth=pngr.imgInfo.cols;
+        pixelHeight=pngr.imgInfo.rows;
+        dpi = new double[2];
+        {
+            final double[] dpi2 = pngr.getMetadata().getDpi();
+            dpi[0]=dpi2[0];
+            dpi[1]=dpi2[1];
+        }        
+        glFormat= ( 4 == bytesPerPixel ) ? GL.GL_RGBA : GL.GL_RGB;
+        data = Buffers.newDirectByteBuffer(bytesPerPixel * pixelWidth * pixelHeight);
+        reversedChannels = false; // RGB[A]
+        final boolean hasAlpha = 4 == bytesPerPixel;
+        int dataOff = bytesPerPixel * pixelWidth * pixelHeight - 1; // start at end-of-buffer, reverse store
+        for (int row = 0; row < pixelHeight; row++) {
+            final ImageLine l1 = pngr.readRow(row);
+            int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ;      // start w/ last pixel in line, reverse read
+            for (int j = pixelWidth - 1; j >= 0; j--) {
+                dataOff = getPixelRGBA8(data, dataOff, l1, lineOff, hasAlpha);
+                lineOff -= bytesPerPixel;
+            }
+        }
+        pngr.end();
+    }
+    private final int pixelWidth, pixelHeight, glFormat, bytesPerPixel;
+    private boolean reversedChannels;
+    private final double[] dpi;
+    private final ByteBuffer data;
+    
+    /** Returns the width of the image. */
+    public int getWidth()    { return pixelWidth; }
+
+    /** Returns the height of the image. */
+    public int getHeight()   { return pixelHeight; }
+
+    /** Returns true if data has the channels reversed to BGR or BGRA, otherwise RGB or RGBA is expected. */
+    public boolean getHasReversedChannels() { return reversedChannels; }
+    
+    /** Returns the dpi of the image. */
+    public double[] getDpi() { return dpi; }
+    
+    /** Returns the OpenGL format for this texture; e.g. GL.GL_BGR or GL.GL_BGRA. */
+    public int getGLFormat() { return glFormat; }
+
+    /** Returns the bytes per pixel */
+    public int getBytesPerPixel() { return bytesPerPixel; }
+
+    /** Returns the raw data for this texture in the correct
+        (bottom-to-top) order for calls to glTexImage2D. */
+    public ByteBuffer getData()  { return data; }
+
+    public void write(File out, boolean allowOverwrite) throws IOException {        
+        final ImageInfo imi = new ImageInfo(pixelWidth, pixelHeight, 8, (4 == bytesPerPixel) ? true : false); // 8 bits per channel, no alpha 
+        // open image for writing to a output stream
+        final OutputStream outs = new BufferedOutputStream(IOUtil.getFileOutputStream(out, allowOverwrite));
+        try {
+            final PngWriter png = new PngWriter(outs, imi); 
+            // add some optional metadata (chunks)
+            png.getMetadata().setDpi(dpi[0], dpi[1]);
+            png.getMetadata().setTimeNow(0); // 0 seconds fron now = now
+            png.getMetadata().setText(PngChunkTextVar.KEY_Title, "JogAmp PNGImage");
+            // png.getMetadata().setText("my key", "my text");
+            final boolean hasAlpha = 4 == bytesPerPixel;
+            final ImageLine l1 = new ImageLine(imi);
+            int dataOff = bytesPerPixel * pixelWidth * pixelHeight - 1; // start at end-of-buffer, reverse read
+            for (int row = 0; row < pixelHeight; row++) {
+                int lineOff = ( pixelWidth - 1 ) * bytesPerPixel ;      // start w/ last pixel in line, reverse store
+                for (int j = pixelWidth - 1; j >= 0; j--) {
+                    dataOff = setPixelRGBA8(l1, lineOff, data, dataOff, hasAlpha, reversedChannels);
+                    lineOff -= bytesPerPixel;
+                }
+                png.writeRow(l1, row);
+            }
+            png.end();
+        } finally {
+            IOUtil.close(outs, false);
+        }
+    }
+    
+    public String toString() { return "PNGImage["+pixelWidth+"x"+pixelHeight+", dpi "+dpi[0]+" x "+dpi[1]+", bytesPerPixel "+bytesPerPixel+", reversedChannels "+reversedChannels+", "+data+"]"; }       
+}
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java
index c60c91b..d35330f 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/SGIImage.java
@@ -41,7 +41,8 @@ package com.jogamp.opengl.util.texture.spi;
 
 import java.io.*;
 import javax.media.opengl.*;
-import com.jogamp.opengl.util.*;
+
+import com.jogamp.common.util.IOUtil;
 
 /** <p> Reads and writes SGI RGB/RGBA images. </p>
 
@@ -584,7 +585,7 @@ public class SGIImage {
         if (DEBUG) 
             System.err.println("total_size was " + total_size);
 
-        DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
+        DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(IOUtil.getFileOutputStream(file, true)));
 
         writeHeader(stream, xsize, ysize, zsize, true);
 
diff --git a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java
index 16ba538..e202c59 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/texture/spi/TGAImage.java
@@ -43,9 +43,8 @@ import java.io.*;
 import java.nio.*;
 import java.nio.channels.*;
 import javax.media.opengl.*;
-import com.jogamp.opengl.util.*;
-import com.jogamp.opengl.util.texture.spi.*;
-import com.jogamp.opengl.util.texture.*;
+
+import com.jogamp.common.util.IOUtil;
 
 /**
  * Targa image reader and writer adapted from sources of the <a href =
@@ -144,8 +143,6 @@ public class TGAImage {
         }
 
         Header(LEDataInputStream in) throws IOException {
-            int ret;
-
             tgaType = TYPE_OLD; // dont try and get footer.
 
             // initial header fields
@@ -252,7 +249,7 @@ public class TGAImage {
      * it into the JimiImage structure. This was taken from the
      * prototype and modified for the new Jimi structure
      */
-    private void decodeImage(LEDataInputStream dIn) throws IOException {
+    private void decodeImage(GLProfile glp, LEDataInputStream dIn) throws IOException {
         switch (header.imageType()) {
         case Header.UCOLORMAPPED:
             throw new IOException("TGADecoder Uncompressed Colormapped images not supported");
@@ -264,7 +261,7 @@ public class TGAImage {
 
             case 24:
             case 32:
-                decodeRGBImageU24_32(dIn);
+                decodeRGBImageU24_32(glp, dIn);
                 break;
             }
             break;
@@ -287,11 +284,9 @@ public class TGAImage {
      * This assumes that the body is for a 24 bit or 32 bit for a
      * RGB or ARGB image respectively.
      */
-    private void decodeRGBImageU24_32(LEDataInputStream dIn) throws IOException {
+    private void decodeRGBImageU24_32(GLProfile glp, LEDataInputStream dIn) throws IOException {
         int i;    // row index
-        int j;    // column index
         int y;    // output row index
-        int raw;  // index through the raw input buffer
         int rawWidth = header.width() * (header.pixelDepth() / 8);
         byte[] rawBuf = new byte[rawWidth];
         byte[] tmpData = new byte[rawWidth * header.height()];
@@ -307,10 +302,9 @@ public class TGAImage {
             System.arraycopy(rawBuf, 0, tmpData, y * rawWidth, rawBuf.length);
         }
 
-        GL gl = GLContext.getCurrentGL();
         if (header.pixelDepth() == 24) {
             bpp=3;
-            if(gl.isGL2GL3()) {
+            if(glp.isGL2GL3()) {
                 format = GL2GL3.GL_BGR;
             } else {
                 format = GL.GL_RGB;
@@ -319,9 +313,13 @@ public class TGAImage {
         } else {
             assert header.pixelDepth() == 32;
             bpp=4;
-
-            if(gl.isGL2GL3()) {
-                format = GL2GL3.GL_BGRA;
+            boolean useBGRA = glp.isGL2GL3();
+            if(!useBGRA) {
+                final GLContext ctx = GLContext.getCurrent();
+                useBGRA = null != ctx && ctx.isTextureFormatBGRA8888Available();
+            }
+            if( useBGRA ) {
+                format = GL.GL_BGRA;
             } else {
                 format = GL.GL_RGBA;
                 swapBGR(tmpData, rawWidth, header.height(), bpp);
@@ -362,17 +360,17 @@ public class TGAImage {
     public ByteBuffer getData()  { return data; }
 
     /** Reads a Targa image from the specified file. */
-    public static TGAImage read(String filename) throws IOException {
-        return read(new FileInputStream(filename));
+    public static TGAImage read(GLProfile glp, String filename) throws IOException {
+        return read(glp, new FileInputStream(filename));
     }
 
     /** Reads a Targa image from the specified InputStream. */
-    public static TGAImage read(InputStream in) throws IOException {
+    public static TGAImage read(GLProfile glp, InputStream in) throws IOException {
         LEDataInputStream dIn = new LEDataInputStream(new BufferedInputStream(in));
 
         Header header = new Header(dIn);
         TGAImage res = new TGAImage(header);
-        res.decodeImage(dIn);
+        res.decodeImage(glp, dIn);
         return res;
     }
 
@@ -383,7 +381,7 @@ public class TGAImage {
 
     /** Writes the image in Targa format to the specified file. */
     public void write(File file) throws IOException {
-        FileOutputStream stream = new FileOutputStream(file);
+        FileOutputStream stream = IOUtil.getFileOutputStream(file, true);
         FileChannel chan = stream.getChannel();
         ByteBuffer buf = ByteBuffer.allocate(header.size());
         buf.order(ByteOrder.LITTLE_ENDIAN);
@@ -391,10 +389,10 @@ public class TGAImage {
         buf.rewind();
         chan.write(buf);
         chan.write(data);
-        data.rewind();
         chan.force(true);
         chan.close();
         stream.close();
+        data.rewind();
     }
 
     /** Creates a TGAImage from data supplied by the end user. Shares
diff --git a/src/jogl/classes/com/jogamp/openmax/OMXEventListener.java b/src/jogl/classes/com/jogamp/openmax/OMXEventListener.java
deleted file mode 100644
index 08cfecc..0000000
--- a/src/jogl/classes/com/jogamp/openmax/OMXEventListener.java
+++ /dev/null
@@ -1,14 +0,0 @@
-
-package com.jogamp.openmax;
-
-public interface OMXEventListener {
-
-    static final int EVENT_CHANGE_SIZE = 1<<0;
-    static final int EVENT_CHANGE_FPS  = 1<<1;
-    static final int EVENT_CHANGE_BPS  = 1<<2;
-    static final int EVENT_CHANGE_LENGTH  = 1<<3;
-
-    public void changedAttributes(OMXInstance omx, int event_mask);
-
-}
-
diff --git a/src/jogl/classes/com/jogamp/openmax/OMXInstance.java b/src/jogl/classes/com/jogamp/openmax/OMXInstance.java
deleted file mode 100644
index fcd055f..0000000
--- a/src/jogl/classes/com/jogamp/openmax/OMXInstance.java
+++ /dev/null
@@ -1,509 +0,0 @@
-
-package com.jogamp.openmax;
-
-import javax.media.opengl.*;
-import javax.media.opengl.glu.GLU;
-import com.jogamp.opengl.util.texture.*;
-
-import jogamp.opengl.egl.EGL;
-import jogamp.opengl.egl.EGLContext;
-import jogamp.opengl.egl.EGLDrawable;
-import jogamp.opengl.egl.EGLExt;
-
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.*;
-
-public class OMXInstance {
-    private long moviePtr = 0;
-
-    protected String path   = null;
-    protected URL url   = null;
-    
-    // *** Texture impl
-    protected Texture texture = null; // holds the last fetched texture
-
-    protected float playSpeed = 1.0f;
-
-    /** 
-     * The following data is set by the setStream function,
-     * and may be set by the native OMX implementation,
-     * in case the stream attributes changes (see attributesUpdated)
-     */
-    protected int width = 0;
-    protected int height = 0;
-    protected int fps = 0; // frames per seconds
-    protected long bps = 0; // bits per seconds
-    protected long totalFrames = 0; // duration in frames
-    protected String acodec = null;
-    protected String vcodec = null;
-
-    /**
-     * Old stream values, before the last attributesUpdated)
-     */
-    protected int o_width = 0;
-    protected int o_height = 0;
-    protected int o_fps = 0; // frames per seconds
-    protected long o_bps = 0; // bits per seconds
-    protected long o_totalFrames = 0; // duration in frames
-    
-    static class EGLImageTexture {
-        public EGLImageTexture(com.jogamp.opengl.util.texture.Texture t, long i, long s) {
-            texture = t; image = i; sync = s;
-        }
-        public String toString() {
-            return "EGLImageTexture[" + texture + ", image " + image + ", sync "+sync+"]";
-        }
-        protected com.jogamp.opengl.util.texture.Texture texture;
-        protected long image;
-        protected long sync;
-    }
-    private EGLImageTexture[] eglImgTexs=null;
-    private HashMap eglImgTexsMap = new HashMap();
-    protected int textureNum;
-    
-    private EGLExt eglExt = null;
-    private long eglSurface = 0;
-    private long eglDisplay = 0;
-    private long eglContext = 0;
-    private int sWidth=0, sHeight=0;
-
-    private GL initGLData(GL gl) {
-        if(null==gl) {
-            throw new RuntimeException("No current GL");
-        }
-        EGLContext eglCtx = (EGLContext) gl.getContext();
-        if(null==eglCtx) {
-            throw new RuntimeException("No current EGL context");
-        }
-        EGLDrawable eglDrawable = (EGLDrawable) eglCtx.getGLDrawable();
-        if(null==eglDrawable) {
-            throw new RuntimeException("No valid drawable");
-        }
-        eglContext = eglCtx.getHandle();
-        eglDisplay = eglDrawable.getDisplay();
-        eglSurface = eglDrawable.getHandle();
-        eglExt = eglCtx.getEGLExt();
-        if(null==eglExt) {
-            throw new RuntimeException("No valid EGLExt");
-        }
-
-        int iTmp[] = new int[1];
-        EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_WIDTH, iTmp, 0);
-        sWidth=iTmp[0];
-        EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_HEIGHT, iTmp, 0);
-        sHeight=iTmp[0];
-        System.out.println("surface size: "+width+"x"+height);
-        System.out.println(eglDrawable);
-        System.out.println(eglCtx);
-        System.out.println("EGL Extensions : "+EGL.eglQueryString(eglDisplay, EGL.EGL_EXTENSIONS));
-        System.out.println("EGL CLIENT APIs: "+EGL.eglQueryString(eglDisplay, EGL.EGL_CLIENT_APIS));
-        return gl;
-    }
-
-    public OMXInstance() {
-        moviePtr = _createInstance();
-        if(0==moviePtr) {
-            throw new GLException("Couldn't create OMXInstance");
-        }
-    }
-    native long _createInstance();
-
-    public synchronized void setStream(int textureNum, URL u) {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        this.textureNum=textureNum;
-        url = u;
-        if (url == null) {
-            System.out.println("setURL (null)");
-            stop();
-            return;
-        }
-        path=null;
-        if (url.getProtocol() == null || "file".equals(url.getProtocol())) {
-            // CV only accepts absolute paths
-            try {
-                File file = new File(url.getPath());
-                if (!file.exists()) {
-                    throw new RuntimeException(new FileNotFoundException(file.toString()));
-                }
-                path = file.getCanonicalPath();
-                System.out.println("setURL: path "+path);
-            } catch (Exception e) {
-                e.printStackTrace();
-                throw new RuntimeException(e);
-            }
-        }
-        path = replaceAll(path, "\\", "/").trim();
-        if(null==path) {
-            throw new RuntimeException("Couldn't parse stream URL: "+url);
-        }
-        System.out.println("setURL: clean path "+path);
-
-        System.out.println("setURL: p1 "+this);
-        _setStream(moviePtr, textureNum, path);
-        System.out.println("setURL: p2 "+this);
-    }
-    native void _setStream(long moviePtr, int textureNum, String path);
-
-    public synchronized void setStreamAllEGLImageTexture2D(GL gl) {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        if(null==vcodec) {
-            return;
-        }
-        gl = initGLData(gl);
-
-        if(null!=eglImgTexs) {
-            removeAllEGLImageTexture2D(gl);
-        } else {
-            eglImgTexs = new EGLImageTexture[textureNum];
-        }
-
-        int[] tmp = new int[1];
-        int tex, e;
-
-        errorCheckGL(gl, "i.1");
-        gl.glEnable(gl.GL_TEXTURE_2D);
-        errorCheckGL(gl, "i.2");
-
-        for(int i=0; i<textureNum; i++) {
-            String s0 = String.valueOf(i);
-            gl.glGenTextures(1, tmp, 0);
-            tex=tmp[0];
-            if( (e=gl.glGetError()) != GL.GL_NO_ERROR || 0>tex ) {
-                throw new RuntimeException("TextureName creation failed: "+e);
-            }
-            gl.glBindTexture(gl.GL_TEXTURE_2D, tex);
-
-            // create space for buffer with a texture
-            gl.glTexImage2D(
-                    gl.GL_TEXTURE_2D, // target
-                    0,                // level
-                    gl.GL_RGBA,       // internal format
-                    width,            // width
-                    height,           // height
-                    0,                // border
-                    gl.GL_RGBA,       // format
-                    gl.GL_UNSIGNED_BYTE, // type
-                    null);            // pixels -- will be provided later
-            gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST);
-            gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST);
-
-            long image=0, sync=0;
-
-            // create EGLImage from texture
-            tmp[0] = EGL.EGL_NONE;
-            image = eglExt.eglCreateImageKHR(
-                        eglDisplay,
-                        eglContext,
-                        eglExt.EGL_GL_TEXTURE_2D_KHR,
-                        tex,
-                        tmp, 0);
-            if (0==image) {
-                throw new RuntimeException("EGLImage creation failed: "+EGL.eglGetError()+", dpy "+eglDisplay+", ctx "+eglContext+", tex "+tex);
-            }
-
-            // Create sync object so that we can be sure that gl has finished
-            // rendering the EGLImage texture before we tell OpenMAX to fill
-            // it with a new frame.
-            tmp[0] = EGL.EGL_NONE;
-            sync = eglExt.eglCreateSyncKHR(
-                    eglDisplay,
-                    eglExt.EGL_SYNC_FENCE_KHR, tmp, 0);
-
-            _setStreamEGLImageTexture2D(moviePtr, i, tex, image, sync);
-
-            eglImgTexs[i] = new EGLImageTexture(
-                com.jogamp.opengl.util.texture.TextureIO.newTexture(tex,
-                                                                 javax.media.opengl.GL2.GL_TEXTURE_2D,
-                                                                 width,
-                                                                 height,
-                                                                 width,
-                                                                 height,
-                                                                 true),
-                image, sync);
-            eglImgTexsMap.put(new Integer(tex), eglImgTexs[i]);
-        }
-        gl.glDisable(gl.GL_TEXTURE_2D);
-    }
-    native void _setStreamEGLImageTexture2D(long moviePtr, int i, int tex, long image, long sync);
-
-    public synchronized void activateStream() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        _activateStream(moviePtr);
-    }
-    native void _activateStream(long moviePtr);
-
-    public synchronized void detachVideoRenderer() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        _detachVideoRenderer(moviePtr);
-    }
-    native void _detachVideoRenderer(long moviePtr); // stop before
-
-    public synchronized void attachVideoRenderer() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        _attachVideoRenderer(moviePtr);
-    }
-    native void _attachVideoRenderer(long moviePtr); // detach before
-
-    public synchronized void setPlaySpeed(float rate) {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        _setPlaySpeed(moviePtr, rate);
-        playSpeed = rate;
-    }
-    public synchronized float getPlaySpeed() {
-        return playSpeed;
-    }
-    native void _setPlaySpeed(long moviePtr, float rate);
-
-    /** @return time position after issuing the command */
-    public synchronized float play() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        return _play(moviePtr);
-    }
-    native float _play(long moviePtr);
-
-    /** @return time position after issuing the command */
-    public synchronized float pause() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        return _pause(moviePtr);
-    }
-    native float _pause(long moviePtr);
-
-    /** @return time position after issuing the command */
-    public synchronized float stop() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        return _stop(moviePtr);
-    }
-    native float _stop(long moviePtr);
-
-    /** @return time position after issuing the command */
-    public synchronized float seek(float pos) {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        return _seek(moviePtr, pos);
-    }
-    native float _seek(long moviePtr, float position);
-
-    public synchronized Texture getLastTextureID() {
-        return texture;
-    }
-    public synchronized Texture getNextTextureID() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        texture=null;
-        EGLImageTexture eglImgTex = (EGLImageTexture) eglImgTexsMap.get(new Integer(_getNextTextureID(moviePtr)));
-        if(null!=eglImgTex) {
-            texture = eglImgTex.texture;
-        }
-        return texture;
-    }
-    native int  _getNextTextureID(long moviePtr);
-
-    public synchronized float getCurrentPosition() {
-        if(0==moviePtr) {
-            throw new GLException("OMX native instance null");
-        }
-        return _getCurrentPosition(moviePtr);
-    }
-    native float _getCurrentPosition(long moviePtr);
-
-    public synchronized void destroy(GL gl) {
-        removeAllEGLImageTexture2D(gl);
-        if (moviePtr != 0) {
-            long ptr = moviePtr;
-            moviePtr = 0;
-            _destroyInstance(ptr);
-
-            eglExt=null;
-            eglSurface=0;
-            eglDisplay=0;
-            eglContext=0;
-        }
-    }
-    protected synchronized void finalize() {
-        if (moviePtr != 0) {
-            destroy(null);
-        }
-    }
-    native void _destroyInstance(long moviePtr);
-
-    public synchronized boolean isValid() {
-        return (moviePtr != 0);
-    }
-    public synchronized String getPath() {
-        return path;
-    }
-    public synchronized URL getURL() {
-        return url;
-    }
-    public synchronized String getVideoCodec() {
-        return vcodec;
-    }
-    public synchronized String getAudioCodec() {
-        return acodec;
-    }
-    public synchronized long getTotalFrames() {
-        return totalFrames;
-    }
-    public synchronized long getBitrate() {
-        return bps;
-    }
-    public synchronized int getFramerate() {
-        return fps;
-    }
-    public synchronized int getWidth() {
-        return width;
-    }
-    public synchronized int getHeight() {
-        return height;
-    }
-    public synchronized String toString() {
-        return "OMXInstance [ stream [ video [ "+vcodec+", "+width+"x"+height+", "+fps+"fps, "+bps+"bsp, "+totalFrames+"f ] ] ]";
-    }
-
-    /**
-     * Java callback method issued by the native OMX backend
-     */
-    private void saveAttributes() {
-        o_width = width;
-        o_height = height;
-        o_fps = fps;
-        o_bps = bps;
-        o_totalFrames = totalFrames;
-    }
-
-    private void attributesUpdated() {
-        int event_mask = 0;
-        if( o_width != width || o_height != height ) {
-            event_mask |= OMXEventListener.EVENT_CHANGE_SIZE;
-        }   
-        if( o_fps != fps ) {
-            event_mask |= OMXEventListener.EVENT_CHANGE_FPS;
-        }
-        if( o_bps != bps ) {
-            event_mask |= OMXEventListener.EVENT_CHANGE_BPS;
-        }
-        if( o_totalFrames != totalFrames ) {
-            event_mask |= OMXEventListener.EVENT_CHANGE_LENGTH;
-        }
-        if(0==event_mask) {
-            return;
-        }
-
-        ArrayList listeners = null;
-        synchronized(this) {
-            listeners = eventListeners;
-        }
-        for(Iterator i = listeners.iterator(); i.hasNext(); ) {
-            OMXEventListener l = (OMXEventListener) i.next();
-            l.changedAttributes(this, event_mask);
-        }
-    }
-    
-    private String replaceAll(String orig, String search, String repl) {
-        String dest=null;
-        // In case replaceAll / java.util.regex.* is not supported (-> CVM)
-        int i=0,j;
-        dest = new String();
-        while((j=orig.indexOf(search, i))>=0) {
-            dest=dest.concat(orig.substring(i, j));
-            dest=dest.concat(repl);
-            i=j+1;
-        }
-        return dest.concat(orig.substring(i, orig.length()));
-    }
-
-    private void removeAllEGLImageTexture2D(GL gl) {
-        if (moviePtr != 0) {
-            if(null==eglExt) {
-                throw new RuntimeException("No valid EGLExt");
-            }
-
-            texture = null;
-            for(int i=0; i<textureNum; i++) {
-                if(null!=eglImgTexs[i]) {
-                    if(0!=eglImgTexs[i].image) {
-                        eglExt.eglDestroyImageKHR(
-                            eglDisplay,
-                            eglImgTexs[i].image);
-                    }
-                    if(0!=eglImgTexs[i].sync) {
-                        eglExt.eglDestroySyncKHR(eglDisplay, eglImgTexs[i].sync);
-                    }
-                    if(null!=gl) {
-                        eglImgTexs[i].texture.destroy(gl);
-                    }
-                    eglImgTexs[i]=null;
-                }
-            }
-            eglImgTexsMap.clear();
-        }
-    }
-
-    private void errorCheckGL(GL gl, String s) {
-        int e;
-        if( (e=gl.glGetError()) != GL.GL_NO_ERROR ) {
-            System.out.println("GL Error: ("+s+"): "+e);
-        }
-    }
-
-    private void errorCheckEGL(String s) {
-        int e;
-        if( (e=EGL.eglGetError()) != EGL.EGL_SUCCESS ) {
-            System.out.println("EGL Error: ("+s+"): "+e);
-        }
-    }
-
-    
-    //
-    // OMXEventListener Support
-    //
-
-    public synchronized void addEventListener(OMXEventListener l) {
-        if(l == null) {
-            return;
-        }
-        ArrayList newEventListeners = (ArrayList) eventListeners.clone();
-        newEventListeners.add(l);
-        eventListeners = newEventListeners;
-    }
-
-    public synchronized void removeEventListener(OMXEventListener l) {
-        if (l == null) {
-            return;
-        }
-        ArrayList newEventListeners = (ArrayList) eventListeners.clone();
-        newEventListeners.remove(l);
-        eventListeners = newEventListeners;
-    }
-
-    public synchronized OMXEventListener[] getEventListeners() {
-        return (OMXEventListener[]) eventListeners.toArray();
-    }
-
-    private ArrayList eventListeners = new ArrayList();
-
-}
-
diff --git a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java
index 1bb5094..f678c70 100644
--- a/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java
+++ b/src/jogl/classes/javax/media/opengl/DefaultGLCapabilitiesChooser.java
@@ -41,12 +41,11 @@
 package javax.media.opengl;
 
 import javax.media.nativewindow.NativeWindowException;
-import jogamp.opengl.Debug;
-
-import java.security.AccessController;
 import java.util.List;
 import javax.media.nativewindow.CapabilitiesImmutable;
 
+import jogamp.opengl.Debug;
+
 /** <P> The default implementation of the {@link
     GLCapabilitiesChooser} interface, which provides consistent visual
     selection behavior across platforms. The precise algorithm is
@@ -86,8 +85,23 @@ import javax.media.nativewindow.CapabilitiesImmutable;
 */
 
 public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser {
-  private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true, AccessController.getContext());
+  private static final boolean DEBUG = Debug.isPropertyDefined("jogl.debug.CapabilitiesChooser", true);
 
+  final static int NO_SCORE = -9999999;
+  final static int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000;
+  final static int OPAQUE_MISMATCH_PENALTY = 750;
+  final static int STENCIL_MISMATCH_PENALTY = 500;
+  final static int MULTISAMPLE_MISMATCH_PENALTY = 500;
+  final static int MULTISAMPLE_EXTENSION_MISMATCH_PENALTY = 250; // just a little drop, no scale
+  // Pseudo attempt to keep equal rank penalties scale-equivalent
+  // (e.g., stencil mismatch is 3 * accum because there are 3 accum
+  // components)
+  final static int COLOR_MISMATCH_PENALTY_SCALE     = 36;
+  final static int DEPTH_MISMATCH_PENALTY_SCALE     = 6;
+  final static int ACCUM_MISMATCH_PENALTY_SCALE     = 1;
+  final static int STENCIL_MISMATCH_PENALTY_SCALE   = 3;
+  final static int MULTISAMPLE_MISMATCH_PENALTY_SCALE   = 3;
+  
   public int chooseCapabilities(final CapabilitiesImmutable desired,
                                 final List /*<CapabilitiesImmutable>*/ available,
                                 final int windowSystemRecommendedChoice) {
@@ -122,20 +136,6 @@ public class DefaultGLCapabilitiesChooser implements GLCapabilitiesChooser {
 
     // Create score array
     int[] scores = new int[availnum];
-    final int NO_SCORE = -9999999;
-    final int DOUBLE_BUFFER_MISMATCH_PENALTY = 1000;
-    final int OPAQUE_MISMATCH_PENALTY = 750;
-    final int STENCIL_MISMATCH_PENALTY = 500;
-    final int MULTISAMPLE_MISMATCH_PENALTY = 500;
-    final int MULTISAMPLE_EXTENSION_MISMATCH_PENALTY = 250; // just a little drop, no scale
-    // Pseudo attempt to keep equal rank penalties scale-equivalent
-    // (e.g., stencil mismatch is 3 * accum because there are 3 accum
-    // components)
-    final int COLOR_MISMATCH_PENALTY_SCALE     = 36;
-    final int DEPTH_MISMATCH_PENALTY_SCALE     = 6;
-    final int ACCUM_MISMATCH_PENALTY_SCALE     = 1;
-    final int STENCIL_MISMATCH_PENALTY_SCALE   = 3;
-    final int MULTISAMPLE_MISMATCH_PENALTY_SCALE   = 3;
     
     for (int i = 0; i < scores.length; i++) {
       scores[i] = NO_SCORE;
diff --git a/src/jogl/classes/javax/media/opengl/GLArrayData.java b/src/jogl/classes/javax/media/opengl/GLArrayData.java
index 26f0f6b..7c56b53 100644
--- a/src/jogl/classes/javax/media/opengl/GLArrayData.java
+++ b/src/jogl/classes/javax/media/opengl/GLArrayData.java
@@ -28,7 +28,7 @@
 
 package javax.media.opengl;
 
-import java.nio.*;
+import java.nio.Buffer;
 
 /**
  *
@@ -129,7 +129,10 @@ public interface GLArrayData {
     public int getComponentSizeInBytes();
 
     /**
-     * The current number of used elements.<br>
+     * The current number of used elements.
+     * <p>
+     * On element consist out of {@link #getComponentCount()} components.
+     * </p>
      * In case the buffer's position is 0 (sealed, flipped), it's based on it's limit instead of it's position.
      */
     public int getElementCount();
diff --git a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java
index 9484f06..f0101a9 100644
--- a/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java
+++ b/src/jogl/classes/javax/media/opengl/GLAutoDrawable.java
@@ -41,7 +41,6 @@
 package javax.media.opengl;
 
 import jogamp.opengl.Debug;
-import java.security.*;
 
 /** A higher-level abstraction than {@link GLDrawable} which supplies
     an event based mechanism ({@link GLEventListener}) for performing
@@ -113,7 +112,7 @@ public interface GLAutoDrawable extends GLDrawable {
   /** Flag reflecting wheather the drawable reconfiguration will be issued in 
     * case a screen device change occured, e.g. in a multihead environment,
     * where you drag the window to another monitor. */
-  public static final boolean SCREEN_CHANGE_ACTION_ENABLED = Debug.getBooleanProperty("jogl.screenchange.action", true, AccessController.getContext());
+  public static final boolean SCREEN_CHANGE_ACTION_ENABLED = Debug.getBooleanProperty("jogl.screenchange.action", true);
 
   /**
    * Returns the context associated with this drawable. The returned
@@ -182,15 +181,15 @@ public interface GLAutoDrawable extends GLDrawable {
 
   /** 
    * <p>
-   * Enqueues a one-shot {@link javax.media.opengl.GLRunnable},
+   * Enqueues a one-shot {@link javax.media.opengl.GLRunnable GLRunnable},
    * which will be executed with the next {@link #display()} call.</p>
    * <p>
-   * If no {@link javax.media.opengl.GLAnimatorControl} is registered, or if it is not animating, the default situation,<br>
+   * If no {@link javax.media.opengl.GLAnimatorControl GLAnimatorControl} is animating (default),<br>
    * or if the current thread is the animator thread,<br>
    * a {@link #display()} call is issued after enqueue the <code>GLRunnable</code>.<br>
    * No extra synchronization is performed in case <code>wait</code> is true, since it is executed in the current thread.</p>
    * <p>
-   * If {@link javax.media.opengl.GLAnimatorControl} is registered and is animating,<br>
+   * If an {@link javax.media.opengl.GLAnimatorControl GLAnimatorControl} is animating,<br>
    * no {@link #display()} call is issued, since the animator thread performs it.<br>
    * If <code>wait</code> is true, the implementation waits until the <code>GLRunnable</code> is executed.<br>
    * </p><br>
@@ -218,7 +217,7 @@ public interface GLAutoDrawable extends GLDrawable {
    * <ul>
    *     <li> Calling {@link GLEventListener#display display(..)} for all
    *          registered {@link GLEventListener}s. </li>
-   *     <li> Executes all one-shot {@link javax.media.opengl.GLRunnable},
+   *     <li> Executes all one-shot {@link javax.media.opengl.GLRunnable GLRunnable},
    *          enqueued via {@link #invoke(boolean, GLRunnable)}.</li>
    * </ul></p>
    * <p> 
diff --git a/src/jogl/classes/javax/media/opengl/GLBase.java b/src/jogl/classes/javax/media/opengl/GLBase.java
index 534e449..bd24b15 100644
--- a/src/jogl/classes/javax/media/opengl/GLBase.java
+++ b/src/jogl/classes/javax/media/opengl/GLBase.java
@@ -29,8 +29,6 @@
 
 package javax.media.opengl;
 
-import java.nio.*;
-
 /**
  * <P>The base interface from which all GL profiles derive, providing
  * checked conversion down to concrete profiles, access to the
@@ -83,86 +81,80 @@ import java.nio.*;
 public interface GLBase {
     
   /**
-   * Indicates whether this GL object conforms to any of the common GL profiles.
-   * @return whether this GL object conforms to any of the common GL profiles
+   * Indicates whether this GL object conforms to any of the OpenGL profiles.
    */
   public boolean isGL();
 
   /**
-   * Indicates whether this GL object conforms to the GL4 compatibility profile.
-   * The GL4 compatibility profile merges the GL2 profile and GL4 core profile.
-   * @return whether this GL object conforms to the GL4 compatibility profile
+   * Indicates whether this GL object conforms to the OpenGL ≥ 4.0 compatibility profile.
+   * The GL4 compatibility profile includes the GL2, GL2ES1, GL2ES2, GL3, GL3bc and GL4 profile.
    */
   public boolean isGL4bc();
 
   /**
-   * Indicates whether this GL object conforms to the GL4 core profile.
-   * The GL4 core profile reflects OpenGL versions greater or equal 3.1
-   * @return whether this GL object conforms to the GL4 core profile
+   * Indicates whether this GL object conforms to the OpenGL ≥ 4.0 core profile.
+   * The GL4 core profile includes the GL2ES2, and GL3 profile.
    */
   public boolean isGL4();
 
   /**
-   * Indicates whether this GL object conforms to the GL3 compatibility profile.
-   * The GL3 compatibility profile merges the GL2 profile and GL3 core profile.
-   * @return whether this GL object conforms to the GL3 compatibility profile
+   * Indicates whether this GL object conforms to the OpenGL ≥ 3.1 compatibility profile.
+   * The GL3 compatibility profile includes the GL2, GL2ES1, GL2ES2 and GL3 profile.
    */
   public boolean isGL3bc();
 
   /**
-   * Indicates whether this GL object conforms to the GL3 core profile.
-   * The GL3 core profile reflects OpenGL versions greater or equal 3.1
-   * @return whether this GL object conforms to the GL3 core profile
+   * Indicates whether this GL object conforms to the OpenGL ≥ 3.1 core profile.
+   * The GL3 core profile includes the GL2ES2 profile.
    */
   public boolean isGL3();
 
   /**
-   * Indicates whether this GL object conforms to the GL2 profile.
-   * The GL2 profile reflects OpenGL versions greater or equal 1.5
-   * @return whether this GL object conforms to the GL2 profile
+   * Indicates whether this GL object conforms to the OpenGL ≤ 3.0 profile.
+   * The GL2 profile includes the GL2ES1 and GL2ES2 profile.
    */
   public boolean isGL2();
 
   /**
-   * Indicates whether this GL object conforms to the GLES1 profile.
-   * @return whether this GL object conforms to the GLES1 profile
+   * Indicates whether this GL object conforms to the OpenGL ES1 ≥ 1.0 profile.
    */
   public boolean isGLES1();
 
   /**
-   * Indicates whether this GL object conforms to the GLES2 profile.
-   * @return whether this GL object conforms to the GLES2 profile
+   * Indicates whether this GL object conforms to the OpenGL ES2 ≥ 2.0 profile.
+   * <p>
+   * Remark: ES2 compatible desktop profiles are not included.
+   * To query whether core ES2 functionality is provided, use {@link #isGLES2Compatible()}.
+   * </p> 
+   * @see #isGLES2Compatible()
    */
   public boolean isGLES2();
 
   /**
-   * Indicates whether this GL object conforms to one of the OpenGL ES compatible profiles.
-   * @return whether this GL object conforms to one of the OpenGL ES profiles
+   * Indicates whether this GL object conforms to one of the OpenGL ES profiles,
+   * see {@link #isGLES1()} and {@link #isGLES2()}.
    */
   public boolean isGLES();
 
   /**
-   * Indicates whether this GL object conforms to the GL2ES1 compatible profile.
-   * @return whether this GL object conforms to the GL2ES1 profile
+   * Indicates whether this GL object conforms to a GL2ES1 compatible profile.
    */
   public boolean isGL2ES1();
 
   /**
-   * Indicates whether this GL object conforms to the GL2ES2 compatible profile.
-   * @return whether this GL object conforms to the GL2ES2 profile
+   * Indicates whether this GL object conforms to a GL2ES2 compatible profile.
    */
   public boolean isGL2ES2();
 
   /**
-   * Indicates whether this GL object is compatible with OpenGL ES2.
+   * Indicates whether this GL object is compatible with the core OpenGL ES2 functionality.
    * @return true if this context is an ES2 context or implements 
    *         the extension <code>GL_ARB_ES2_compatibility</code>, otherwise false 
    */
   public boolean isGLES2Compatible();
 
   /**
-   * Indicates whether this GL object conforms to the GL2GL3 compatible profile.
-   * @return whether this GL object conforms to the GL2GL3 profile
+   * Indicates whether this GL object conforms to a GL2GL3 compatible profile.
    */
   public boolean isGL2GL3();
 
@@ -171,90 +163,77 @@ public interface GLBase {
 
   /**
    * Casts this object to the GL interface.
-   * @return this object cast to the GL interface
    * @throws GLException if this GLObject is not a GL implementation
    */
   public GL getGL() throws GLException;
 
   /**
    * Casts this object to the GL4bc interface.
-   * @return this object cast to the GL4bc interface
    * @throws GLException if this GLObject is not a GL4bc implementation
    */
   public GL4bc getGL4bc() throws GLException;
 
   /**
    * Casts this object to the GL4 interface.
-   * @return this object cast to the GL4 interface
    * @throws GLException if this GLObject is not a GL4 implementation
    */
   public GL4 getGL4() throws GLException;
 
   /**
    * Casts this object to the GL3bc interface.
-   * @return this object cast to the GL3bc interface
    * @throws GLException if this GLObject is not a GL3bc implementation
    */
   public GL3bc getGL3bc() throws GLException;
 
   /**
    * Casts this object to the GL3 interface.
-   * @return this object cast to the GL3 interface
    * @throws GLException if this GLObject is not a GL3 implementation
    */
   public GL3 getGL3() throws GLException;
 
   /**
    * Casts this object to the GL2 interface.
-   * @return this object cast to the GL2 interface
    * @throws GLException if this GLObject is not a GL2 implementation
    */
   public GL2 getGL2() throws GLException;
 
   /**
    * Casts this object to the GLES1 interface.
-   * @return this object cast to the GLES1 interface
    * @throws GLException if this GLObject is not a GLES1 implementation
    */
   public GLES1 getGLES1() throws GLException;
 
   /**
    * Casts this object to the GLES2 interface.
-   * @return this object cast to the GLES2 interface
    * @throws GLException if this GLObject is not a GLES2 implementation
    */
   public GLES2 getGLES2() throws GLException;
 
   /**
    * Casts this object to the GL2ES1 interface.
-   * @return this object cast to the GL2ES1 interface
    * @throws GLException if this GLObject is not a GL2ES1 implementation
    */
   public GL2ES1 getGL2ES1() throws GLException;
 
   /**
    * Casts this object to the GL2ES2 interface.
-   * @return this object cast to the GL2ES2 interface
    * @throws GLException if this GLObject is not a GL2ES2 implementation
    */
   public GL2ES2 getGL2ES2() throws GLException;
 
   /**
    * Casts this object to the GL2GL3 interface.
-   * @return this object cast to the GL2GL3 interface
    * @throws GLException if this GLObject is not a GL2GL3 implementation
    */
   public GL2GL3 getGL2GL3() throws GLException;
 
   /**
-   * Returns the GLProfile with which this GL object is associated.
-   * @return the GLProfile with which this GL object is associated
+   * Returns the GLProfile associated with this GL object.
    */
   public GLProfile getGLProfile();
 
   /**
-   * Returns the GLContext with which this GL object is associated.
-   * @return the GLContext with which this GL object is associated
+   * Returns the GLContext associated which this GL object.
    */
   public GLContext getContext();
 
diff --git a/src/jogl/classes/javax/media/opengl/GLCapabilities.java b/src/jogl/classes/javax/media/opengl/GLCapabilities.java
index 9022c7d..8b832b3 100644
--- a/src/jogl/classes/javax/media/opengl/GLCapabilities.java
+++ b/src/jogl/classes/javax/media/opengl/GLCapabilities.java
@@ -401,9 +401,9 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil
     return pbufferRenderToTextureRectangle;
   }
 
-  public StringBuffer toString(StringBuffer sink) {
+  public StringBuilder toString(StringBuilder sink) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
 
     int samples = sampleBuffers ? numSamples : 0 ;
@@ -448,7 +448,7 @@ public class GLCapabilities extends Capabilities implements Cloneable, GLCapabil
   /** Returns a textual representation of this GLCapabilities
       object. */ 
   public String toString() {
-    StringBuffer msg = new StringBuffer();
+    StringBuilder msg = new StringBuilder();
     msg.append("GLCaps[");
     toString(msg);
     msg.append("]");
diff --git a/src/jogl/classes/javax/media/opengl/GLContext.java b/src/jogl/classes/javax/media/opengl/GLContext.java
index 38c2d79..815da27 100644
--- a/src/jogl/classes/javax/media/opengl/GLContext.java
+++ b/src/jogl/classes/javax/media/opengl/GLContext.java
@@ -41,14 +41,14 @@
 package javax.media.opengl;
 
 import java.nio.IntBuffer;
-import java.security.AccessControlContext;
-import java.security.AccessController;
 import java.util.HashMap;
 import java.util.HashSet;
 
 import javax.media.nativewindow.AbstractGraphicsDevice;
 
 import com.jogamp.common.util.IntObjectHashMap;
+import com.jogamp.common.util.locks.LockFactory;
+import com.jogamp.common.util.locks.RecursiveLock;
 
 import jogamp.opengl.Debug;
 import jogamp.opengl.GLContextImpl;
@@ -66,18 +66,13 @@ import jogamp.opengl.GLContextImpl;
     abstraction provides a stable object which clients can use to
     refer to a given context. */
 public abstract class GLContext {
-  public static final boolean DEBUG = Debug.debug("GLContext");
-      
+  public static final boolean DEBUG = Debug.debug("GLContext");  
+  public static final boolean TRACE_SWITCH = Debug.isPropertyDefined("jogl.debug.GLContext.TraceSwitch", true);
+  
   /** Reflects property jogl.debug.DebugGL. If true, the debug pipeline is enabled at context creation. */
-  public final static boolean DEBUG_GL;
+  public final static boolean DEBUG_GL = Debug.isPropertyDefined("jogl.debug.DebugGL", true);
   /** Reflects property jogl.debug.TraceGL. If true, the trace pipeline is enabled at context creation. */
-  public final static boolean TRACE_GL;
-  
-  static { 
-      final AccessControlContext acl = AccessController.getContext();
-      DEBUG_GL = Debug.isPropertyDefined("jogl.debug.DebugGL", true, acl);
-      TRACE_GL = Debug.isPropertyDefined("jogl.debug.TraceGL", true, acl);
-  }
+  public final static boolean TRACE_GL = Debug.isPropertyDefined("jogl.debug.TraceGL", true);
   
   /** Indicates that the context was not made current during the last call to {@link #makeCurrent makeCurrent}. */
   public static final int CONTEXT_NOT_CURRENT = 0;
@@ -86,33 +81,33 @@ public abstract class GLContext {
   /** Indicates that a newly-created context was made current during the last call to {@link #makeCurrent makeCurrent}. */
   public static final int CONTEXT_CURRENT_NEW = 2;
 
-  /** <code>ARB_create_context</code> related: created via ARB_create_context */
-  protected static final int CTX_IS_ARB_CREATED = 1 << 0;
-  /** <code>ARB_create_context</code> related: compatibility profile */
-  protected static final int CTX_PROFILE_COMPAT = 1 << 1;
-  /** <code>ARB_create_context</code> related: core profile */
-  protected static final int CTX_PROFILE_CORE   = 1 << 2;
-  /** <code>ARB_create_context</code> related: ES profile */
-  protected static final int CTX_PROFILE_ES     = 1 << 3;
-  /** <code>ARB_create_context</code> related: flag forward compatible */
-  protected static final int CTX_OPTION_FORWARD = 1 << 4;
-  /** <code>ARB_create_context</code> related: flag not forward compatible */
-  protected static final int CTX_OPTION_ANY     = 1 << 5;
-  /** <code>ARB_create_context</code> related: flag debug */
-  public static final int CTX_OPTION_DEBUG   = 1 << 6;  
-  /** <code>GL_ARB_ES2_compatibility</code> related: Context is compatible w/ ES2 */
-  protected static final int CTX_PROFILE_ES2_COMPAT = 1 << 8;
-
-  /** GLContext {@link com.jogamp.gluegen.runtime.ProcAddressTable} caching related: GL software implementation */
-  protected static final int CTX_IMPL_ACCEL_SOFT = 1 << 0;
-  /** GLContext {@link com.jogamp.gluegen.runtime.ProcAddressTable} caching related: GL hardware implementation */
-  protected static final int CTX_IMPL_ACCEL_HARD = 1 << 1;
+  /** <code>ARB_create_context</code> related: created via ARB_create_context. Cache key value. */
+  protected static final int CTX_IS_ARB_CREATED  = 1 <<  0;
+  /** <code>ARB_create_context</code> related: compatibility profile. Cache key value. */
+  protected static final int CTX_PROFILE_COMPAT  = 1 <<  1;
+  /** <code>ARB_create_context</code> related: core profile. Cache key value. */
+  protected static final int CTX_PROFILE_CORE    = 1 <<  2;
+  /** <code>ARB_create_context</code> related: ES profile. Cache key value. */
+  protected static final int CTX_PROFILE_ES      = 1 <<  3;
+  /** <code>ARB_create_context</code> related: flag forward compatible. Cache key value. */
+  protected static final int CTX_OPTION_FORWARD  = 1 <<  4;
+  /** <code>ARB_create_context</code> related: flag debug. Not a cache key. */
+  public static final int CTX_OPTION_DEBUG       = 1 <<  5;
+  
+  /** <code>GL_ARB_ES2_compatibility</code> implementation related: Context is compatible w/ ES2. Not a cache key. */
+  protected static final int CTX_IMPL_ES2_COMPAT = 1 <<  8;
 
+  /** Context uses software rasterizer, otherwise hardware rasterizer. Cache key value. */
+  protected static final int CTX_IMPL_ACCEL_SOFT = 1 << 15;
+  
   private static ThreadLocal<GLContext> currentContext = new ThreadLocal<GLContext>();
 
   private HashMap<String, Object> attachedObjectsByString = new HashMap<String, Object>();
   private IntObjectHashMap attachedObjectsByInt = new IntObjectHashMap();
 
+  // RecursiveLock maintains a queue of waiting Threads, ensuring the longest waiting thread will be notified at unlock.  
+  protected RecursiveLock lock = LockFactory.createRecursiveLock();
+
   /** The underlying native OpenGL context */
   protected long contextHandle;
 
@@ -124,8 +119,13 @@ public abstract class GLContext {
   protected int ctxMinorVersion;
   protected int ctxOptions;
   protected String ctxVersionString;
+  private int currentSwapInterval;
 
   protected void resetStates() {
+      if (DEBUG) {
+        System.err.println(getThreadName() + ": GLContext.resetStates()");
+        // Thread.dumpStack();
+      }
       ctxMajorVersion=-1;
       ctxMinorVersion=-1;
       ctxOptions=0;
@@ -133,6 +133,7 @@ public abstract class GLContext {
       attachedObjectsByString.clear();
       attachedObjectsByInt.clear();
       contextHandle=0;
+      currentSwapInterval = -1;
   }
 
   /**
@@ -171,7 +172,7 @@ public abstract class GLContext {
 
   /**
    * Makes this GLContext current on the calling thread.
-   *
+   * <p>
    * There are two return values that indicate success and one that
    * indicates failure. A return value of CONTEXT_CURRENT_NEW
    * indicates that that context has been made current, and that
@@ -181,15 +182,22 @@ public abstract class GLContext {
    * this case, the application may wish to initialize the state.  A
    * return value of CONTEXT_CURRENT indicates that the context has
    * been made currrent, with its previous state restored.
-   * 
+   * </p>
+   * <p>
    * If the context could not be made current (for example, because
    * the underlying drawable has not ben realized on the display) ,
    * a value of CONTEXT_NOT_CURRENT is returned.
-   *
+   * </p>
+   * <p> 
    * If the context is in use by another thread at the time of the
    * call, then if isSynchronized() is true the call will
    * block. If isSynchronized() is false, an exception will be
    * thrown and the context will remain current on the other thread.
+   * </p>
+   * <p>
+   * The drawable's surface is being locked at entry
+   * and unlocked at {@link #release()} 
+   * </p>
    *
    * @return CONTEXT_CURRENT if the context was successfully made current
    * @return CONTEXT_CURRENT_NEW if the context was successfully made
@@ -206,6 +214,10 @@ public abstract class GLContext {
 
   /**
    * Releases control of this GLContext from the current thread.
+   * <p>
+   * The drawable's surface is being unlocked at exit,
+   * assumed to be locked by {@link #makeCurrent()}. 
+   * </p>
    *
    * @throws GLException if the context had not previously been made
    * current on the current thread
@@ -252,7 +264,7 @@ public abstract class GLContext {
   public static GL getCurrentGL() throws GLException {
     GLContext glc = getCurrent();
     if(null==glc) {
-        throw new GLException("No OpenGL context current on this thread");
+        throw new GLException(getThreadName()+": No OpenGL context current on this thread");
     }
     return glc.getGL();
   }
@@ -280,7 +292,7 @@ public abstract class GLContext {
    */
   public final void validateCurrent() throws GLException {  
     if(getCurrent() != this) {
-        throw new GLException("Given GL context not current");
+        throw new GLException(getThreadName()+": This context is not current. Current context: "+getCurrent()+", this context "+this);
     }
   }
   
@@ -290,13 +302,19 @@ public abstract class GLContext {
    * new GLContext implementations; not for use by end users.
    */
   protected static void setCurrent(GLContext cur) {
+    if(TRACE_SWITCH) {
+       System.err.println(getThreadName()+": GLContext.ContextSwitch: - setCurrent() - "+cur);
+    }
     currentContext.set(cur);
   }
   
   /**
    * Destroys this OpenGL context and frees its associated
-   * resources. The context should have been released before this
-   * method is called.
+   * resources.
+   * <p>
+   * The context may be current w/o recursion when calling <code>destroy()</code>,
+   * in which case this method destroys the context and releases the lock.
+   * </p> 
    */
   public abstract void destroy();
 
@@ -378,7 +396,7 @@ public abstract class GLContext {
    * Classname, GL, GLDrawable
    */
   public String toString() {
-    StringBuffer sb = new StringBuffer();
+    StringBuilder sb = new StringBuilder();
     sb.append(getClass().getSimpleName());
     sb.append(" [");
     this.append(sb);
@@ -386,7 +404,7 @@ public abstract class GLContext {
     return sb.toString();
   }
 
-  public final StringBuffer append(StringBuffer sb) {
+  public final StringBuilder append(StringBuilder sb) {
     sb.append("OpenGL ");
     sb.append(getGLVersionMajor());
     sb.append(".");
@@ -408,15 +426,48 @@ public abstract class GLContext {
         sb.append(",\n\tDrawable: ");
         sb.append(getGLDrawable());
     }
+    sb.append(", lock ");
+    sb.append(lock.toString());
     return sb;
   }
 
+  /**
+   * Returns true if the specified OpenGL core- or extension-function can be
+   * successfully called using this GL context given the current host (OpenGL
+   * <i>client</i>) and display (OpenGL <i>server</i>) configuration.
+   *
+   * See {@link GL#isFunctionAvailable(String)} for more details.
+   *
+   * @param glFunctionName the name of the OpenGL function (e.g., use
+   * "glPolygonOffsetEXT" or "glPolygonOffset" to check if the {@link
+   * javax.media.opengl.GL#glPolygonOffset(float,float)} is available).
+   */
+  public abstract boolean isFunctionAvailable(String glFunctionName);
+  
+  /**
+   * Returns true if the specified OpenGL extension can be
+   * successfully called using this GL context given the current host (OpenGL
+   * <i>client</i>) and display (OpenGL <i>server</i>) configuration.
+   *
+   * See {@link GL#isExtensionAvailable(String)} for more details.
+   *
+   * @param glExtensionName the name of the OpenGL extension (e.g.,
+   * "GL_VERTEX_PROGRAM_ARB").
+   */
+  public abstract boolean isExtensionAvailable(String glExtensionName);
+  
+  /** Returns the number of platform extensions */
+  public abstract int getPlatformExtensionCount();
+  
   /** Returns a non-null (but possibly empty) string containing the
       space-separated list of available platform-dependent (e.g., WGL,
       GLX) extensions. Can only be called while this context is
       current. */
   public abstract String getPlatformExtensionsString();
 
+  /** Returns the number of OpenGL extensions */
+  public abstract int getGLExtensionCount();
+  
   /** Returns a non-null (but possibly empty) string containing the
       space-separated list of available extensions.
       Can only be called while this context is current.
@@ -425,14 +476,6 @@ public abstract class GLContext {
    */
   public abstract String getGLExtensionsString();
 
-  public final int getGLVersionMajor() { return ctxMajorVersion; }
-  public final int getGLVersionMinor() { return ctxMinorVersion; }
-  public final boolean isGLCompatibilityProfile() { return ( 0 != ( CTX_PROFILE_COMPAT & ctxOptions ) ); }
-  public final boolean isGLCoreProfile()          { return ( 0 != ( CTX_PROFILE_CORE   & ctxOptions ) ); }
-  public final boolean isGLForwardCompatible()    { return ( 0 != ( CTX_OPTION_FORWARD & ctxOptions ) ); }
-  public final boolean isGLDebugEnabled()         { return ( 0 != ( CTX_OPTION_DEBUG & ctxOptions ) ); }
-  public final boolean isCreatedWithARBMethod()   { return ( 0 != ( CTX_IS_ARB_CREATED & ctxOptions ) ); }
-
   /**
    * @return Additional context creation flags, supported: {@link GLContext#CTX_OPTION_DEBUG}.
    */
@@ -456,13 +499,15 @@ public abstract class GLContext {
    * <ul>
    *   <li> options
    *   <ul>
-   *     <li> <code>old</code> refers to the non ARB_create_context created context</li>
-   *     <li> <code>new</code> refers to the ARB_create_context created context</li>
-   *     <li> <code>compatible profile</code></li>
-   *     <li> <code>core profile</code></li>
-   *     <li> <code>forward compatible</code></li>
-   *     <li> <code>any</code> refers to the non forward compatible context</li>
-   *     <li> <code>ES</code>  refers to the GLES context variant</li>
+   *     <li> <code>ES profile</code> ES profile</li>
+   *     <li> <code>Compatibility profile</code> Compatibility profile including fixed function pipeline and deprecated functionality</li>
+   *     <li> <code>Core profile</code> Core profile</li>
+   *     <li> <code>forward</code> Forward profile excluding deprecated functionality</li>
+   *     <li> <code>arb</code> refers to an ARB_create_context created context</li>
+   *     <li> <code>debug</code> refers to a debug context</li>
+   *     <li> <code>ES2 compatible</code> refers to an ES2 compatible implementation</li>
+   *     <li> <code>software</code> refers to a software implementation of the rasterizer</li>
+   *     <li> <code>hardware</code> refers to a hardware implementation of the rasterizer</li>
    *   </ul></li>
    *   <li> <i>gl-version</i> the GL_VERSION string</li>
    * </ul>
@@ -477,19 +522,52 @@ public abstract class GLContext {
    * </table> 
    *
    * <table border="0">
-   *     <tr><td></td>   <td>ES2</td>  <td><code>2.0 (ES, any, new) - 2.0 ES Profile</code></td></tr>
-   *     <tr><td>ATI</td><td>GL2</td>  <td><code>3.0 (compatibility profile, any, new) - 3.2.9704 Compatibility Profile Context</code></td></tr>
-   *     <tr><td>ATI</td><td>GL3</td>  <td><code>3.3 (core profile, any, new) - 1.4 (3.2.9704 Compatibility Profile Context)</code></td></tr>
-   *     <tr><td>ATI</td><td>GL3bc</td><td><code>3.3 (compatibility profile, any, new) - 1.4 (3.2.9704 Compatibility Profile Context)</code></td></tr>
-   *     <tr><td>NV</td><td>GL2</td>   <td><code>3.0 (compatibility profile, any, new) - 3.0.0 NVIDIA 195.36.07.03</code></td></tr>
-   *     <tr><td>NV</td><td>GL3</td>   <td><code>3.3 (core profile, any, new) - 3.3.0 NVIDIA 195.36.07.03</code></td></tr>
-   *     <tr><td>NV</td><td>GL3bc</td> <td><code>3.3 (compatibility profile, any, new) - 3.3.0 NVIDIA 195.36.07.03</code></td></tr>
+   *     <tr><td></td>   <td>ES2</td>  <td><code>2.0 (ES profile, ES2 compatible, hardware) - 2.0 ES Profile</code></td></tr>
+   *     <tr><td>ATI</td><td>GL2</td>  <td><code>3.0 (Compatibility profile, arb, hardware) - 3.2.9704 Compatibility Profile Context</code></td></tr>
+   *     <tr><td>ATI</td><td>GL3</td>  <td><code>3.3 (Core profile, any, new, hardware) - 1.4 (3.2.9704 Compatibility Profile Context)</code></td></tr>
+   *     <tr><td>ATI</td><td>GL3bc</td><td><code>3.3 (Compatibility profile, arb, hardware) - 1.4 (3.2.9704 Compatibility Profile Context)</code></td></tr>
+   *     <tr><td>NV</td><td>GL2</td>   <td><code>3.0 (Compatibility profile, arb, hardware) - 3.0.0 NVIDIA 195.36.07.03</code></td></tr>
+   *     <tr><td>NV</td><td>GL3</td>   <td><code>3.3 (Core profile, arb, hardware) - 3.3.0 NVIDIA 195.36.07.03</code></td></tr>
+   *     <tr><td>NV</td><td>GL3bc</td> <td><code>3.3 (Compatibility profile, arb, hardware) - 3.3.0 NVIDIA 195.36.07.03</code></td></tr>
+   *     <tr><td>NV</td><td>GL2</td>   <td><code>3.0 (Compatibility profile, arb, ES2 compatible, hardware) - 3.0.0 NVIDIA 290.10</code></td></tr>
    * </table> 
    */
   public final String getGLVersion() {
     return ctxVersionString;
   }
 
+  public final int getGLVersionMajor() { return ctxMajorVersion; }
+  public final int getGLVersionMinor() { return ctxMinorVersion; }
+  public final boolean isGLCompatibilityProfile() { return ( 0 != ( CTX_PROFILE_COMPAT & ctxOptions ) ); }
+  public final boolean isGLCoreProfile()          { return ( 0 != ( CTX_PROFILE_CORE   & ctxOptions ) ); }
+  public final boolean isGLForwardCompatible()    { return ( 0 != ( CTX_OPTION_FORWARD & ctxOptions ) ); }
+  public final boolean isGLDebugEnabled()         { return ( 0 != ( CTX_OPTION_DEBUG   & ctxOptions ) ); }
+  public final boolean isCreatedWithARBMethod()   { return ( 0 != ( CTX_IS_ARB_CREATED & ctxOptions ) ); }
+  
+  /**
+   * @return true if this context is an ES2 context or implements 
+   *         the extension <code>GL_ARB_ES2_compatibility</code>, otherwise false 
+   */
+  public final boolean isGLES2Compatible() {
+      return 0 != ( ctxOptions & CTX_IMPL_ES2_COMPAT ) ;
+  }
+  
+  public final boolean hasGLSL() {
+      return isGL2ES2() ;
+  }
+  
+  /** Note: The GL impl. may return a const value, ie {@link GLES2#isNPOTTextureAvailable()} always returns <code>true</code>. */
+  public boolean isNPOTTextureAvailable() {
+      return isGL3() || isGLES2Compatible() || isExtensionAvailable(GL_ARB_texture_non_power_of_two);
+  }
+  private static final String GL_ARB_texture_non_power_of_two = "GL_ARB_texture_non_power_of_two";
+  
+  public boolean isTextureFormatBGRA8888Available() {
+      return isGL2GL3() || 
+             isExtensionAvailable("GL_EXT_texture_format_BGRA8888") || 
+             isExtensionAvailable("GL_IMG_texture_format_BGRA8888") ;
+  }
+
   public final boolean isGL4bc() {
       return ctxMajorVersion>=4 && 0 != (ctxOptions & CTX_IS_ARB_CREATED)
                                 && 0 != (ctxOptions & CTX_PROFILE_COMPAT);
@@ -541,43 +619,61 @@ public abstract class GLContext {
   }
 
   /**
-   * @return true if this context is an ES2 context or implements 
-   *         the extension <code>GL_ARB_ES2_compatibility</code>, otherwise false 
+   * Set the swap interval if the current context.
+   * @param interval Should be ≥ 0. 0 Disables the vertical synchronisation, 
+   *                 where ≥ 1 is the number of vertical refreshes before a swap buffer occurs.
+   *                 A value < 0 is ignored.
+   * @return true if the operation was successful, otherwise false 
+   *  
+   * @throws GLException if the context is not current.
    */
-  public final boolean isGLES2Compatible() {
-      return 0 != ( ctxOptions & CTX_PROFILE_ES2_COMPAT ) ;
-  }
-  
-  public final boolean hasGLSL() {
-      return isGL2ES2() ;
-  }
-
-  public final void setSwapInterval(int interval) {
-    if (!isCurrent()) {
-        throw new GLException("This context is not current. Current context: "+getCurrent()+", this context "+this);
+  public final boolean setSwapInterval(int interval) throws GLException {
+    validateCurrent();
+    if(0<=interval) {
+        if( setSwapIntervalImpl(interval) ) {
+            currentSwapInterval = interval;
+            return true;
+        }
+    }
+    return false;
+  }
+  protected boolean setSwapIntervalImpl(int interval) { 
+      return false; 
+  }    
+  /** Return the current swap interval. 
+   * <p>
+   * If the context has not been made current at all,
+   * the default value <code>-1</code> is returned.
+   * </p>
+   * <p>
+   * The default value for a valid context is <code>1</code> for 
+   * an EGL based profile (ES1 or ES2) and <code>-1</code> (undefined)
+   * for desktop.
+   * </p>
+   */
+  public final int getSwapInterval() {
+    if(-1 == currentSwapInterval && this.isGLES()) {
+        currentSwapInterval = 1;
     }
-    setSwapIntervalImpl(interval);
-  }
-  protected void setSwapIntervalImpl(int interval) { /** nop per default .. **/  }
-  protected int currentSwapInterval = -1; // default: not set yet ..
-  public int getSwapInterval() {
     return currentSwapInterval;
   }
+  protected final void setDefaultSwapInterval() {
+    if(this.isGLES()) {
+        currentSwapInterval = 1;
+    } else {
+        currentSwapInterval = -1;
+    }      
+  }
   
   public final boolean queryMaxSwapGroups(int[] maxGroups, int maxGroups_offset,
                                           int[] maxBarriers, int maxBarriers_offset) {
-      
-    if (!isCurrent()) {
-        throw new GLException("This context is not current. Current context: "+getCurrent()+", this context "+this);
-    }
+    validateCurrent();
     return queryMaxSwapGroupsImpl(maxGroups, maxGroups_offset, maxBarriers, maxBarriers_offset);
   }
   protected boolean queryMaxSwapGroupsImpl(int[] maxGroups, int maxGroups_offset,
                                           int[] maxBarriers, int maxBarriers_offset) { return false; }
   public final boolean joinSwapGroup(int group) {
-    if (!isCurrent()) {
-        throw new GLException("This context is not current. Current context: "+getCurrent()+", this context "+this);
-    }
+    validateCurrent();
     return joinSwapGroupImpl(group);
   }
   protected boolean joinSwapGroupImpl(int group) { /** nop per default .. **/  return false; }
@@ -586,9 +682,7 @@ public abstract class GLContext {
       return currentSwapGroup;
   }
   public final boolean bindSwapBarrier(int group, int barrier) {
-    if (!isCurrent()) {
-        throw new GLException("This context is not current. Current context: "+getCurrent()+", this context "+this);
-    }
+    validateCurrent();
     return bindSwapBarrierImpl(group, barrier);    
   }
   protected boolean bindSwapBarrierImpl(int group, int barrier) { /** nop per default .. **/  return false; }
@@ -727,29 +821,10 @@ public abstract class GLContext {
       return true;
   }
 
-  protected static int compose8bit(int one, int two, int three, int four) {
-    return  ( ( one   & 0x000000FF ) << 24 ) |
-            ( ( two   & 0x000000FF ) << 16 ) |
-            ( ( three & 0x000000FF ) <<  8 ) |
-            ( ( four  & 0x000000FF )       ) ;
-  }
-
-  protected static int getComposed8bit(int bits32, int which ) {
-    switch (which) {
-        case 1: return ( bits32 & 0xFF000000 ) >> 24 ;
-        case 2: return ( bits32 & 0x00FF0000 ) >> 16 ;
-        case 3: return ( bits32 & 0x0000FF00 ) >>  8 ;
-        case 4: return ( bits32 & 0xFF0000FF )       ;
-    }
-    throw new GLException("argument which out of range: "+which);
-  }
-
-  protected static String composed8BitToString(int bits32, boolean hex1, boolean hex2, boolean hex3, boolean hex4) {
-    int a = getComposed8bit(bits32, 1);
-    int b = getComposed8bit(bits32, 2);
-    int c = getComposed8bit(bits32, 3);
-    int d = getComposed8bit(bits32, 4);
-    return "["+toString(a, hex1)+", "+toString(b, hex2)+", "+toString(c, hex3)+", "+toString(d, hex4)+"]";
+  protected static int composeBits(int a8, int b8, int c16) {
+    return  ( ( a8    & 0x000000FF ) << 24 ) |
+            ( ( b8    & 0x000000FF ) << 16 ) |
+            ( ( c16   & 0x0000FFFF )       ) ;
   }
 
   private static void validateProfileBits(int bits, String argName) {
@@ -777,7 +852,7 @@ public abstract class GLContext {
   private static /*final*/ HashSet<String> deviceVersionsAvailableSet = new HashSet<String>();
 
   protected static String getDeviceVersionAvailableKey(AbstractGraphicsDevice device, int major, int profile) {
-      return device.getUniqueID() + "-" + toHexString(compose8bit(major, profile, 0, 0));
+      return device.getUniqueID() + "-" + toHexString(composeBits(major, profile, 0));
   }
 
   protected static boolean getAvailableGLVersionsSet(AbstractGraphicsDevice device) {
@@ -794,8 +869,7 @@ public abstract class GLContext {
           }
           deviceVersionsAvailableSet.add(devKey);
           if (DEBUG) {
-            System.err.println(getThreadName() + ": !!! createContextARB: SET mappedVersionsAvailableSet "+devKey);
-            // Thread.dumpStack();
+            System.err.println(getThreadName() + ": createContextARB: SET mappedVersionsAvailableSet "+devKey);
           }
       }
   }
@@ -826,15 +900,21 @@ public abstract class GLContext {
     validateProfileBits(resCtp, "resCtp");
 
     String key = getDeviceVersionAvailableKey(device, reqMajor, profile);
-    Integer val = new Integer(compose8bit(resMajor, resMinor, resCtp, 0));
+    Integer val = new Integer(composeBits(resMajor, resMinor, resCtp));
     synchronized(deviceVersionAvailable) {
         val = deviceVersionAvailable.put( key, val );
     }
     return val;
   }
 
-  protected static Integer getAvailableGLVersion(AbstractGraphicsDevice device, int reqMajor, int profile)  {
-    String key = getDeviceVersionAvailableKey(device, reqMajor, profile);
+  /**
+   * @param device the device to request whether the profile is available for
+   * @param reqMajor Key Value either 1, 2, 3 or 4
+   * @param reqProfile Key Value either {@link #CTX_PROFILE_COMPAT}, {@link #CTX_PROFILE_CORE} or {@link #CTX_PROFILE_ES}
+   * @return the available GL version as encoded with {@link #composeBits(int, int, int), otherwise <code>null</code>
+   */
+  protected static Integer getAvailableGLVersion(AbstractGraphicsDevice device, int reqMajor, int reqProfile)  {
+    String key = getDeviceVersionAvailableKey(device, reqMajor, reqProfile);
     Integer val;
     synchronized(deviceVersionAvailable) {
         val = deviceVersionAvailable.get( key );
@@ -849,62 +929,107 @@ public abstract class GLContext {
    * @param minor if not null, returns the used minor version
    * @param ctp if not null, returns the used context profile
    */
-  protected static boolean getAvailableGLVersion(AbstractGraphicsDevice device,
-                                                 int reqMajor, int reqProfile, int[] major, int minor[], int ctp[]) {
+  protected static boolean getAvailableGLVersion(AbstractGraphicsDevice device, int reqMajor, int reqProfile, 
+                                                 int[] major, int minor[], int ctp[]) {
 
     Integer valI = getAvailableGLVersion(device, reqMajor, reqProfile);
     if(null==valI) {
         return false;
     }
 
-    int val = valI.intValue();
+    int bits32 = valI.intValue();
 
     if(null!=major) {
-        major[0] = getComposed8bit(val, 1);
+        major[0] = ( bits32 & 0xFF000000 ) >> 24 ;
     }
     if(null!=minor) {
-        minor[0] = getComposed8bit(val, 2);
+        minor[0] = ( bits32 & 0x00FF0000 ) >> 16 ;
     }
     if(null!=ctp) {
-        ctp[0]   = getComposed8bit(val, 3);
+        ctp[0]   = ( bits32 & 0x0000FFFF )       ;
     }
     return true;
   }
-
-  /**
+  
+  /** 
+   * returns the highest GLProfile string regarding the implementation version and context profile bits.
+   * @throws GLException if version and context profile bits could not be mapped to a GLProfile
+   */
+  protected static String getGLProfile(int major, int minor, int ctp) 
+          throws GLException {
+    if(0 != ( CTX_PROFILE_COMPAT & ctp )) {        
+        if(major >= 4)                            { return GLProfile.GL4bc; }
+        else if(major == 3 && minor >= 1)         { return GLProfile.GL3bc; }
+        else                                      { return GLProfile.GL2; }        
+    } else if(0 != ( CTX_PROFILE_CORE & ctp )) {
+        if(major >= 4)                            { return GLProfile.GL4; }
+        else if(major == 3 && minor >= 1)         { return GLProfile.GL3; }        
+    } else if(0 != ( CTX_PROFILE_ES & ctp )) {
+        if(major == 2)                            { return GLProfile.GLES2; }
+        else if(major == 1)                       { return GLProfile.GLES1; }                
+    }
+    throw new GLException("Unhandled OpenGL version/profile: "+GLContext.getGLVersion(major, minor, ctp, null));
+  }
+  
+  /** 
    * @param major Key Value either 1, 2, 3 or 4
    * @param profile Key Value either {@link #CTX_PROFILE_COMPAT}, {@link #CTX_PROFILE_CORE} or {@link #CTX_PROFILE_ES}
+   * @return the highest GLProfile string regarding the version and profile bits.
+   * @throws GLException if version and context profile bits could not be mapped to a GLProfile
+   */  
+  public static String getAvailableGLProfile(AbstractGraphicsDevice device, int reqMajor, int reqProfile) 
+          throws GLException {
+    int major[] = { 0 };
+    int minor[] = { 0 };
+    int ctp[] = { 0 };
+    if(GLContext.getAvailableGLVersion(device, reqMajor, reqProfile, major, minor, ctp)) {
+        return GLContext.getGLProfile(major[0], minor[0], ctp[0]);
+    }
+    return null;
+  }
+
+  /**
+   * @param device the device to request whether the profile is available for
+   * @param reqMajor Key Value either 1, 2, 3 or 4
+   * @param reqProfile Key Value either {@link #CTX_PROFILE_COMPAT}, {@link #CTX_PROFILE_CORE} or {@link #CTX_PROFILE_ES}
+   * @param isHardware return value of one boolean, whether the profile is a hardware rasterizer or not
+   * @return true if the requested GL version is available regardless of a software or hardware rasterizer, otherwise false.
    */
-  public static boolean isGLVersionAvailable(AbstractGraphicsDevice device, int major, int profile) {
-      return null != getAvailableGLVersion(device, major, profile);
+  public static boolean isGLVersionAvailable(AbstractGraphicsDevice device, int reqMajor, int reqProfile, boolean isHardware[]) {
+      Integer valI = getAvailableGLVersion(device, reqMajor, reqProfile);
+      if(null==valI) {
+          return false;
+      }
+      isHardware[0] = 0 == ( valI.intValue() & GLContext.CTX_IMPL_ACCEL_SOFT ) ;
+      return true;
   }
 
-  public static boolean isGLES1Available(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 1, GLContext.CTX_PROFILE_ES);
+  public static boolean isGLES1Available(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 1, GLContext.CTX_PROFILE_ES, isHardware);
   }
 
-  public static boolean isGLES2Available(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 2, GLContext.CTX_PROFILE_ES);
+  public static boolean isGLES2Available(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 2, GLContext.CTX_PROFILE_ES, isHardware);
   }
 
-  public static boolean isGL4bcAvailable(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 4, CTX_PROFILE_COMPAT);
+  public static boolean isGL4bcAvailable(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 4, CTX_PROFILE_COMPAT, isHardware);
   }
 
-  public static boolean isGL4Available(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 4, CTX_PROFILE_CORE);
+  public static boolean isGL4Available(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 4, CTX_PROFILE_CORE, isHardware);
   }
 
-  public static boolean isGL3bcAvailable(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 3, CTX_PROFILE_COMPAT);
+  public static boolean isGL3bcAvailable(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 3, CTX_PROFILE_COMPAT, isHardware);
   }
 
-  public static boolean isGL3Available(AbstractGraphicsDevice device) {
-      return isGLVersionAvailable(device, 3, CTX_PROFILE_CORE);
+  public static boolean isGL3Available(AbstractGraphicsDevice device, boolean isHardware[]) {
+      return isGLVersionAvailable(device, 3, CTX_PROFILE_CORE, isHardware);
   }
 
-  public static boolean isGL2Available(AbstractGraphicsDevice device) {
-    return isGLVersionAvailable(device, 2, CTX_PROFILE_COMPAT);
+  public static boolean isGL2Available(AbstractGraphicsDevice device, boolean isHardware[]) {
+    return isGLVersionAvailable(device, 2, CTX_PROFILE_COMPAT, isHardware);
   }
 
   /**
@@ -928,15 +1053,18 @@ public abstract class GLContext {
     sb.append(".");
     sb.append(minor);
     sb.append(" (");
-    needColon = appendString(sb, "ES",                    needColon, 0 != ( CTX_PROFILE_ES & ctp ));
-    needColon = appendString(sb, "ES2 compatible",        needColon, 0 != ( CTX_PROFILE_ES2_COMPAT & ctp ));
-    needColon = appendString(sb, "compatibility profile", needColon, 0 != ( CTX_PROFILE_COMPAT & ctp ));
-    needColon = appendString(sb, "core profile",          needColon, 0 != ( CTX_PROFILE_CORE & ctp ));
-    needColon = appendString(sb, "forward compatible",    needColon, 0 != ( CTX_OPTION_FORWARD & ctp ));
+    needColon = appendString(sb, "ES profile",            needColon, 0 != ( CTX_PROFILE_ES & ctp ));
+    needColon = appendString(sb, "Compatibility profile", needColon, 0 != ( CTX_PROFILE_COMPAT & ctp ));
+    needColon = appendString(sb, "Core profile",          needColon, 0 != ( CTX_PROFILE_CORE & ctp ));
+    needColon = appendString(sb, "forward",               needColon, 0 != ( CTX_OPTION_FORWARD & ctp )); 
+    needColon = appendString(sb, "arb",                   needColon, 0 != ( CTX_IS_ARB_CREATED & ctp ));
     needColon = appendString(sb, "debug",                 needColon, 0 != ( CTX_OPTION_DEBUG & ctp ));    
-    needColon = appendString(sb, "any",                   needColon, 0 != ( CTX_OPTION_ANY & ctp ));
-    needColon = appendString(sb, "new",                   needColon, 0 != ( CTX_IS_ARB_CREATED & ctp ));
-    needColon = appendString(sb, "old",                   needColon, 0 == ( CTX_IS_ARB_CREATED & ctp ));
+    needColon = appendString(sb, "ES2 compatible",        needColon, 0 != ( CTX_IMPL_ES2_COMPAT & ctp ));
+    if( 0 != ( CTX_IMPL_ACCEL_SOFT & ctp ) ) {
+        needColon = appendString(sb, "software",          needColon, true);
+    } else {
+        needColon = appendString(sb, "hardware",          needColon, true);
+    }
     sb.append(")");
     if(null!=gl_version) {
         sb.append(" - ");
@@ -949,13 +1077,6 @@ public abstract class GLContext {
   // internal string utils 
   //
   
-  protected static String toString(int val, boolean hex) {
-    if(hex) {
-        return "0x" + Integer.toHexString(val);
-    }
-    return String.valueOf(val);
-  }
-
   protected static String toHexString(int hex) {
     return "0x" + Integer.toHexString(hex);
   }
diff --git a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java
index 3f97004..1093685 100644
--- a/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java
+++ b/src/jogl/classes/javax/media/opengl/GLDrawableFactory.java
@@ -46,7 +46,6 @@ import java.util.ArrayList;
 import java.util.List;
 
 import com.jogamp.common.JogampRuntimeException;
-import jogamp.common.Debug;
 
 import com.jogamp.common.util.ReflectionUtil;
 
@@ -56,6 +55,8 @@ import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.nativewindow.ProxySurface;
 import javax.media.opengl.GLProfile.ShutdownType;
 
+import jogamp.opengl.Debug;
+
 /** <P> Provides a virtual machine- and operating system-independent
     mechanism for creating {@link GLDrawable}s. </P>
 
@@ -122,7 +123,7 @@ public abstract class GLDrawableFactory {
     
     final String nativeOSType = NativeWindowFactory.getNativeWindowType(true);
     GLDrawableFactory tmp = null;
-    String factoryClassName = Debug.getProperty("jogl.gldrawablefactory.class.name", true, AccessController.getContext());
+    String factoryClassName = Debug.getProperty("jogl.gldrawablefactory.class.name", true);
     ClassLoader cl = GLDrawableFactory.class.getClassLoader();
     if (null == factoryClassName) {
         if ( nativeOSType.equals(NativeWindowFactory.TYPE_X11) ) {
@@ -240,13 +241,22 @@ public abstract class GLDrawableFactory {
    * Retrieve the default <code>device</code> {@link AbstractGraphicsDevice#getConnection() connection},
    * {@link AbstractGraphicsDevice#getUnitID() unit ID} and {@link AbstractGraphicsDevice#getUniqueID() unique ID name}. for this factory<br>
    * The implementation must return a non <code>null</code> default device, which must not be opened, ie. it's native handle is <code>null</code>.
+   * <p>
+   * This method shall return the default device if available
+   * even if the GLDrawableFactory is not functional and hence not compatible. 
+   * The latter situation may happen because no native OpenGL implementation is available for the specific implementation.
+   * </p>
    * @return the default shared device for this factory, eg. :0.0 on X11 desktop.
+   * @see #getIsDeviceCompatible(AbstractGraphicsDevice)
    */
   public abstract AbstractGraphicsDevice getDefaultDevice();
 
   /**
    * @param device which {@link javax.media.nativewindow.AbstractGraphicsDevice#getConnection() connection} denotes the shared the target device, may be <code>null</code> for the platform's default device.
-   * @return true if the device is compatible with this factory, ie. if it can be used for creation. Otherwise false.
+   * @return true if the device is compatible with this factory, ie. if it can be used for GLDrawable creation. Otherwise false.
+   *         This implies validation whether the implementation is functional.
+   *         
+   * @see #getDefaultDevice()
    */
   public abstract boolean getIsDeviceCompatible(AbstractGraphicsDevice device);
 
@@ -257,11 +267,15 @@ public abstract class GLDrawableFactory {
               throw new InternalError("no default device");
           }
           if (GLProfile.DEBUG) {
-              System.err.println("Info: GLDrawableFactory.validateDevice: using default device : "+device);
+              System.err.println("Info: "+getClass().getSimpleName()+".validateDevice: using default device : "+device);
           }
-      } else if( !getIsDeviceCompatible(device) ) {
+      }
+      
+      // Always validate the device, 
+      // since even the default device may not be used by this factory.
+      if( !getIsDeviceCompatible(device) ) {
           if (GLProfile.DEBUG) {
-              System.err.println("Info: GLDrawableFactory.validateDevice: device not compatible : "+device);
+              System.err.println("Info: "+getClass().getSimpleName()+".validateDevice: device not compatible : "+device);
           }
           return null;
       }
@@ -317,15 +331,13 @@ public abstract class GLDrawableFactory {
 
   protected static GLDrawableFactory getFactoryImpl(String glProfileImplName) throws GLException {
     if ( GLProfile.usesNativeGLES(glProfileImplName) ) {
-        if(null==eglFactory) {
-            throw new GLException("No EGLDrawableFactory available for profile: "+glProfileImplName);
+        if(null!=eglFactory) {   
+            return eglFactory;
         }
-        return eglFactory;
-    }
-    if(null==nativeOSFactory) {
-        throw new GLException("No native platform GLDrawableFactory available for profile: "+glProfileImplName);
+    } else if(null!=nativeOSFactory) {
+        return nativeOSFactory;
     }
-    return nativeOSFactory;
+    throw new GLException("No GLDrawableFactory available for profile: "+glProfileImplName);
   }
 
   protected static GLDrawableFactory getFactoryImpl(AbstractGraphicsDevice device) throws GLException {
diff --git a/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java b/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java
index 7a12e52..2bfc77d 100644
--- a/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java
+++ b/src/jogl/classes/javax/media/opengl/GLPipelineFactory.java
@@ -159,7 +159,7 @@ public class GLPipelineFactory {
     }
 
     private static final String getArgsClassNameList(Class<?> arg0, Object[] args) {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append(arg0.getName());
         if(args!=null) {
             for(int j=0; j<args.length; j++) {
diff --git a/src/jogl/classes/javax/media/opengl/GLProfile.java b/src/jogl/classes/javax/media/opengl/GLProfile.java
index 6b39fe7..f85c6ba 100644
--- a/src/jogl/classes/javax/media/opengl/GLProfile.java
+++ b/src/jogl/classes/javax/media/opengl/GLProfile.java
@@ -39,7 +39,6 @@ package javax.media.opengl;
 
 import jogamp.opengl.Debug;
 import jogamp.opengl.GLDrawableFactoryImpl;
-import jogamp.opengl.GLDynamicLookupHelper;
 import jogamp.opengl.DesktopGLDynamicLookupHelper;
 
 import com.jogamp.common.GlueGenVersion;
@@ -75,6 +74,16 @@ import java.util.List;
 public class GLProfile {
     
     public static final boolean DEBUG = Debug.debug("GLProfile");
+    
+    /** 
+     * We have to disable support for ANGLE, the D3D ES2 emulation on Windows provided w/ Firefox and Chrome. 
+     * When run in the mentioned browsers, the eglInitialize(..) implementation crashes.
+     * <p>
+     * This can be overridden by explicitly enabling ANGLE on Windows by setting the property
+     * <code>jogl.enable.ANGLE</code>.
+     * </p> 
+     */
+    private static final boolean enableANGLE = Debug.isPropertyDefined("jogl.enable.ANGLE", true);
 
     static {
         // Also initializes TempJarCache if shall be used.
@@ -246,8 +255,25 @@ public class GLProfile {
     }
     
     public static String glAvailabilityToString(AbstractGraphicsDevice device) {
+        return glAvailabilityToString(device, null).toString();
+    }
+    
+    public static StringBuilder glAvailabilityToString(AbstractGraphicsDevice device, StringBuilder sb) {
+        return glAvailabilityToString(device, sb, null, 0);
+    }
+    private static StringBuilder doIndent(StringBuilder sb, String indent, int indentCount) {
+        while(indentCount>0) {
+            sb.append(indent);
+            indentCount--;
+        }
+        return sb;
+    }
+    public static StringBuilder glAvailabilityToString(AbstractGraphicsDevice device, StringBuilder sb, String indent, int indentCount) {
         boolean avail;
-        StringBuffer sb = new StringBuffer();
+        if(null == sb) {
+            sb = new StringBuilder();
+        }
+        final boolean useIndent = null != indent;
 
         initSingleton();
         
@@ -256,77 +282,135 @@ public class GLProfile {
         }
         final HashMap<String /*GLProfile_name*/, GLProfile> map = getProfileMap(device, false);
         
-        sb.append("GLAvailability[Native[GL4bc ");
+        if(useIndent) {
+            doIndent(sb, indent, indentCount).append("Native");
+            indentCount++;
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL4bc").append(indent);
+        } else {
+            sb.append("Native[GL4bc ");
+        }        
         avail=isAvailableImpl(map, GL4bc);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 4, GLContext.CTX_PROFILE_COMPAT);
+            glAvailabilityToString(device, sb.append(" "), 4, GLContext.CTX_PROFILE_COMPAT);
         }
 
-        sb.append(", GL4 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL4").append(indent);
+        } else {
+            sb.append(", GL4 ");
+        }
         avail=isAvailableImpl(map, GL4);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 4, GLContext.CTX_PROFILE_CORE);
+            glAvailabilityToString(device, sb.append(" "), 4, GLContext.CTX_PROFILE_CORE);
         }
 
-        sb.append(", GL3bc ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL3bc").append(indent);
+        } else {
+            sb.append(", GL3bc ");
+        }
         avail=isAvailableImpl(map, GL3bc);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 3, GLContext.CTX_PROFILE_COMPAT);
+            glAvailabilityToString(device, sb.append(" "), 3, GLContext.CTX_PROFILE_COMPAT);
         }
 
-        sb.append(", GL3 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL3").append(indent);
+        } else {
+            sb.append(", GL3 ");
+        }
         avail=isAvailableImpl(map, GL3);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 3, GLContext.CTX_PROFILE_CORE);
+            glAvailabilityToString(device, sb.append(" "), 3, GLContext.CTX_PROFILE_CORE);
         }
 
-        sb.append(", GL2 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL2").append(indent);
+        } else {
+            sb.append(", GL2 ");
+        }
         avail=isAvailableImpl(map, GL2);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 2, GLContext.CTX_PROFILE_COMPAT);
+            glAvailabilityToString(device, sb.append(" "), 2, GLContext.CTX_PROFILE_COMPAT);
         }
 
-        sb.append(", GL2ES1 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL2ES1").append(indent);
+        } else {
+            sb.append(", GL2ES1 ");
+        }
         sb.append(isAvailableImpl(map, GL2ES1));
 
-        sb.append(", GLES1 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GLES1").append(indent);
+        } else {
+            sb.append(", GLES1 ");
+        }
         avail=isAvailableImpl(map, GLES1);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 1, GLContext.CTX_PROFILE_ES);
+            glAvailabilityToString(device, sb.append(" "), 1, GLContext.CTX_PROFILE_ES);
         }
 
-        sb.append(", GL2ES2 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GL2ES2").append(indent);
+        } else {
+            sb.append(", GL2ES2 ");
+        }
         sb.append(isAvailableImpl(map, GL2ES2));
 
-        sb.append(", GLES2 ");
+        if(useIndent) {
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("GLES2").append(indent);
+        } else {
+            sb.append(", GLES2 ");
+        }
         avail=isAvailableImpl(map, GLES2);
         sb.append(avail);
         if(avail) {
-            glAvailabilityToString(device, sb, 2, GLContext.CTX_PROFILE_ES);
+            glAvailabilityToString(device, sb.append(" "), 2, GLContext.CTX_PROFILE_ES);
         }
 
-        sb.append("], Profiles[");
+        if(useIndent) {
+            indentCount--;
+            doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("Profiles");
+            indentCount++;
+        } else {
+            sb.append("], Profiles[");
+        }
+        
         if(null != map) {
             for(Iterator<GLProfile> i=map.values().iterator(); i.hasNext(); ) {
+                if(useIndent) {
+                    doIndent(sb.append(Platform.getNewline()), indent, indentCount);
+                }
                 sb.append(i.next().toString());
-                sb.append(", ");
+                if(!useIndent) {
+                    sb.append(", ");
+                }
+            }
+            if(useIndent) {
+                doIndent(sb.append(Platform.getNewline()), indent, indentCount).append("default ");
+            } else {
+                sb.append(", default ");
             }
-            sb.append(", default ");
             try {
                 sb.append(getDefault(device));
             } catch (GLException gle) {
                 sb.append("n/a");
             }
         }
-        sb.append("]]");
+        if(useIndent) {
+            sb.append(Platform.getNewline());
+        } else {
+            sb.append("]");
+        }
 
-        return sb.toString();
+        return sb;
     }
     
     /** Uses the default device */
@@ -471,6 +555,7 @@ public class GLProfile {
 
     /** Returns a default GLProfile object, reflecting the best for the running platform.
      * It selects the first of the set {@link GLProfile#GL_PROFILE_LIST_ALL}
+     * and favors hardware acceleration.
      * @throws GLException if no profile is available for the device.
      * @see #GL_PROFILE_LIST_ALL
      */
@@ -479,7 +564,10 @@ public class GLProfile {
         return glp;
     }
 
-    /** Uses the default device 
+    /** Returns a default GLProfile object, reflecting the best for the running platform.
+     * It selects the first of the set {@link GLProfile#GL_PROFILE_LIST_ALL}
+     * and favors hardware acceleration.
+     * <p>Uses the default device.</p> 
      * @throws GLException if no profile is available for the default device.
      */
     public static GLProfile getDefault() {
@@ -493,20 +581,20 @@ public class GLProfile {
      * @throws GLException if no profile is available for the device.
      * @see #GL_PROFILE_LIST_MAX
      */
-    public static GLProfile getMaximum(AbstractGraphicsDevice device)
+    public static GLProfile getMaximum(AbstractGraphicsDevice device, boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(device, GL_PROFILE_LIST_MAX);
+        return get(device, GL_PROFILE_LIST_MAX, favorHardwareRasterizer);
     }
 
     /** Uses the default device 
      * @throws GLException if no profile is available for the default device.
      * @see #GL_PROFILE_LIST_MAX
      */
-    public static GLProfile getMaximum()
+    public static GLProfile getMaximum(boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(GL_PROFILE_LIST_MAX);
+        return get(GL_PROFILE_LIST_MAX, favorHardwareRasterizer);
     }
 
     /**
@@ -516,20 +604,20 @@ public class GLProfile {
      * @throws GLException if no desktop profile is available for the device.
      * @see #GL_PROFILE_LIST_MIN
      */
-    public static GLProfile getMinimum(AbstractGraphicsDevice device)
+    public static GLProfile getMinimum(AbstractGraphicsDevice device, boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(device, GL_PROFILE_LIST_MIN);
+        return get(device, GL_PROFILE_LIST_MIN, favorHardwareRasterizer);
     }
 
     /** Uses the default device 
      * @throws GLException if no desktop profile is available for the default device.
      * @see #GL_PROFILE_LIST_MIN
      */
-    public static GLProfile getMinimum()
+    public static GLProfile getMinimum(boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(GL_PROFILE_LIST_MIN);
+        return get(GL_PROFILE_LIST_MIN, favorHardwareRasterizer);
     }
 
 
@@ -540,20 +628,20 @@ public class GLProfile {
      * @throws GLException if no fixed function profile is available for the device.
      * @see #GL_PROFILE_LIST_MAX_FIXEDFUNC
      */
-    public static GLProfile getMaxFixedFunc(AbstractGraphicsDevice device)
+    public static GLProfile getMaxFixedFunc(AbstractGraphicsDevice device, boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(device, GL_PROFILE_LIST_MAX_FIXEDFUNC);
+        return get(device, GL_PROFILE_LIST_MAX_FIXEDFUNC, favorHardwareRasterizer);
     }
 
     /** Uses the default device 
      * @throws GLException if no fixed function profile is available for the default device.
      * @see #GL_PROFILE_LIST_MAX_FIXEDFUNC
      */
-    public static GLProfile getMaxFixedFunc()
+    public static GLProfile getMaxFixedFunc(boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(GL_PROFILE_LIST_MAX_FIXEDFUNC);
+        return get(GL_PROFILE_LIST_MAX_FIXEDFUNC, favorHardwareRasterizer);
     }
 
     /**
@@ -563,20 +651,20 @@ public class GLProfile {
      * @throws GLException if no programmable profile is available for the device.
      * @see #GL_PROFILE_LIST_MAX_PROGSHADER
      */
-    public static GLProfile getMaxProgrammable(AbstractGraphicsDevice device)
+    public static GLProfile getMaxProgrammable(AbstractGraphicsDevice device, boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(device, GL_PROFILE_LIST_MAX_PROGSHADER);
+        return get(device, GL_PROFILE_LIST_MAX_PROGSHADER, favorHardwareRasterizer);
     }
 
     /** Uses the default device 
      * @throws GLException if no programmable profile is available for the default device.
      * @see #GL_PROFILE_LIST_MAX_PROGSHADER
      */
-    public static GLProfile getMaxProgrammable()
+    public static GLProfile getMaxProgrammable(boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(GL_PROFILE_LIST_MAX_PROGSHADER);
+        return get(GL_PROFILE_LIST_MAX_PROGSHADER, favorHardwareRasterizer);
     }
 
     /** 
@@ -585,8 +673,10 @@ public class GLProfile {
      * <pre>
      *   GLProfile.get(device, GLProfile.GL2ES1).getImpl());
      * </pre>
+     * <p>Selection favors hardware rasterizer.</p>
      *
      * @throws GLException if no GL2ES1 compatible profile is available for the default device.
+     * @see #isGL2ES1()
      * @see #get(AbstractGraphicsDevice, String)
      * @see #getImpl()
      */
@@ -598,6 +688,7 @@ public class GLProfile {
 
     /** 
      * Calls {@link #getGL2ES1(AbstractGraphicsDevice)} using the default device. 
+     * <p>Selection favors hardware rasterizer.</p>
      * @see #getGL2ES1(AbstractGraphicsDevice)
      */
     public static GLProfile getGL2ES1()
@@ -612,8 +703,10 @@ public class GLProfile {
      * <pre>
      *   GLProfile.get(device, GLProfile.GL2ES2).getImpl());
      * </pre>
+     * <p>Selection favors hardware rasterizer.</p>
      *
      * @throws GLException if no GL2ES2 compatible profile is available for the default device.
+     * @see #isGL2ES2()
      * @see #get(AbstractGraphicsDevice, String)
      * @see #getImpl()
      */
@@ -625,6 +718,7 @@ public class GLProfile {
 
     /** 
      * Calls {@link #getGL2ES2(AbstractGraphicsDevice)} using the default device. 
+     * <p>Selection favors hardware rasterizer.</p>
      * @see #getGL2ES2(AbstractGraphicsDevice)
      */
     public static GLProfile getGL2ES2()
@@ -633,6 +727,36 @@ public class GLProfile {
         return get(defaultDevice, GL2ES2).getImpl();
     }
 
+    /** 
+     * Returns the GL2GL3 profile implementation, hence compatible w/ GL2GL3.<br/>
+     * It returns:
+     * <pre>
+     *   GLProfile.get(device, GLProfile.GL2GL3).getImpl());
+     * </pre>
+     * <p>Selection favors hardware rasterizer.</p>
+     *
+     * @throws GLException if no GL2GL3 compatible profile is available for the default device.
+     * @see #isGL2GL3()
+     * @see #get(AbstractGraphicsDevice, String)
+     * @see #getImpl()
+     */
+    public static GLProfile getGL2GL3(AbstractGraphicsDevice device)
+        throws GLException
+    {
+        return get(device, GL2GL3).getImpl();
+    }
+
+    /** 
+     * Calls {@link #getGL2GL3(AbstractGraphicsDevice)} using the default device. 
+     * <p>Selection favors hardware rasterizer.</p>
+     * @see #getGL2GL3(AbstractGraphicsDevice)
+     */
+    public static GLProfile getGL2GL3()
+        throws GLException
+    {
+        return get(defaultDevice, GL2GL3).getImpl();
+    }
+
     /** Returns a GLProfile object.
      * verifies the given profile and chooses an appropriate implementation.
      * A generic value of <code>null</code> or <code>GL</code> will result in
@@ -673,31 +797,45 @@ public class GLProfile {
      * where an implementation is available.
      *
      * @param device a valid AbstractGraphicsDevice, or <code>null</null> for the default device.
-     * @param profiles array of valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..) 
+     * @param profiles array of valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..)
+     * @param favorHardwareRasterizer set to true, if hardware rasterizer shall be favored, otherwise false. 
      * @throws GLException if the non of the requested profiles is available for the device.
      */
-    public static GLProfile get(AbstractGraphicsDevice device, String[] profiles)
+    public static GLProfile get(AbstractGraphicsDevice device, String[] profiles, boolean favorHardwareRasterizer)
         throws GLException
     {
+        GLProfile glProfileAny = null;
+        
         HashMap<String /*GLProfile_name*/, GLProfile> map = getProfileMap(device, true);
         for(int i=0; i<profiles.length; i++) {
-            String profile = profiles[i];
-            GLProfile glProfile = map.get(profile);
+            final GLProfile glProfile = map.get(profiles[i]);
             if(null!=glProfile) {
-                return glProfile;
+                if(!favorHardwareRasterizer) {
+                    return glProfile;
+                }
+                if(glProfile.isHardwareRasterizer()) {
+                    return glProfile;
+                }
+                if(null==glProfileAny) {
+                    glProfileAny = glProfile;
+                }                
             }
         }
+        if(null!=glProfileAny) {
+            return glProfileAny;
+        }                
         throw new GLException("Profiles "+array2String(profiles)+" not available on device "+device);
     }
 
     /** Uses the default device 
      * @param profiles array of valid GLProfile name ({@link #GL4bc}, {@link #GL4}, {@link #GL2}, ..) 
+     * @param favorHardwareRasterizer set to true, if hardware rasterizer shall be favored, otherwise false. 
      * @throws GLException if the non of the requested profiles is available for the default device.
      */
-    public static GLProfile get(String[] profiles)
+    public static GLProfile get(String[] profiles, boolean favorHardwareRasterizer)
         throws GLException
     {
-        return get(defaultDevice, profiles);
+        return get(defaultDevice, profiles, favorHardwareRasterizer);
     }
     
     /** Indicates whether the native OpenGL ES1 profile is in use. 
@@ -812,6 +950,11 @@ public class GLProfile {
         return null != profileImpl ? profileImpl : this;
     }
     
+    /** return true if impl. is a hardware rasterizer, otherwise false. */
+    public final boolean isHardwareRasterizer() {
+        return isHardwareRasterizer;
+    }
+    
     /** 
      * return this profiles implementation name, eg. GL2ES2 -> GL2, or GL3 -> GL3 
      */
@@ -819,69 +962,69 @@ public class GLProfile {
         return null != profileImpl ? profileImpl.getName() : getName();
     }
 
-    /** Indicates whether this profile is capable of GL4bc. */
+    /** Indicates whether this profile is capable of GL4bc.  <p>Includes [ GL4bc ].</p> */
     public final boolean isGL4bc() {
-        return GL4bc.equals(profile);
+        return GL4bc == profile;
     }
 
-    /** Indicates whether this profile is capable of GL4. */
+    /** Indicates whether this profile is capable of GL4.    <p>Includes [ GL4bc, GL4 ].</p> */
     public final boolean isGL4() {
-        return isGL4bc() || GL4.equals(profile);
+        return isGL4bc() || GL4 == profile;
     }
 
-    /** Indicates whether this profile is capable of GL3bc. */
+    /** Indicates whether this profile is capable of GL3bc.  <p>Includes [ GL4bc, GL3bc ].</p> */
     public final boolean isGL3bc() {
-        return isGL4bc() || GL3bc.equals(profile);
+        return isGL4bc() || GL3bc == profile;
     }
 
-    /** Indicates whether this profile is capable of GL3. */
+    /** Indicates whether this profile is capable of GL3.    <p>Includes [ GL4bc, GL4, GL3bc, GL3 ].</p> */
     public final boolean isGL3() {
-        return isGL4() || isGL3bc() || GL3.equals(profile);
+        return isGL4() || isGL3bc() || GL3 == profile;
     }
 
-    /** Indicates whether this context is a GL2 context */
+    /** Indicates whether this context is a GL2 context      <p>Includes [ GL4bc, GL3bc, GL2 ].</p> */
     public final boolean isGL2() {
-        return isGL3bc() || GL2.equals(profile);
+        return isGL3bc() || GL2 == profile;
     }
 
-    /** Indicates whether this profile is capable of GLES1. */
+    /** Indicates whether this profile is capable of GLES1.  <p>Includes [ GLES1 ].</p> */
     public final boolean isGLES1() {
-        return GLES1.equals(profile);
+        return GLES1 == profile;
     }
 
-    /** Indicates whether this profile is capable of GLES2. */
+    /** Indicates whether this profile is capable of GLES2.  <p>Includes [ GLES2 ].</p> */
     public final boolean isGLES2() {
-        return GLES2.equals(profile);
+        return GLES2 == profile;
     }
 
-    /** Indicates whether this profile is capable of GL2ES1. */
+    /** Indicates whether this profile is capable of GL2ES1. <p>Includes [ GL4bc, GL3bc, GL2, GLES1, GL2ES1 ].</p> */
     public final boolean isGL2ES1() {
-        return GL2ES1.equals(profile) || isGL2() || isGLES1() ;
+        return GL2ES1 == profile || isGLES1() || isGL2();
     }
 
-    /** Indicates whether this profile is capable os GL2ES2. */
-    public final boolean isGL2ES2() {
-        return GL2ES2.equals(profile) || isGL2() || isGL3() || isGLES2() ;
+    /** Indicates whether this profile is capable os GL2GL3. <p>Includes [ GL4bc, GL4, GL3bc, GL3, GL2, GL2GL3 ].</p> */
+    public final boolean isGL2GL3() {
+        return GL2GL3 == profile || isGL3() || isGL2();
     }
 
-    /** Indicates whether this profile is capable os GL2GL3. */
-    public final boolean isGL2GL3() {
-        return GL2GL3.equals(profile) || isGL2() || isGL3() ;
+    /** Indicates whether this profile is capable os GL2ES2. <p>Includes [ GL4bc, GL4, GL3bc, GL3, GL2, GL2GL3, GL2ES2, GLES2 ].</p> */
+    public final boolean isGL2ES2() {
+        return GL2ES2 == profile || isGLES2() || isGL2GL3();
     }
 
-    /** Indicates whether this profile supports GLSL. */
+    /** Indicates whether this profile supports GLSL, ie. {@link #isGL2ES2()}. */
     public final boolean hasGLSL() {
         return isGL2ES2() ;
     }
 
     /** Indicates whether this profile uses the native OpenGL ES1 implementations. */
     public final boolean usesNativeGLES1() {
-        return GLES1.equals(getImplName());
+        return GLES1 == getImplName();
     }
 
     /** Indicates whether this profile uses the native OpenGL ES2 implementations. */
     public final boolean usesNativeGLES2() {
-        return GLES2.equals(getImplName());
+        return GLES2 == getImplName();
     }
 
     /** Indicates whether this profile uses either of the native OpenGL ES implementations. */
@@ -1187,7 +1330,7 @@ public class GLProfile {
     }
 
     public String toString() {
-        return "GLProfile[" + getName() + "/" + getImplName() + "]";
+        return "GLProfile[" + getName() + "/" + getImplName() + "."+(this.isHardwareRasterizer?"hw":"sw")+"]";
     }
 
     private static /*final*/ boolean isAWTAvailable;
@@ -1198,11 +1341,9 @@ public class GLProfile {
     private static /*final*/ boolean hasGLES2Impl;
     private static /*final*/ boolean hasGLES1Impl;
 
-    private static /*final*/ GLDrawableFactoryImpl eglFactory;
-    private static /*final*/ GLDrawableFactoryImpl desktopFactory;
-    private static /*final*/ AbstractGraphicsDevice defaultDevice;
-    private static /*final*/ AbstractGraphicsDevice defaultDesktopDevice;
-    private static /*final*/ AbstractGraphicsDevice defaultEGLDevice;
+    private static /*final*/ GLDrawableFactoryImpl eglFactory = null;
+    private static /*final*/ GLDrawableFactoryImpl desktopFactory = null;
+    private static /*final*/ AbstractGraphicsDevice defaultDevice = null;
 
     private static volatile boolean initialized = false;
     private static RecursiveThreadGroupLock initLock = LockFactory.createRecursiveThreadGroupLock();
@@ -1264,17 +1405,22 @@ public class GLProfile {
             if(null!=t) {
                 t.printStackTrace();
             }
-            if(null == desktopFactory) {
-                System.err.println("Info: GLProfile.init - Desktop GLDrawable factory not available");
-            }
         }
 
+        final AbstractGraphicsDevice defaultDesktopDevice;
         if(null == desktopFactory) {
-            hasDesktopGLFactory   = false;
-            hasGL234Impl   = false;
+            hasDesktopGLFactory  = false;
+            hasGL234Impl         = false;
+            defaultDesktopDevice = null;
+            if(DEBUG) {
+                System.err.println("Info: GLProfile.init - Desktop GLDrawable factory not available");
+            }
         } else {
             defaultDesktopDevice = desktopFactory.getDefaultDevice();
-            defaultDevice = defaultDesktopDevice;
+            defaultDevice        = defaultDesktopDevice; 
+            if(DEBUG) {
+                System.err.println("Info: GLProfile.init - Default device is desktop derived: "+defaultDevice);
+            }
         }
 
         if ( ReflectionUtil.isClassAvailable("jogamp.opengl.egl.EGLDrawableFactory", classloader) ) {
@@ -1282,15 +1428,22 @@ public class GLProfile {
             try {
                 eglFactory = (GLDrawableFactoryImpl) GLDrawableFactory.getFactoryImpl(GLES2);
                 if(null != eglFactory) {
-                    hasEGLFactory = true;
-                    GLDynamicLookupHelper eglLookupHelper = eglFactory.getGLDynamicLookupHelper(2);
-                    // update hasGLES1Impl, hasGLES2Impl based on EGL
-                    if(null!=eglLookupHelper) {
-                        hasGLES2Impl = eglLookupHelper.isLibComplete() && hasGLES2Impl;
-                    }
-                    eglLookupHelper = eglFactory.getGLDynamicLookupHelper(1);
-                    if(null!=eglLookupHelper) {
-                        hasGLES1Impl = eglLookupHelper.isLibComplete() && hasGLES1Impl;
+                    final boolean isANGLE = ((jogamp.opengl.egl.EGLDrawableFactory)eglFactory).isANGLE();
+                    if(isANGLE && !enableANGLE) {
+                        if(DEBUG) {
+                            System.err.println("Info: GLProfile.init - EGL/ES2 ANGLE disabled");
+                        }
+                        eglFactory.destroy(ShutdownType.COMPLETE);
+                        eglFactory    = null;
+                        hasEGLFactory = false;
+                    } else {
+                        if(DEBUG && isANGLE) {
+                            System.err.println("Info: GLProfile.init - EGL/ES2 ANGLE enabled");
+                        }
+                        hasEGLFactory = true;
+                        // update hasGLES1Impl, hasGLES2Impl based on EGL
+                        hasGLES2Impl = null!=eglFactory.getGLDynamicLookupHelper(2) && hasGLES2Impl;
+                        hasGLES1Impl = null!=eglFactory.getGLDynamicLookupHelper(1) && hasGLES1Impl;
                     }
                 }
             } catch (LinkageError le) {
@@ -1306,38 +1459,46 @@ public class GLProfile {
                 if(null!=t) {
                     t.printStackTrace();
                 }
-                if(null == eglFactory) {
-                    System.err.println("Info: GLProfile.init - EGL GLDrawable factory not available");
-                }
             }
         }
 
+        final AbstractGraphicsDevice defaultEGLDevice;        
         if(null == eglFactory) {
-            hasGLES2Impl   = false;
-            hasGLES1Impl   = false;
+            hasGLES2Impl     = false;
+            hasGLES1Impl     = false;
+            defaultEGLDevice = null;
+            if(DEBUG) {
+                System.err.println("Info: GLProfile.init - EGL GLDrawable factory not available");
+            }
         } else {
             defaultEGLDevice = eglFactory.getDefaultDevice();
-            if (null==defaultDevice) {
+            if(null == defaultDevice) {
                 defaultDevice = defaultEGLDevice;
+                if(DEBUG) {
+                    System.err.println("Info: GLProfile.init - Default device is EGL derived: "+defaultDevice);
+                }
             }
         }
 
-        final boolean addedDesktopProfile = initProfilesForDevice(defaultDesktopDevice);
-        final boolean addedEGLProfile = initProfilesForDevice(defaultEGLDevice);
-        final boolean addedAnyProfile = addedDesktopProfile || addedEGLProfile ;
+        /** Should not be required .. but keep it here if simple probe on defaultDevice ain't enough. 
+        final boolean addedDesktopProfile = initProfilesForDevice(defaultDesktopDevice); 
+        final boolean addedEGLProfile     = initProfilesForDevice(defaultEGLDevice); 
+        final boolean addedAnyProfile =  addedDesktopProfile || addedEGLProfile ;
+         */
+        final boolean addedAnyProfile =  initProfilesForDevice(defaultDevice);
 
         if(DEBUG) {
-            System.err.println("GLProfile.init addedAnyProfile(d/e) "+addedAnyProfile+" ("+addedDesktopProfile+"/"+addedEGLProfile+")");
+            // System.err.println("GLProfile.init addedAnyProfile      "+addedAnyProfile+" (desktop: "+addedDesktopProfile+", egl "+addedEGLProfile+")");
+            System.err.println("GLProfile.init addedAnyProfile      "+addedAnyProfile);
             System.err.println("GLProfile.init isAWTAvailable       "+isAWTAvailable);
             System.err.println("GLProfile.init hasDesktopGLFactory  "+hasDesktopGLFactory);
             System.err.println("GLProfile.init hasGL234Impl         "+hasGL234Impl);
             System.err.println("GLProfile.init hasEGLFactory        "+hasEGLFactory);
             System.err.println("GLProfile.init hasGLES1Impl         "+hasGLES1Impl);
             System.err.println("GLProfile.init hasGLES2Impl         "+hasGLES2Impl);
-            System.err.println("GLProfile.init defaultDesktopDevice "+defaultDesktopDevice);
-            System.err.println("GLProfile.init defaultEGLDevice     "+defaultEGLDevice);
             System.err.println("GLProfile.init defaultDevice        "+defaultDevice);
-            System.err.println("GLProfile.init: "+array2String(GL_PROFILE_LIST_ALL)+", "+ glAvailabilityToString());
+            System.err.println("GLProfile.init profile order        "+array2String(GL_PROFILE_LIST_ALL));            
+            System.err.println(JoglVersion.getDefaultOpenGLInfo(null));            
         }
     }
 
@@ -1366,21 +1527,24 @@ public class GLProfile {
         boolean isSet = GLContext.getAvailableGLVersionsSet(device);
 
         if(DEBUG) {
-            String msg = "Info: GLProfile.initProfilesForDevice: "+device+", isSet "+isSet;
-            Throwable t = new Throwable(msg);
-            t.printStackTrace();
-            // System.err.println(msg);
+            System.err.println("Info: GLProfile.initProfilesForDevice: "+device+", isSet "+isSet);
         }
         if(isSet) {
-            return GLProfile.isAvailable(device, GL_DEFAULT);
+            // Avoid recursion and check whether impl. is sane!
+            final String deviceKey = device.getUniqueID();
+            HashMap<String /*GLProfile_name*/, GLProfile> map = deviceConn2ProfileMap.get(deviceKey);
+            if( null == map ) {
+                throw new InternalError("GLContext Avail. GLVersion is set - but no profile map for device: "+device);
+            }
+            return null != map.get(GL_DEFAULT);
         }
 
         boolean addedDesktopProfile = false;
         boolean addedEGLProfile = false;
-        boolean deviceIsDesktopCompatible = false;
-        boolean deviceIsEGLCompatible = false;
         
-        if( hasDesktopGLFactory && ( deviceIsDesktopCompatible = desktopFactory.getIsDeviceCompatible(device)) ) {
+        final boolean deviceIsDesktopCompatible = hasDesktopGLFactory && desktopFactory.getIsDeviceCompatible(device);
+        
+        if( deviceIsDesktopCompatible ) {
             // 1st pretend we have all Desktop and EGL profiles ..
             computeProfileMap(device, true /* desktopCtxUndef*/, true  /* esCtxUndef */);
 
@@ -1394,22 +1558,21 @@ public class GLProfile {
             if(null != sharedResourceThread) {
                 initLock.removeOwner(sharedResourceThread);
             }
-            if(!desktopSharedCtxAvail) {
-                hasDesktopGLFactory = false;
-            }
             if (DEBUG) {
                 System.err.println("GLProfile.initProfilesForDevice: "+device+": desktop Shared Ctx "+desktopSharedCtxAvail);
             }
-            if( hasDesktopGLFactory && null == GLContext.getAvailableGLVersion(device, 2, GLContext.CTX_PROFILE_COMPAT) ) {
-                // nobody yet set the available desktop versions, see {@link GLContextImpl#makeCurrent},
-                // so we have to add the usual suspect
-                GLContext.mapAvailableGLVersion(device,
-                                                2, GLContext.CTX_PROFILE_COMPAT,
-                                                1, 5, GLContext.CTX_PROFILE_COMPAT|GLContext.CTX_OPTION_ANY);
+            if(!desktopSharedCtxAvail) {
+                hasDesktopGLFactory = false;
+            } else if( !GLContext.getAvailableGLVersionsSet(device) ) {
+                throw new InternalError("Available GLVersions not set");
             }
             addedDesktopProfile = computeProfileMap(device, false /* desktopCtxUndef*/, false /* esCtxUndef */);
-        } else if( hasEGLFactory && ( hasGLES2Impl || hasGLES1Impl ) && 
-                   ( deviceIsEGLCompatible = eglFactory.getIsDeviceCompatible(device)) ) {
+        }
+        
+        final boolean deviceIsEGLCompatible = hasEGLFactory && eglFactory.getIsDeviceCompatible(device);
+        
+        // also test GLES1 and GLES2 on desktop, since we have implementations / emulations available.
+        if( deviceIsEGLCompatible && ( hasGLES2Impl || hasGLES1Impl ) ) {
             // 1st pretend we have all EGL profiles ..
             computeProfileMap(device, false /* desktopCtxUndef*/, true /* esCtxUndef */);
 
@@ -1434,22 +1597,28 @@ public class GLProfile {
             if (DEBUG) {
                 System.err.println("GLProfile.initProfilesForDevice: "+device+": egl Shared Ctx "+eglSharedCtxAvail);
             }
-            if(hasGLES2Impl && null == GLContext.getAvailableGLVersion(device, 2, GLContext.CTX_PROFILE_ES) ) {
-                // nobody yet set the available desktop versions, see {@link GLContextImpl#makeCurrent},
-                // so we have to add the usual suspect
+            if( hasGLES2Impl ) {
+                // The native ES2 impl. overwrites a previous mapping using 'ES2 compatibility' by a desktop profile 
                 GLContext.mapAvailableGLVersion(device,
                                                 2, GLContext.CTX_PROFILE_ES,
-                                                2, 0, GLContext.CTX_PROFILE_ES|GLContext.CTX_OPTION_ANY);
+                                                2, 0, GLContext.CTX_PROFILE_ES|GLContext.CTX_IMPL_ES2_COMPAT);
+                if (DEBUG) {
+                  System.err.println(GLContext.getThreadName() + ": initProfilesForDeviceCritical-MapVersionsAvailable HAVE: ES2 -> ES 2.0");
+                }
             }
-            if(hasGLES1Impl && null == GLContext.getAvailableGLVersion(device, 1, GLContext.CTX_PROFILE_ES)) {
-                // nobody yet set the available desktop versions, see {@link GLContextImpl#makeCurrent},
-                // so we have to add the usual suspect
+            if( hasGLES1Impl ) {
+                // Always favor the native ES1 impl.
                 GLContext.mapAvailableGLVersion(device,
                                                 1, GLContext.CTX_PROFILE_ES,
-                                                1, 0, GLContext.CTX_PROFILE_ES|GLContext.CTX_OPTION_ANY);
+                                                1, 0, GLContext.CTX_PROFILE_ES);
+                if (DEBUG) {
+                  System.err.println(GLContext.getThreadName() + ": initProfilesForDeviceCritical-MapVersionsAvailable HAVE: ES1 -> ES 1.0");
+                }
             }
             addedEGLProfile = computeProfileMap(device, false /* desktopCtxUndef*/, false /* esCtxUndef */);
-        } else {
+        } 
+        
+        if( !addedDesktopProfile && !addedEGLProfile ) {
             setProfileMap(device, new HashMap<String /*GLProfile_name*/, GLProfile>()); // empty
             if(DEBUG) {
                 System.err.println("GLProfile: device could not be initialized: "+device);
@@ -1507,18 +1676,8 @@ public class GLProfile {
         return defaultDevice;
     }
 
-    public static AbstractGraphicsDevice getDefaultDesktopDevice() {
-        initSingleton();
-        return defaultDesktopDevice;
-    }
-
-    public static AbstractGraphicsDevice getDefaultEGLDevice() {
-        initSingleton();
-        return defaultEGLDevice;
-    }
-
     private static String array2String(String[] list) {
-        StringBuffer msg = new StringBuffer();
+        StringBuilder msg = new StringBuilder();
         msg.append("[");
         for (int i = 0; i < list.length; i++) {
             if (i > 0)
@@ -1529,7 +1688,7 @@ public class GLProfile {
         return msg.toString();
     }
 
-    private static void glAvailabilityToString(AbstractGraphicsDevice device, StringBuffer sb, int major, int profile) {
+    private static void glAvailabilityToString(AbstractGraphicsDevice device, StringBuilder sb, int major, int profile) {
         String str = GLContext.getAvailableGLVersionAsString(device, major, profile);
         if(null==str) {
             throw new GLException("Internal Error");
@@ -1543,30 +1702,37 @@ public class GLProfile {
         if (DEBUG) {
             System.err.println("GLProfile.init map "+device.getConnection()+", desktopCtxUndef "+desktopCtxUndef+", esCtxUndef "+esCtxUndef);
         }
-        GLProfile defaultGLProfile = null;
+        final boolean isHardwareRasterizer[] = new boolean[1];
+        GLProfile defaultGLProfileAny = null;
+        GLProfile defaultGLProfileHW = null;
         HashMap<String, GLProfile> _mappedProfiles = new HashMap<String, GLProfile>(GL_PROFILE_LIST_ALL.length + 1 /* default */);
         for(int i=0; i<GL_PROFILE_LIST_ALL.length; i++) {
             String profile = GL_PROFILE_LIST_ALL[i];
-            String profileImpl = computeProfileImpl(device, profile, desktopCtxUndef, esCtxUndef);
+            String profileImpl = computeProfileImpl(device, profile, desktopCtxUndef, esCtxUndef, isHardwareRasterizer);
             if(null!=profileImpl) {
                 final GLProfile glProfile;
                 if(profile.equals(profileImpl)) {
-                    glProfile = new GLProfile(profile, null);
+                    glProfile = new GLProfile(profile, null, isHardwareRasterizer[0]);
                 } else {
                     final GLProfile _mglp = _mappedProfiles.get(profileImpl);
                     if(null == _mglp) {
                         throw new InternalError("XXX0");
                     }
-                    glProfile = new GLProfile(profile, _mglp);
+                    glProfile = new GLProfile(profile, _mglp, isHardwareRasterizer[0]);
                 }
                 _mappedProfiles.put(profile, glProfile);
                 if (DEBUG) {
                     System.err.println("GLProfile.init map "+glProfile+" on devide "+device.getConnection());
                 }
-                if(null==defaultGLProfile) {
-                    defaultGLProfile=glProfile;
+                if(null==defaultGLProfileHW && isHardwareRasterizer[0]) {
+                    defaultGLProfileHW=glProfile;
+                    if (DEBUG) {
+                        System.err.println("GLProfile.init map defaultHW "+glProfile+" on device "+device.getConnection());
+                    }
+                } else if(null==defaultGLProfileAny) {
+                    defaultGLProfileAny=glProfile;
                     if (DEBUG) {
-                        System.err.println("GLProfile.init map default "+glProfile+" on device "+device.getConnection());
+                        System.err.println("GLProfile.init map defaultAny "+glProfile+" on device "+device.getConnection());
                     }
                 }
             } else {
@@ -1575,8 +1741,10 @@ public class GLProfile {
                 }
             }
         }
-        if(null!=defaultGLProfile) {
-            _mappedProfiles.put(GL_DEFAULT, defaultGLProfile);
+        if(null!=defaultGLProfileHW) {
+            _mappedProfiles.put(GL_DEFAULT, defaultGLProfileHW);
+        } else if(null!=defaultGLProfileAny) {
+            _mappedProfiles.put(GL_DEFAULT, defaultGLProfileAny);
         }
         setProfileMap(device, _mappedProfiles);
         return _mappedProfiles.size() > 0;
@@ -1585,68 +1753,114 @@ public class GLProfile {
     /**
      * Returns the profile implementation
      */
-    private static String computeProfileImpl(AbstractGraphicsDevice device, String profile, boolean desktopCtxUndef, boolean esCtxUndef) {
+    private static String computeProfileImpl(AbstractGraphicsDevice device, String profile, boolean desktopCtxUndef, boolean esCtxUndef, boolean isHardwareRasterizer[]) {
         // OSX GL3.. doesn't support GLSL<150, 
         // hence GL2ES2 and GL2GL3 need to be mapped on GL2 on OSX for GLSL compatibility.
         final boolean isOSX = Platform.OS_TYPE == Platform.OSType.MACOS;
         
         if (GL2ES1.equals(profile)) {
+            final boolean es1HardwareRasterizer[] = new boolean[1];
+            final boolean gles1Available = hasGLES1Impl && ( esCtxUndef || GLContext.isGLES1Available(device, es1HardwareRasterizer) );
+            final boolean gles1HWAvailable = gles1Available && es1HardwareRasterizer[0] ;
             if(hasGL234Impl) {
-                if(GLContext.isGL4bcAvailable(device)) {
-                    return GL4bc;
-                } else if(GLContext.isGL3bcAvailable(device)) {
-                    return GL3bc;
-                } else if(desktopCtxUndef || GLContext.isGL2Available(device)) {
-                    return GL2;
+                if(GLContext.isGL4bcAvailable(device, isHardwareRasterizer)) {
+                    if(!gles1HWAvailable || isHardwareRasterizer[0]) {
+                        return GL4bc;
+                    }
+                }
+                if(GLContext.isGL3bcAvailable(device, isHardwareRasterizer)) {
+                    if(!gles1HWAvailable || isHardwareRasterizer[0]) {
+                        return GL3bc;
+                    }
+                }
+                if(desktopCtxUndef || GLContext.isGL2Available(device, isHardwareRasterizer)) {
+                    if(!gles1HWAvailable || isHardwareRasterizer[0]) {
+                        return GL2;
+                    }
                 }
             }
-            if(hasGLES1Impl && ( esCtxUndef || GLContext.isGLES1Available(device))) {
+            if(gles1Available) {
+                isHardwareRasterizer[0] = es1HardwareRasterizer[0];
                 return GLES1;
             }
         } else if (GL2ES2.equals(profile)) {
+            final boolean es2HardwareRasterizer[] = new boolean[1];
+            final boolean gles2Available = hasGLES2Impl && ( esCtxUndef || GLContext.isGLES2Available(device, es2HardwareRasterizer) );
+            final boolean gles2HWAvailable = gles2Available && es2HardwareRasterizer[0] ;
             if(hasGL234Impl) {
-                if(!isOSX && GLContext.isGL4bcAvailable(device)) {
-                    return GL4bc;
-                } else if(!isOSX && GLContext.isGL4Available(device)) {
-                    return GL4;
-                } else if(!isOSX && GLContext.isGL3bcAvailable(device)) {
-                    return GL3bc;
-                } else if(!isOSX && GLContext.isGL3Available(device)) {
-                    return GL3;
-                } else if(desktopCtxUndef || GLContext.isGL2Available(device)) {
-                    return GL2;
+                if(!isOSX) {
+                    if(GLContext.isGL4bcAvailable(device, isHardwareRasterizer)) {
+                        if(!gles2HWAvailable || isHardwareRasterizer[0]) {
+                            return GL4bc;
+                        }
+                    }
+                    if(GLContext.isGL4Available(device, isHardwareRasterizer)) {
+                        if(!gles2HWAvailable || isHardwareRasterizer[0]) {
+                            return GL4;
+                        }
+                    }
+                    if(GLContext.isGL3bcAvailable(device, isHardwareRasterizer)) {
+                        if(!gles2HWAvailable || isHardwareRasterizer[0]) {
+                            return GL3bc;
+                        }
+                    }
+                    if(GLContext.isGL3Available(device, isHardwareRasterizer)) {
+                        if(!gles2HWAvailable || isHardwareRasterizer[0]) {
+                            return GL3;
+                        }
+                    }
+                }
+                if(desktopCtxUndef || GLContext.isGL2Available(device, isHardwareRasterizer)) {
+                    if(!gles2HWAvailable || isHardwareRasterizer[0]) {
+                        return GL2;
+                    }
                 }
             }
-            if(hasGLES2Impl && ( esCtxUndef || GLContext.isGLES2Available(device))) {
+            if(gles2Available) {
+                isHardwareRasterizer[0] = es2HardwareRasterizer[0];
                 return GLES2;
             }
         } else if(GL2GL3.equals(profile)) {
             if(hasGL234Impl) {
-                if(!isOSX && GLContext.isGL4bcAvailable(device)) {
+                if(!isOSX && GLContext.isGL4bcAvailable(device, isHardwareRasterizer)) {
                     return GL4bc;
-                } else if(!isOSX && GLContext.isGL4Available(device)) {
+                } else if(!isOSX && GLContext.isGL4Available(device, isHardwareRasterizer)) {
                     return GL4;
-                } else if(!isOSX && GLContext.isGL3bcAvailable(device)) {
+                } else if(!isOSX && GLContext.isGL3bcAvailable(device, isHardwareRasterizer)) {
                     return GL3bc;
-                } else if(!isOSX && GLContext.isGL3Available(device)) {
+                } else if(!isOSX && GLContext.isGL3Available(device, isHardwareRasterizer)) {
                     return GL3;
-                } else if(desktopCtxUndef || GLContext.isGL2Available(device)) {
+                } else if(desktopCtxUndef || GLContext.isGL2Available(device, isHardwareRasterizer)) {
                     return GL2;
                 }
             }
-        } else if(GL4bc.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL4bcAvailable(device))) {
+        } else if(GL4bc.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL4bcAvailable(device, isHardwareRasterizer))) {
             return GL4bc;
-        } else if(GL4.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL4Available(device))) {
+        } else if(GL4.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL4Available(device, isHardwareRasterizer))) {
             return GL4;
-        } else if(GL3bc.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL3bcAvailable(device))) {
+        } else if(GL3bc.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL3bcAvailable(device, isHardwareRasterizer))) {
             return GL3bc;
-        } else if(GL3.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL3Available(device))) {
+        } else if(GL3.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL3Available(device, isHardwareRasterizer))) {
             return GL3;
-        } else if(GL2.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL2Available(device))) {
+        } else if(GL2.equals(profile) && hasGL234Impl && ( desktopCtxUndef || GLContext.isGL2Available(device, isHardwareRasterizer))) {
             return GL2;
-        } else if(GLES2.equals(profile) && hasGLES2Impl && ( esCtxUndef || GLContext.isGLES2Available(device))) {
+        } else if(GLES2.equals(profile) && hasGLES2Impl && ( esCtxUndef || GLContext.isGLES2Available(device, isHardwareRasterizer))) {
             return GLES2;
-        } else if(GLES1.equals(profile) && hasGLES1Impl && ( esCtxUndef || GLContext.isGLES1Available(device))) {
+        /**
+         * TODO: GLES2_TRUE_DESKTOP (see: GLContextImpl, GLProfile)
+         * Hack to enable GLES2 for desktop profiles w/ ES2 compatibility,
+         * however .. a consequent implementation would need to have all GL2ES2
+         * implementing profile to also implement GLES2!
+         * Let's rely on GL2ES2 and let the user/impl. query isGLES2Compatible()
+        } else if(GLES2.equals(profile)) {
+            if(hasGL234Impl || hasGLES2Impl) {
+                if(esCtxUndef) {
+                    return GLES2;
+                }
+                return GLContext.getAvailableGLProfile(device, 2, GLContext.CTX_PROFILE_ES);
+            }
+          */
+        } else if(GLES1.equals(profile) && hasGLES1Impl && ( esCtxUndef || GLContext.isGLES1Available(device, isHardwareRasterizer))) {
             return GLES1;
         }
         return null;
@@ -1690,7 +1904,7 @@ public class GLProfile {
         if(null==device) {
             device = defaultDevice;
         }
-        String deviceKey = device.getUniqueID();
+        final String deviceKey = device.getUniqueID();
         HashMap<String /*GLProfile_name*/, GLProfile> map = deviceConn2ProfileMap.get(deviceKey);
         if( null != map ) {
             return map;
@@ -1715,11 +1929,13 @@ public class GLProfile {
         }
     }
 
-    private GLProfile(String profile, GLProfile profileImpl) {
+    private GLProfile(String profile, GLProfile profileImpl, boolean isHardwareRasterizer) {
         this.profile = profile;
         this.profileImpl = profileImpl;
+        this.isHardwareRasterizer = isHardwareRasterizer;
     }
 
-    private GLProfile profileImpl = null;
-    private String profile = null;
+    private final GLProfile profileImpl;
+    private final String profile;
+    private final boolean isHardwareRasterizer;
 }
diff --git a/src/jogl/classes/javax/media/opengl/GLRunnable.java b/src/jogl/classes/javax/media/opengl/GLRunnable.java
index cbd086c..141d07c 100644
--- a/src/jogl/classes/javax/media/opengl/GLRunnable.java
+++ b/src/jogl/classes/javax/media/opengl/GLRunnable.java
@@ -39,12 +39,14 @@ package javax.media.opengl;
  */
 public interface GLRunnable { 
     /**
-     * Called by the drawable to initiate one-shot OpenGL commands by the
-     * client, like {@link GLEventListener#display(GLAutoDrawable)}.
-     * 
-     * @param drawable the associated drawable the implementation shall use
-     * @return false if impl invalidates the back buffers, hence {@link GLAutoDrawable#display()} will 
-     *         issue another {@link GLEventListener#display(GLAutoDrawable)} call. Otherwise true.
+     * Initiate one-shot OpenGL commands with a valid current context, 
+     * processed by {@link GLAutoDrawable#display()}, enqueued by 
+     * {@link GLAutoDrawable#invoke(boolean, GLRunnable)}. 
+     *  
+     * @param drawable the associated drawable and current context for this call
+     * @return true if the GL [back] framebuffer remain intact by this runnable, otherwise false.
+     *         If returning false and hence the impl signals an invalidated back buffer,
+     *         another {@link GLEventListener#display(GLAutoDrawable)} call will be issued.
      */
     boolean run(GLAutoDrawable drawable);
 }
diff --git a/src/jogl/classes/javax/media/opengl/GLUniformData.java b/src/jogl/classes/javax/media/opengl/GLUniformData.java
index 5c9388b..475ff45 100644
--- a/src/jogl/classes/javax/media/opengl/GLUniformData.java
+++ b/src/jogl/classes/javax/media/opengl/GLUniformData.java
@@ -107,10 +107,10 @@ public class GLUniformData {
         if(data instanceof Buffer) {
             final int sz = rows*columns;
             final Buffer buffer = (Buffer)data;
-            if(buffer.limit()<sz || 0!=buffer.limit()%sz) {
-                throw new GLException("data buffer size invalid: new buffer limit: "+buffer.limit()+"\n\t"+this);
+            if(buffer.remaining()<sz || 0!=buffer.remaining()%sz) {
+                throw new GLException("remaining data buffer size invalid: buffer: "+buffer.toString()+"\n\t"+this);
             }
-            this.count=buffer.limit()/(rows*columns);
+            this.count=buffer.remaining()/(rows*columns);
         } else {
             if(isMatrix) {
                 throw new GLException("Atom type not allowed for matrix : "+this);
diff --git a/src/jogl/classes/javax/media/opengl/Threading.java b/src/jogl/classes/javax/media/opengl/Threading.java
index d0f3ebb..4788f9c 100644
--- a/src/jogl/classes/javax/media/opengl/Threading.java
+++ b/src/jogl/classes/javax/media/opengl/Threading.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2012 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -39,7 +40,7 @@
 
 package javax.media.opengl;
 
-import jogamp.opengl.*;
+import jogamp.opengl.ThreadingImpl;
 
 /** This API provides access to the threading model for the implementation of 
     the classes in this package.
@@ -101,17 +102,17 @@ import jogamp.opengl.*;
 
     In addition to specifying programmatically whether the single
     thread for OpenGL work is enabled, users may switch it on and off
-    using the system property <code>opengl.1thread</code>. Valid values
+    using the system property <code>jogl.1thread</code>. Valid values
     for this system property are:
 
     <PRE>
-    -Dopengl.1thread=false     Disable single-threading of OpenGL work
-    -Dopengl.1thread=true      Enable single-threading of OpenGL work (default -- on a newly-created worker thread)
-    -Dopengl.1thread=auto      Select default single-threading behavior (currently on)
-    -Dopengl.1thread=awt       Enable single-threading of OpenGL work on AWT event dispatch thread (current default on all
-                                 platforms, and also the default behavior older releases)
-    -Dopengl.1thread=worker    Enable single-threading of OpenGL work on newly-created worker thread (not suitable for Mac
-                                 OS X or X11 platforms, and risky on Windows in applet environments)
+    -Djogl.1thread=false     Disable single-threading of OpenGL work, hence use multithreading.
+    -Djogl.1thread=true      Enable single-threading of OpenGL work (default -- on a newly-created worker thread)
+    -Djogl.1thread=auto      Select default single-threading behavior (currently on)
+    -Djogl.1thread=awt       Enable single-threading of OpenGL work on AWT event dispatch thread (current default on all
+                             platforms, and also the default behavior older releases)
+    -Djogl.1thread=worker    Enable single-threading of OpenGL work on newly-created worker thread (not suitable for Mac
+                             OS X or X11 platforms, and risky on Windows in applet environments)
     </PRE>    
 */
 
@@ -133,21 +134,27 @@ public class Threading {
         once disabled, partly to discourage careless use of this
         method. This method should be called as early as possible in an
         application. */ 
-    public static void disableSingleThreading() {
+    public static final void disableSingleThreading() {
         ThreadingImpl.disableSingleThreading();
     }
 
     /** Indicates whether OpenGL work is being automatically forced to a
         single thread in this implementation. */
-    public static boolean isSingleThreaded() {
+    public static final boolean isSingleThreaded() {
         return ThreadingImpl.isSingleThreaded();
     }
 
+    /** Indicates whether the current thread is the designated toolkit thread,
+        if such semantics exists. */    
+    public static final boolean isToolkitThread() throws GLException {
+        return ThreadingImpl.isToolkitThread();
+    }
+    
     /** Indicates whether the current thread is the single thread on
         which this implementation of the javax.media.opengl APIs
         performs all of its OpenGL-related work. This method should only
         be called if the single-thread model is in effect. */
-    public static boolean isOpenGLThread() throws GLException {
+    public static final boolean isOpenGLThread() throws GLException {
         return ThreadingImpl.isOpenGLThread();
     }
 
@@ -159,8 +166,31 @@ public class Threading {
         thread (i.e., if <code>isOpenGLThread()</code> returns
         false). It is up to the end user to check to see whether the
         current thread is the OpenGL thread and either execute the
-        Runnable directly or perform the work inside it. */
-    public static void invokeOnOpenGLThread(Runnable r) throws GLException {
-        ThreadingImpl.invokeOnOpenGLThread(r);
+        Runnable directly or perform the work inside it. 
+     **/
+    public static final void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException {
+        ThreadingImpl.invokeOnOpenGLThread(wait, r);
+    }
+    
+    /**
+     * If {@link #isSingleThreaded()} <b>and</b> not {@link #isOpenGLThread()}
+     * <b>and</b> the <code>lock</code> is not being hold by this thread,
+     * invoke Runnable <code>r</code> on the OpenGL thread via {@link #invokeOnOpenGLThread(boolean, Runnable)}.
+     * <p>
+     * Otherwise invoke Runnable <code>r</code> on the current thread.
+     * </p>
+     * 
+     * @param wait set to true for waiting until Runnable <code>r</code> is finished, otherwise false. 
+     * @param r the Runnable to be executed
+     * @param lock optional lock object to be tested
+     * @throws GLException
+     */
+    public static final void invoke(boolean wait, Runnable r, Object lock) throws GLException {
+        if ( isSingleThreaded() && !isOpenGLThread() && 
+             ( null == lock || !Thread.holdsLock(lock) ) ) {
+            invokeOnOpenGLThread(wait, r);
+        } else {
+            r.run();
+        }
     }
 }
diff --git a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java
index e909416..a8d3c03 100644
--- a/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java
+++ b/src/jogl/classes/javax/media/opengl/awt/GLCanvas.java
@@ -57,8 +57,8 @@ import java.awt.geom.Rectangle2D;
 import java.awt.EventQueue;
 import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
-import java.util.List;
 
+import javax.media.nativewindow.AbstractGraphicsConfiguration;
 import javax.media.nativewindow.OffscreenLayerOption;
 import javax.media.nativewindow.WindowClosingProtocol;
 import javax.media.nativewindow.AbstractGraphicsDevice;
@@ -66,10 +66,7 @@ import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
 import javax.media.nativewindow.NativeSurface;
 import javax.media.nativewindow.NativeWindowFactory;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
-import javax.media.nativewindow.awt.AWTWindowClosingProtocol;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 
 import javax.media.opengl.GL;
 import javax.media.opengl.GLAnimatorControl;
@@ -88,16 +85,16 @@ import javax.media.opengl.Threading;
 
 import com.jogamp.common.GlueGenVersion;
 import com.jogamp.common.util.VersionUtil;
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
+import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol;
+import com.jogamp.nativewindow.awt.JAWTWindow;
 import com.jogamp.opengl.JoglVersion;
 
-import com.jogamp.common.util.locks.LockFactory;
-import com.jogamp.common.util.locks.RecursiveLock;
-
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.opengl.Debug;
 import jogamp.opengl.GLContextImpl;
 import jogamp.opengl.GLDrawableHelper;
-import jogamp.opengl.ThreadingImpl;
 
 // FIXME: Subclasses need to call resetGLFunctionAvailability() on their
 // context whenever the displayChanged() function is called on our
@@ -140,15 +137,11 @@ import jogamp.opengl.ThreadingImpl;
 @SuppressWarnings("serial")
 public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosingProtocol, OffscreenLayerOption {
 
-  private static final boolean DEBUG;
-
-  static {
-      DEBUG = Debug.debug("GLCanvas");
-  }
+  private static final boolean DEBUG = Debug.debug("GLCanvas");
 
   private GLDrawableHelper drawableHelper = new GLDrawableHelper();
   private AWTGraphicsConfiguration awtConfig;
-  private GLDrawable drawable;
+  private volatile GLDrawable drawable;
   private GLContextImpl context;
   private boolean sendReshape = false;
   
@@ -233,7 +226,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     super();
 
     if(null==capsReqUser) {
-        capsReqUser = new GLCapabilities(GLProfile.getDefault(GLProfile.getDefaultDesktopDevice()));
+        capsReqUser = new GLCapabilities(GLProfile.getDefault(GLProfile.getDefaultDevice()));
     } else {
         // don't allow the user to change data
         capsReqUser = (GLCapabilitiesImmutable) capsReqUser.cloneMutable();
@@ -330,14 +323,14 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
         final GraphicsConfiguration compatible = (null!=config)?config.getAWTGraphicsConfiguration():null;
         boolean equalCaps = config.getChosenCapabilities().equals(awtConfig.getChosenCapabilities());
         if(DEBUG) {
-            Exception e = new Exception("Info: Call Stack: "+Thread.currentThread().getName());
-            e.printStackTrace();
-            System.err.println("!!! Created Config (n): HAVE    GC "+chosen);
-            System.err.println("!!! Created Config (n): THIS    GC "+gc);
-            System.err.println("!!! Created Config (n): Choosen GC "+compatible);
-            System.err.println("!!! Created Config (n): HAVE    CF "+awtConfig);
-            System.err.println("!!! Created Config (n): Choosen CF "+config);
-            System.err.println("!!! Created Config (n): EQUALS CAPS "+equalCaps);
+            System.err.println(getThreadName()+": Info:");
+            System.err.println("Created Config (n): HAVE    GC "+chosen);
+            System.err.println("Created Config (n): THIS    GC "+gc);
+            System.err.println("Created Config (n): Choosen GC "+compatible);
+            System.err.println("Created Config (n): HAVE    CF "+awtConfig);
+            System.err.println("Created Config (n): Choosen CF "+config);
+            System.err.println("Created Config (n): EQUALS CAPS "+equalCaps);
+            Thread.dumpStack();
         }
 
         if (compatible != null) {
@@ -381,100 +374,71 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
   }
   
   public GLContext createContext(GLContext shareWith) {
-      drawableSync.lock();
-      try {
-        return (null != drawable) ? drawable.createContext(shareWith) : null;
-      } finally {
-        drawableSync.unlock();
-      }
+      return (null != drawable) ? drawable.createContext(shareWith) : null;
   }
 
   public void setRealized(boolean realized) {
   }
 
   public boolean isRealized() {
-      drawableSync.lock();
-      try {
-        return ( null != drawable ) ? drawable.isRealized() : false;
-      } finally {
-        drawableSync.unlock();
-      }
+     return ( null != drawable ) ? drawable.isRealized() : false;
+  }
+  protected final boolean isRealizedImpl() {
+      return ( null != drawable ) ? drawable.isRealized() : false;
   }
 
-  public int getDefaultCloseOperation() {
+  public WindowClosingMode getDefaultCloseOperation() {
       return awtWindowClosingProtocol.getDefaultCloseOperation();
   }
 
-  public int setDefaultCloseOperation(int op) {
+  public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
       return awtWindowClosingProtocol.setDefaultCloseOperation(op);
   }
 
   public void display() {
     if( !validateGLDrawable() ) {
         if(DEBUG) {
-            System.err.println("Info: GLCanvas display - skipped GL render, drawable not valid yet");
+            System.err.println(getThreadName()+": Info: GLCanvas display - skipped GL render, drawable not valid yet");
         }
         return; // not yet available ..
     }
-    maybeDoSingleThreadedWorkaround(displayOnEventDispatchThreadAction,
-                                    displayAction);
+    Threading.invoke(true, displayOnEventDispatchThreadAction, getTreeLock());
 
     awtWindowClosingProtocol.addClosingListenerOneShot();
   }
 
   private void dispose(boolean regenerate) {
-    drawableSync.lock();
-    try {
-        final GLAnimatorControl animator =  getAnimator();
-        if(DEBUG) {
-            Exception ex1 = new Exception("Info: dispose("+regenerate+") - START, hasContext " +
-                    (null!=context) + ", hasDrawable " + (null!=drawable)+", "+animator);
-            ex1.printStackTrace();
-        }
+    final GLAnimatorControl animator =  getAnimator();
+    if(DEBUG) {
+        System.err.println(getThreadName()+": Info: dispose("+regenerate+") - START, hasContext " +
+                (null!=context) + ", hasDrawable " + (null!=drawable)+", "+animator);
+        Thread.dumpStack();
+    }
 
-        if(null!=context) {
-            boolean animatorPaused = false;
-            if(null!=animator) {
-                // can't remove us from animator for recreational addNotify()
-                animatorPaused = animator.pause();
-            }
+    if(null!=context) {
+        boolean animatorPaused = false;
+        if(null!=animator) {
+            // can't remove us from animator for recreational addNotify()
+            animatorPaused = animator.pause();
+        }
 
-            disposeRegenerate=regenerate;
-
-            if (Threading.isSingleThreaded() &&
-                !Threading.isOpenGLThread()) {
-              // Workaround for termination issues with applets --
-              // sun.applet.AppletPanel should probably be performing the
-              // remove() call on the EDT rather than on its own thread
-              // Hint: User should run remove from EDT.
-              if (ThreadingImpl.isAWTMode() &&
-                  Thread.holdsLock(getTreeLock())) {
-                // The user really should not be invoking remove() from this
-                // thread -- but since he/she is, we can not go over to the
-                // EDT at this point. Try to destroy the context from here.
-                if(context.isCreated()) {
-                    drawableHelper.invokeGL(drawable, context, disposeAction, null);
-                }
-              } else if(context.isCreated()) {
-                Threading.invokeOnOpenGLThread(disposeOnEventDispatchThreadAction);
-              }
-            } else if(context.isCreated()) {
-              drawableHelper.invokeGL(drawable, context, disposeAction, null);
-            }
+        disposeRegenerate=regenerate;
 
-            if(animatorPaused) {
-                animator.resume();
-            }
-        }
-        if(!regenerate) {
-            disposeAbstractGraphicsDevice();
+        if(context.isCreated()) {
+            Threading.invoke(true, disposeOnEventDispatchThreadAction, getTreeLock());
         }
 
-        if(DEBUG) {
-            System.err.println("dispose("+regenerate+") - END, "+animator);
+        if(animatorPaused) {
+            animator.resume();
         }
-    } finally {
-        drawableSync.unlock();
+    }
+    
+    if(!regenerate) {
+        disposeAbstractGraphicsDevice();
+    }
+
+    if(DEBUG) {
+        System.err.println(getThreadName()+": dispose("+regenerate+") - END, "+animator);
     }
   }
 
@@ -519,8 +483,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     }
   }
 
-  RecursiveLock drawableSync = LockFactory.createRecursiveLock();
-
   /** Overridden to track when this component is added to a container.
       Subclasses which override this method must call
       super.addNotify() in their addNotify() method in order to
@@ -532,47 +494,42 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     @Override
   public void addNotify() {
     if(DEBUG) {
-        Exception ex1 = new Exception(Thread.currentThread().getName()+" - Info: addNotify - start, bounds: "+this.getBounds());
-        ex1.printStackTrace();
+        System.err.println(getThreadName()+": Info: addNotify - start, bounds: "+this.getBounds());
+        Thread.dumpStack();
     }
 
-    drawableSync.lock();
-    try {
-        /**
-         * 'super.addNotify()' determines the GraphicsConfiguration,
-         * while calling this class's overriden 'getGraphicsConfiguration()' method
-         * after which it creates the native peer.
-         * Hence we have to set the 'awtConfig' before since it's GraphicsConfiguration
-         * is being used in getGraphicsConfiguration().
-         * This code order also allows recreation, ie re-adding the GLCanvas.
-         */
-        awtConfig = chooseGraphicsConfiguration(capsReqUser, capsReqUser, chooser, device);
-        if(null==awtConfig) {
-            throw new GLException("Error: NULL AWTGraphicsConfiguration");
-        }
+    /**
+     * 'super.addNotify()' determines the GraphicsConfiguration,
+     * while calling this class's overriden 'getGraphicsConfiguration()' method
+     * after which it creates the native peer.
+     * Hence we have to set the 'awtConfig' before since it's GraphicsConfiguration
+     * is being used in getGraphicsConfiguration().
+     * This code order also allows recreation, ie re-adding the GLCanvas.
+     */
+    awtConfig = chooseGraphicsConfiguration(capsReqUser, capsReqUser, chooser, device);
+    if(null==awtConfig) {
+        throw new GLException("Error: NULL AWTGraphicsConfiguration");
+    }
 
-        // before native peer is valid: X11
-        disableBackgroundErase();
+    // before native peer is valid: X11
+    disableBackgroundErase();
 
-        // issues getGraphicsConfiguration() and creates the native peer
-        super.addNotify();
+    // issues getGraphicsConfiguration() and creates the native peer
+    super.addNotify();
 
-        // after native peer is valid: Windows
-        disableBackgroundErase();
+    // after native peer is valid: Windows
+    disableBackgroundErase();
 
-        if (!Beans.isDesignTime()) {
-            createDrawableAndContext();
-        }
+    if (!Beans.isDesignTime()) {
+        createDrawableAndContext();
+    }
 
-        // init drawable by paint/display makes the init sequence more equal
-        // for all launch flavors (applet/javaws/..)
-        // validateGLDrawable();
+    // init drawable by paint/display makes the init sequence more equal
+    // for all launch flavors (applet/javaws/..)
+    // validateGLDrawable();
 
-        if(DEBUG) {
-            System.err.println(Thread.currentThread().getName()+" - Info: addNotify - end: peer: "+getPeer());
-        }
-    } finally {
-       drawableSync.unlock();
+    if(DEBUG) {
+        System.err.println(getThreadName()+": Info: addNotify - end: peer: "+getPeer());
     }
   }
 
@@ -594,24 +551,17 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
   private boolean validateGLDrawable() {
     boolean realized = false;
     if (!Beans.isDesignTime()) {
-        drawableSync.lock();
-        try {
-            if ( null != drawable ) {
-                realized = drawable.isRealized();
-                if ( !realized && 0 < drawable.getWidth() * drawable.getHeight() ) {
-                    drawable.setRealized(true);
-                    realized = true;
-                    sendReshape=true; // ensure a reshape is being send ..
-                    if(DEBUG) {
-                        String msg = Thread.currentThread().getName()+" - Realized Drawable: "+drawable.toString();
-                        // System.err.println(msg);
-                        Throwable t = new Throwable(msg);
-                        t.printStackTrace();
-                    }
+        if ( null != drawable ) {
+            realized = drawable.isRealized();
+            if ( !realized && 0 < drawable.getWidth() * drawable.getHeight() ) {
+                drawable.setRealized(true);
+                realized = true;
+                sendReshape=true; // ensure a reshape is being send ..
+                if(DEBUG) {
+                    System.err.println(getThreadName()+": Realized Drawable: "+drawable.toString());
+                    Thread.dumpStack();
                 }
             }
-        } finally {
-           drawableSync.unlock();
         }
     }
     return realized;
@@ -629,8 +579,8 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     @Override
   public void removeNotify() {
     if(DEBUG) {
-        Exception ex1 = new Exception(Thread.currentThread().getName()+" - Info: removeNotify - start");
-        ex1.printStackTrace();
+        System.err.println(getThreadName()+": Info: removeNotify - start");
+        Thread.dumpStack();
     }
 
     awtWindowClosingProtocol.removeClosingListener();
@@ -638,7 +588,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     if (Beans.isDesignTime()) {
       super.removeNotify();
     } else {
-      drawableSync.lock();
       try {
         dispose(false);
       } finally {
@@ -646,11 +595,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
         drawable=null;
         awtConfig=null;
         super.removeNotify();
-        drawableSync.unlock();
       }
     }
     if(DEBUG) {
-        System.err.println(Thread.currentThread().getName()+" - Info: removeNotify - end, peer: "+getPeer());
+        System.err.println(getThreadName()+": Info: removeNotify - end, peer: "+getPeer());
     }
   }
 
@@ -745,7 +693,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
   }
 
   public void swapBuffers() {
-    maybeDoSingleThreadedWorkaround(swapBuffersOnEventDispatchThreadAction, swapBuffersAction);
+    Threading.invoke(true, swapBuffersOnEventDispatchThreadAction, getTreeLock());
   }
 
   public void setContextCreationFlags(int flags) {
@@ -777,30 +725,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
   }
 
   public NativeSurface getNativeSurface() {
-      drawableSync.lock();
-      try {
-        return (null != drawable) ? drawable.getNativeSurface() : null;
-      } finally {
-        drawableSync.unlock();
-      }
+    return (null != drawable) ? drawable.getNativeSurface() : null;
   }
 
   public long getHandle() {
-      drawableSync.lock();
-      try {
-        return (null != drawable) ? drawable.getHandle() : 0;
-      } finally {
-        drawableSync.unlock();
-      }
+    return (null != drawable) ? drawable.getHandle() : 0;
   }
 
   public GLDrawableFactory getFactory() {
-      drawableSync.lock();
-      try {
-        return (null != drawable) ? drawable.getFactory() : null;
-      } finally {
-        drawableSync.unlock();
-      }
+    return (null != drawable) ? drawable.getFactory() : null;
   }
 
   @Override
@@ -810,7 +743,6 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     
     return "AWT-GLCanvas[Realized "+isRealized()+
                           ",\n\t"+((null!=drawable)?drawable.getClass().getName():"null-drawable")+                         
-                          ",\n\tRealized "+isRealized()+
                           ",\n\tFactory   "+getFactory()+
                           ",\n\thandle    0x"+Long.toHexString(getHandle())+
                           ",\n\tDrawable size "+dw+"x"+dh+
@@ -823,26 +755,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
   // Internals only below this point
   //
 
-  private void maybeDoSingleThreadedWorkaround(Runnable eventDispatchThreadAction,
-                                               Runnable invokeGLAction) {
-    if (Threading.isSingleThreaded() &&
-        !Threading.isOpenGLThread()) {
-      Threading.invokeOnOpenGLThread(eventDispatchThreadAction);
-    } else {
-      drawableHelper.invokeGL(drawable, context, invokeGLAction, initAction);
-    }
-  }
-
-  class DisposeAction implements Runnable {
+  private boolean disposeRegenerate;
+  private final Runnable postDisposeAction = new Runnable() {
     public void run() {
-      drawableHelper.dispose(GLCanvas.this);
-
-      if(null!=context) {
-        context.makeCurrent(); // implicit wait for lock ..
-        context.destroy();
-        context=null;
-      }
-
+      context=null;
       if(null!=drawable) {
           final JAWTWindow jawtWindow = (JAWTWindow)drawable.getNativeSurface();
           drawable.setRealized(false);
@@ -859,43 +775,38 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
           createDrawableAndContext();
           
           if(DEBUG) {
-            System.err.println("GLCanvas.dispose(true): new drawable: "+drawable);
+            System.err.println(getThreadName()+": GLCanvas.dispose(true): new drawable: "+drawable);
           }
           validateGLDrawable(); // immediate attempt to recreate the drawable
       }
     }
-  }
-  private boolean disposeRegenerate;
-  private DisposeAction disposeAction = new DisposeAction();
+  }; 
 
-  private DisposeOnEventDispatchThreadAction disposeOnEventDispatchThreadAction =
-    new DisposeOnEventDispatchThreadAction();
-
-  class DisposeOnEventDispatchThreadAction implements Runnable {
+  private final Runnable disposeOnEventDispatchThreadAction = new Runnable() {
     public void run() {
-      drawableHelper.invokeGL(drawable, context, disposeAction, null);
+      drawableHelper.disposeGL(GLCanvas.this, drawable, context, postDisposeAction);      
     }
-  }
+  };
 
-  class DisposeAbstractGraphicsDeviceAction implements Runnable {
+  private final Runnable disposeAbstractGraphicsDeviceAction = new Runnable() {
     public void run() {
       if(null != awtConfig) {
-          final AbstractGraphicsDevice adevice = awtConfig.getScreen().getDevice();
+          final AbstractGraphicsConfiguration aconfig = awtConfig.getNativeGraphicsConfiguration();          
+          final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
           final String adeviceMsg;
           if(DEBUG) {
             adeviceMsg = adevice.toString();
           } else {
             adeviceMsg = null;  
           }
-          boolean closed = awtConfig.getScreen().getDevice().close();
+          boolean closed = adevice.close();
           if(DEBUG) {
-            System.err.println(Thread.currentThread().getName() + " - GLCanvas.dispose(false): closed GraphicsDevice: "+adeviceMsg+", result: "+closed);
+            System.err.println(getThreadName()+": GLCanvas.dispose(false): closed GraphicsDevice: "+adeviceMsg+", result: "+closed);
           }
           awtConfig=null;
       }
     }
-  }
-  private DisposeAbstractGraphicsDeviceAction disposeAbstractGraphicsDeviceAction = new DisposeAbstractGraphicsDeviceAction();
+  };
 
   /**
    * Disposes the AbstractGraphicsDevice within EDT,
@@ -917,18 +828,17 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     }
   }
 
-  class InitAction implements Runnable {
+  private final Runnable initAction = new Runnable() {
     public void run() {
       drawableHelper.init(GLCanvas.this);
     }
-  }
-  private InitAction initAction = new InitAction();
+  };
   
-  class DisplayAction implements Runnable {
+  private final Runnable displayAction = new Runnable() {
     public void run() {
       if (sendReshape) {
         if(DEBUG) {
-            System.err.println(Thread.currentThread().getName()+" - reshape: "+getWidth()+"x"+getHeight());
+            System.err.println(getThreadName()+": Reshape: "+getWidth()+"x"+getHeight());
         }
         // Note: we ignore the given x and y within the parent component
         // since we are drawing directly into this heavyweight component.
@@ -938,33 +848,28 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
 
       drawableHelper.display(GLCanvas.this);
     }
-  }
-  private DisplayAction displayAction = new DisplayAction();
+  };
 
-  class SwapBuffersAction implements Runnable {
+  private final Runnable swapBuffersAction = new Runnable() {
     public void run() {
       drawable.swapBuffers();
     }
-  }
-  private SwapBuffersAction swapBuffersAction = new SwapBuffersAction();
+  };
 
   // Workaround for ATI driver bugs related to multithreading issues
   // like simultaneous rendering via Animators to canvases that are
   // being resized on the AWT event dispatch thread
-  class DisplayOnEventDispatchThreadAction implements Runnable {
+  private final Runnable displayOnEventDispatchThreadAction = new Runnable() {
     public void run() {
-      drawableHelper.invokeGL(drawable, context, displayAction, initAction);
+        drawableHelper.invokeGL(drawable, context, displayAction, initAction);
     }
-  }
-  private DisplayOnEventDispatchThreadAction displayOnEventDispatchThreadAction =
-    new DisplayOnEventDispatchThreadAction();
-  class SwapBuffersOnEventDispatchThreadAction implements Runnable {
+  };
+  
+  private final Runnable swapBuffersOnEventDispatchThreadAction = new Runnable() {
     public void run() {
-      drawableHelper.invokeGL(drawable, context, swapBuffersAction, initAction);
-    }
-  }
-  private SwapBuffersOnEventDispatchThreadAction swapBuffersOnEventDispatchThreadAction =
-    new SwapBuffersOnEventDispatchThreadAction();
+        drawableHelper.invokeGL(drawable, context, swapBuffersAction, initAction);
+    }  
+  };
 
   // Disables the AWT's erasing of this Canvas's background on Windows
   // in Java SE 6. This internal API is not available in previous
@@ -999,7 +904,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
       }
       disableBackgroundEraseInitialized = true;
       if(DEBUG) {
-        System.err.println("GLCanvas: TK disableBackgroundErase method found: "+
+        System.err.println(getThreadName()+": GLCanvas: TK disableBackgroundErase method found: "+
                 (null!=disableBackgroundEraseMethod));
       }
     }
@@ -1011,7 +916,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
         t = e;
       }
       if(DEBUG) {
-        System.err.println("GLCanvas: TK disableBackgroundErase error: "+t);
+        System.err.println(getThreadName()+": GLCanvas: TK disableBackgroundErase error: "+t);
       }
     }
   }
@@ -1074,6 +979,10 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     return config;
   }
   
+  protected static String getThreadName() {
+    return Thread.currentThread().getName();
+  }
+  
   /**
    * A most simple JOGL AWT test entry
    */
@@ -1083,16 +992,12 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     // System.err.println(NativeWindowVersion.getInstance());
     System.err.println(JoglVersion.getInstance());
 
-    GLDrawableFactory factory = GLDrawableFactory.getDesktopFactory();
-    List<GLCapabilitiesImmutable> availCaps = factory.getAvailableCapabilities(null);
-    for(int i=0; i<availCaps.size(); i++) {
-        System.err.println(availCaps.get(i));
-    }
+    System.err.println(JoglVersion.getDefaultOpenGLInfo(null).toString());
 
-    GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault(GLProfile.getDefaultDesktopDevice()) );
-    Frame frame = new Frame("JOGL AWT Test");
+    final GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault(GLProfile.getDefaultDevice()) );
+    final Frame frame = new Frame("JOGL AWT Test");
 
-    GLCanvas glCanvas = new GLCanvas(caps);
+    final GLCanvas glCanvas = new GLCanvas(caps);
     frame.add(glCanvas);
     frame.setSize(128, 128);
 
@@ -1101,24 +1006,15 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
             GL gl = drawable.getGL();
             System.err.println(JoglVersion.getGLInfo(gl, null));
         }
-
-        public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
-        }
-
-        public void display(GLAutoDrawable drawable) {
-        }
-
-        public void dispose(GLAutoDrawable drawable) {
-        }
+        public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
+        public void display(GLAutoDrawable drawable) { }
+        public void dispose(GLAutoDrawable drawable) { }
     });
 
-    final Frame _frame = frame;
-    final GLCanvas _glCanvas = glCanvas;
-
     try {
         javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
             public void run() {
-                _frame.setVisible(true);
+                frame.setVisible(true);
             }});
     } catch (Throwable t) {
         t.printStackTrace();
@@ -1127,9 +1023,7 @@ public class GLCanvas extends Canvas implements AWTGLAutoDrawable, WindowClosing
     try {
         javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
             public void run() {
-                _frame.setVisible(false);
-                _frame.remove(_glCanvas);
-                _frame.dispose();
+                frame.dispose();
             }});
     } catch (Throwable t) {
         t.printStackTrace();
diff --git a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java
index dd55588..db3f189 100644
--- a/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java
+++ b/src/jogl/classes/javax/media/opengl/awt/GLJPanel.java
@@ -43,8 +43,6 @@ package javax.media.opengl.awt;
 import java.nio.ByteBuffer;
 import java.nio.IntBuffer;
 import java.beans.Beans;
-import java.security.AccessControlContext;
-import java.security.AccessController;
 
 import java.awt.Color;
 import java.awt.EventQueue;
@@ -62,7 +60,7 @@ import javax.swing.JPanel;
 import javax.media.nativewindow.WindowClosingProtocol;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.NativeSurface;
-import javax.media.nativewindow.awt.AWTWindowClosingProtocol;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 
 import javax.media.opengl.DefaultGLCapabilitiesChooser;
 import javax.media.opengl.GL;
@@ -82,6 +80,8 @@ import javax.media.opengl.GLPbuffer;
 import javax.media.opengl.GLProfile;
 import javax.media.opengl.GLRunnable;
 import javax.media.opengl.Threading;
+
+import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol;
 import com.jogamp.opengl.util.FBObject;
 import com.jogamp.opengl.util.GLBuffers;
 
@@ -90,7 +90,6 @@ import jogamp.opengl.GLContextImpl;
 import jogamp.opengl.GLDrawableFactoryImpl;
 import jogamp.opengl.GLDrawableHelper;
 import jogamp.opengl.GLDrawableImpl;
-import jogamp.opengl.ThreadingImpl;
 import jogamp.opengl.awt.Java2D;
 import jogamp.opengl.awt.Java2DGLContext;
 
@@ -125,9 +124,9 @@ import jogamp.opengl.awt.Java2DGLContext;
  *  </P>
 */
 
+ at SuppressWarnings("serial")
 public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosingProtocol {
   private static final boolean DEBUG = Debug.debug("GLJPanel");
-  private static final boolean VERBOSE = Debug.verbose();
 
   private GLDrawableHelper drawableHelper = new GLDrawableHelper();
   private volatile boolean isInitialized;
@@ -153,22 +152,20 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
   // Used by all backends either directly or indirectly to hook up callbacks
   private Updater updater = new Updater();
 
-  private static final AccessControlContext localACC = AccessController.getContext();
-
   // Turns off the pbuffer-based backend (used by default, unless the
   // Java 2D / OpenGL pipeline is in use)
   private static boolean hardwareAccelerationDisabled =
-    Debug.isPropertyDefined("jogl.gljpanel.nohw", true, localACC);
+    Debug.isPropertyDefined("jogl.gljpanel.nohw", true);
 
   // Turns off the fallback to software-based rendering from
   // pbuffer-based rendering
   private static boolean softwareRenderingDisabled =
-    Debug.isPropertyDefined("jogl.gljpanel.nosw", true, localACC);
+    Debug.isPropertyDefined("jogl.gljpanel.nosw", true);
 
   // Indicates whether the Java 2D OpenGL pipeline is enabled
   private boolean oglPipelineEnabled =
     Java2D.isOGLPipelineActive() &&
-    !Debug.isPropertyDefined("jogl.gljpanel.noogl", true, localACC);
+    !Debug.isPropertyDefined("jogl.gljpanel.noogl", true);
 
   // For handling reshape events lazily
   // private int reshapeX;
@@ -244,7 +241,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
         if (userCapsRequest != null) {
             caps = (GLCapabilities) userCapsRequest.cloneMutable();
         } else {
-            caps = new GLCapabilities(GLProfile.getDefault(GLProfile.getDefaultDesktopDevice()));
+            caps = new GLCapabilities(GLProfile.getDefault(GLProfile.getDefaultDevice()));
         }
         caps.setDoubleBuffered(false);
         offscreenCaps = caps;
@@ -270,70 +267,35 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
   }
 
-  protected void dispose(boolean regenerate) {
+  protected void dispose() {
     if(DEBUG) {
-        Exception ex1 = new Exception("Info: dispose("+regenerate+") - start");
-        ex1.printStackTrace();
+        System.err.println(getThreadName()+": GLJPanel.dispose() - start");
+        // Thread.dumpStack();
     }
 
-    if (backend != null) {
+    if (backend != null && backend.getContext() != null) {
       boolean animatorPaused = false;
       GLAnimatorControl animator =  getAnimator();
       if(null!=animator) {
-        if(regenerate) {
-            animatorPaused = animator.pause();
-        }
+        animatorPaused = animator.pause();
       }
 
-      disposeRegenerate=regenerate;
-      disposeContext=backend.getContext();
-      disposeDrawable=backend.getDrawable();
-
-      if (Threading.isSingleThreaded() &&
-          !Threading.isOpenGLThread()) {
-          // Workaround for termination issues with applets --
-          // sun.applet.AppletPanel should probably be performing the
-          // remove() call on the EDT rather than on its own thread
-          if (ThreadingImpl.isAWTMode() &&
-              Thread.holdsLock(getTreeLock())) {
-            // The user really should not be invoking remove() from this
-            // thread -- but since he/she is, we can not go over to the
-            // EDT at this point. Try to destroy the context from here.
-            if(disposeContext.isCreated()) {
-                drawableHelper.invokeGL(disposeDrawable, disposeContext, disposeAction, null);
-            }
-          } else if(disposeContext.isCreated()) {
-            Threading.invokeOnOpenGLThread(disposeOnEventDispatchThreadAction);
-          }
-      } else if(disposeContext.isCreated()) {
-          drawableHelper.invokeGL(disposeDrawable, disposeContext, disposeAction, null);
+      if(backend.getContext().isCreated()) {      
+          Threading.invoke(true, disposeAction, getTreeLock());
       }
-
-      if(!regenerate) {
-          AbstractGraphicsDevice adevice = disposeDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
-          String adeviceMsg=null;
-          if(DEBUG) {
-            adeviceMsg = adevice.toString();
-          }
-          // boolean closed = adevice.close();
-          boolean closed = false;
-          if (DEBUG) {
-              System.err.println("GLJPanel.dispose(false): closed GraphicsDevice: " + adeviceMsg + ", result: " + closed);
-          }
-      }
-
-      backend.setContext(disposeContext);
-      if(null==disposeContext) {
-        isInitialized = false;
+      if(null != backend) {
+          // not yet destroyed due to backend.isUsingOwnThreadManagment() == true
+          backend.destroy();
+          isInitialized = false;
       }
 
       if(animatorPaused) {
         animator.resume();
-      }
+      }     
     }
-
+    
     if(DEBUG) {
-        System.err.println("dispose("+regenerate+") - stop");
+        System.err.println(getThreadName()+": GLJPanel.dispose() - stop");
     }
   }
 
@@ -349,8 +311,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       super.paintComponent() in their paintComponent() method in order
       to function properly. <P>
 
-      <B>Overrides:</B>
       <DL><DD><CODE>paintComponent</CODE> in class <CODE>javax.swing.JComponent</CODE></DD></DL> */
+  @Override
   protected void paintComponent(final Graphics g) {
     if (Beans.isDesignTime()) {
       // Make GLJPanel behave better in NetBeans GUI builder
@@ -390,20 +352,22 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     updater.setGraphics(g);
+    
     backend.doPaintComponent(g);
   }
 
+  
   /** Overridden to track when this component is added to a container.
       Subclasses which override this method must call
       super.addNotify() in their addNotify() method in order to
       function properly. <P>
 
-      <B>Overrides:</B>
       <DL><DD><CODE>addNotify</CODE> in class <CODE>java.awt.Component</CODE></DD></DL> */
+  @Override
   public void addNotify() {
     super.addNotify();
     if (DEBUG) {
-      System.err.println("GLJPanel.addNotify()");
+      System.err.println(getThreadName()+": GLJPanel.addNotify()");
     }
   }
 
@@ -412,26 +376,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       super.removeNotify() in their removeNotify() method in order to
       function properly. <P>
 
-      <B>Overrides:</B>
       <DL><DD><CODE>removeNotify</CODE> in class <CODE>java.awt.Component</CODE></DD></DL> */
+  @Override
   public void removeNotify() {
-    if(DEBUG) {
-        Exception ex1 = new Exception("Info: removeNotify - start");
-        ex1.printStackTrace();
-    }
-
     awtWindowClosingProtocol.removeClosingListener();
 
-    dispose(false);
-    if (backend != null) {
-      backend.destroy();
-      backend = null;
-    }
-    isInitialized = false;
+    dispose();
     super.removeNotify();
-    if(DEBUG) {
-        System.err.println("Info: removeNotify - end");
-    }
   }
 
   /** Overridden to cause {@link GLDrawableHelper#reshape} to be
@@ -439,9 +390,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       which override this method must call super.reshape() in
       their reshape() method in order to function properly. <P>
 
-      <B>Overrides:</B>
       <DL><DD><CODE>reshape</CODE> in class <CODE>java.awt.Component</CODE></DD></DL> */
-  public void reshape(int x, int y, int width, int height) {
+  @SuppressWarnings("deprecation")
+  @Override
+public void reshape(int x, int y, int width, int height) {
     super.reshape(x, y, width, height);
 
     // reshapeX = x;
@@ -451,6 +403,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     handleReshape = true;
   }
 
+  @Override
   public void setOpaque(boolean opaque) {
     if (backend != null) {
       backend.setOpaque(opaque);
@@ -483,7 +436,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
   }
 
   public GLContext createContext(GLContext shareWith) {
-    return backend.createContext(shareWith);
+    return (null != backend) ? backend.createContext(shareWith) : null;
   }
 
   public void setRealized(boolean realized) {
@@ -644,11 +597,11 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     awtWindowClosingProtocol.addClosingListenerOneShot();
   }
 
-  public int getDefaultCloseOperation() {
+  public WindowClosingMode getDefaultCloseOperation() {
       return awtWindowClosingProtocol.getDefaultCloseOperation();
   }
 
-  public int setDefaultCloseOperation(int op) {
+  public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
       return awtWindowClosingProtocol.setDefaultCloseOperation(op);
   }
 
@@ -657,7 +610,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     panelHeight = reshapeHeight;
 
     if (DEBUG) {
-      System.err.println("GLJPanel.handleReshape: (w,h) = (" +
+      System.err.println(getThreadName()+": GLJPanel.handleReshape: (w,h) = (" +
                          panelWidth + "," + panelHeight + ")");
     }
 
@@ -665,7 +618,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     backend.handleReshape();
     handleReshape = false;
   }
-
+  
   // This is used as the GLEventListener for the pbuffer-based backend
   // as well as the callback mechanism for the other backends
   class Updater implements GLEventListener {
@@ -692,8 +645,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
         return;
       }
       if (sendReshape) {
-        if (DEBUG||VERBOSE) {
-          System.err.println("display: reshape(" + viewportX + "," + viewportY + " " + panelWidth + "x" + panelHeight + ")");
+        if (DEBUG) {
+          System.err.println(getThreadName()+": GLJPanel.display: reshape(" + viewportX + "," + viewportY + " " + panelWidth + "x" + panelHeight + ")");
         }
         drawableHelper.reshape(GLJPanel.this, viewportX, viewportY, panelWidth, panelHeight);
         sendReshape = false;
@@ -715,62 +668,39 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     return "AWT-GLJPanel[ "+((null!=backend)?backend.getDrawable().getClass().getName():"null-drawable")+"]";
   }
 
-  private boolean disposeRegenerate;
-  private GLContext disposeContext;
-  private GLDrawable disposeDrawable;
-  private DisposeAction disposeAction = new DisposeAction();
-
-  class DisposeAction implements Runnable {
+  private final Runnable postDisposeAction = new Runnable() {
       public void run() {
-          updater.dispose(GLJPanel.this);
-
-          if (null != disposeContext) {
-              disposeContext.destroy();
-              disposeContext = null;
-          }
-          if (null != disposeDrawable) {
-              disposeDrawable.setRealized(false);
-          }
-          if (null != disposeDrawable) {
-              if (disposeRegenerate) {
-                  disposeDrawable.setRealized(true);
-                  disposeContext = (GLContextImpl) disposeDrawable.createContext(shareWith);
-                  disposeContext.setSynchronized(true);
-              }
+          if (backend != null && !backend.isUsingOwnThreadManagment()) {
+              backend.destroy();
+              backend = null;
+              isInitialized = false;      
           }
       }
-  }
+  }; 
 
-  private DisposeOnEventDispatchThreadAction disposeOnEventDispatchThreadAction =
-    new DisposeOnEventDispatchThreadAction();
-
-  class DisposeOnEventDispatchThreadAction implements Runnable {
+  private final Runnable disposeAction = new Runnable() {
     public void run() {
-      drawableHelper.invokeGL(disposeDrawable, disposeContext, disposeAction, null);
+      drawableHelper.disposeGL(GLJPanel.this, backend.getDrawable(), backend.getContext(), postDisposeAction);
     }
-  }
-
+  }; 
 
-  class InitAction implements Runnable {
+  private final Runnable updaterInitAction = new Runnable() {
     public void run() {
       updater.init(GLJPanel.this);
     }
-  }
-  private InitAction initAction = new InitAction();
+  };
 
-  class DisplayAction implements Runnable {
+  private final Runnable updaterDisplayAction = new Runnable() {
     public void run() {
       updater.display(GLJPanel.this);
     }
-  }
-  private DisplayAction displayAction = new DisplayAction();
+  };
 
-  class PaintImmediatelyAction implements Runnable {
+  private final Runnable paintImmediatelyAction = new Runnable() {
     public void run() {
       paintImmediately(0, 0, getWidth(), getHeight());
     }
-  }
-  private PaintImmediatelyAction paintImmediatelyAction = new PaintImmediatelyAction();
+  }; 
 
   private int getNextPowerOf2(int number) {
     // Workaround for problems where 0 width or height are transiently
@@ -787,6 +717,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     return tmp[0];
   }
 
+  protected static String getThreadName() {
+    return Thread.currentThread().getName();
+  }
+    
   //----------------------------------------------------------------------
   // Implementations of the various backends
   //
@@ -795,6 +729,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
   // software / pixmap rendering, pbuffer-based acceleration, Java 2D
   // / JOGL bridge
   static interface Backend {
+    // Create, Destroy, ..
+    public boolean isUsingOwnThreadManagment();
+    
     // Called each time the backend needs to initialize itself
     public void initialize();
 
@@ -854,7 +791,6 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     protected int                   readBackWidthInPixels;
     protected int                   readBackHeightInPixels;
 
-    private int awtFormat;
     private int glFormat;
     private int glType;
 
@@ -907,13 +843,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
             switch (awtFormat) {
             case BufferedImage.TYPE_3BYTE_BGR:
               glFormat = GL2.GL_BGR;
-              glType   = GL2.GL_UNSIGNED_BYTE;
+              glType   = GL.GL_UNSIGNED_BYTE;
               readBackBytes = ByteBuffer.allocate(readBackWidthInPixels * readBackHeightInPixels * 3);
               break;
 
             case BufferedImage.TYPE_INT_RGB:
             case BufferedImage.TYPE_INT_ARGB:
-              glFormat = GL2.GL_BGRA;
+              glFormat = GL.GL_BGRA;
               glType   = getGLPixelType();
               readBackInts = IntBuffer.allocate(readBackWidthInPixels * readBackHeightInPixels);
               break;
@@ -1023,7 +959,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     private GLDrawableImpl offscreenDrawable;
     private GLContextImpl offscreenContext;
 
+    public boolean isUsingOwnThreadManagment() { return false; }
+    
     public void initialize() {
+      if(DEBUG) {
+          System.err.println(getThreadName()+": SoftwareBackend: initialize()");
+      }
       // Fall-through path: create an offscreen context instead
       offscreenDrawable = (GLDrawableImpl) factory.createOffscreenDrawable(
                                                 null /* default platform device */,
@@ -1040,18 +981,25 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     public void destroy() {
+      if(DEBUG) {
+          System.err.println(getThreadName()+": SoftwareBackend: destroy() - offscreenContext: "+(null!=offscreenContext)+" - offscreenDrawable: "+(null!=offscreenDrawable));
+      }
       if (offscreenContext != null) {
         offscreenContext.destroy();
         offscreenContext = null;
       }
       if (offscreenDrawable != null) {
+        final AbstractGraphicsDevice adevice = offscreenDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
         offscreenDrawable.destroy();
         offscreenDrawable = null;
+        if(null != adevice) {
+            adevice.close();
+        }
       }
     }
 
     public GLContext createContext(GLContext shareWith) {
-      return offscreenDrawable.createContext(shareWith);
+      return (null != offscreenDrawable) ? offscreenDrawable.createContext(shareWith) : null;
     }
 
     public void setContext(GLContext ctx) {
@@ -1093,7 +1041,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     protected void doPaintComponentImpl() {
-      drawableHelper.invokeGL(offscreenDrawable, offscreenContext, displayAction, initAction);
+      drawableHelper.invokeGL(offscreenDrawable, offscreenContext, updaterDisplayAction, updaterInitAction);
     }
 
     protected int getGLPixelType() {
@@ -1110,10 +1058,15 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     private int       pbufferWidth  = 256;
     private int       pbufferHeight = 256;
 
+    public boolean isUsingOwnThreadManagment() { return false; }
+    
     public void initialize() {
       if (pbuffer != null) {
         throw new InternalError("Creating pbuffer twice without destroying it (memory leak / correctness bug)");
       }
+      if(DEBUG) {
+          System.err.println(getThreadName()+": PbufferBackend: initialize()");
+      }
       try {
         pbuffer = factory.createGLPbuffer(null /* default platform device */,
                                           offscreenCaps,
@@ -1127,7 +1080,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       } catch (GLException e) {
         if (DEBUG) {
           e.printStackTrace();
-          System.err.println("Info: GLJPanel: Falling back on software rendering because of problems creating pbuffer");
+          System.err.println(getThreadName()+": GLJPanel: Falling back on software rendering because of problems creating pbuffer");
         }
         hardwareAccelerationDisabled = true;
         backend = null;
@@ -1137,6 +1090,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     public void destroy() {
+      if(DEBUG) {
+          System.err.println(getThreadName()+": PbufferBackend: destroy() - pbuffer: "+(null!=pbuffer));
+      }
       if (pbuffer != null) {
         pbuffer.destroy();
         pbuffer = null;
@@ -1144,7 +1100,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     public GLContext createContext(GLContext shareWith) {
-      return pbuffer.createContext(shareWith);
+      return (null != pbuffer) ? pbuffer.createContext(shareWith) : null;
     }
 
     public void setContext(GLContext ctx) {
@@ -1186,7 +1142,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       if ((panelWidth > pbufferWidth)                  || (panelHeight > pbufferHeight) ||
           (panelWidth < (pbufferWidth / shrinkFactor)) || (panelHeight < (pbufferHeight / shrinkFactor))) {
         if (DEBUG) {
-          System.err.println("Resizing pbuffer from (" + pbufferWidth + ", " + pbufferHeight + ") " +
+          System.err.println(getThreadName()+": Resizing pbuffer from (" + pbufferWidth + ", " + pbufferHeight + ") " +
                              " to fit (" + panelWidth + ", " + panelHeight + ")");
         }
         // Must destroy and recreate pbuffer to fit
@@ -1204,7 +1160,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
             readBackWidthInPixels  = Math.max(1, panelWidth);
             readBackHeightInPixels = Math.max(1, panelHeight);
             if (DEBUG) {
-              System.err.println("Warning: falling back to software rendering due to bugs in OpenGL drivers");
+              System.err.println(getThreadName()+": Warning: falling back to software rendering due to bugs in OpenGL drivers");
               e.printStackTrace();
             }
             createAndInitializeBackend();
@@ -1216,7 +1172,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
         pbufferWidth = getNextPowerOf2(panelWidth);
         pbufferHeight = getNextPowerOf2(panelHeight);
         if (DEBUG && !hardwareAccelerationDisabled) {
-          System.err.println("New pbuffer size is (" + pbufferWidth + ", " + pbufferHeight + ")");
+          System.err.println(getThreadName()+": New pbuffer size is (" + pbufferWidth + ", " + pbufferHeight + ")");
         }
         initialize();
       }
@@ -1258,7 +1214,6 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     private Object j2dSurface;
     // Graphics object being used during Java2D update action
     // (absolutely essential to cache this)
-    private Graphics cached2DGraphics;
     // No-op context representing the Java2D OpenGL context
     private GLContext j2dContext;
     // Context associated with no-op drawable representing the JOGL
@@ -1301,7 +1256,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     // comment related to Issue 274 below
     private GraphicsConfiguration workaroundConfig;
 
+    public boolean isUsingOwnThreadManagment() { return true; }
+    
     public void initialize() {
+      if(DEBUG) {
+          System.err.println(getThreadName()+": J2DOGL: initialize()");
+      }
       // No-op in this implementation; everything is done lazily
       isInitialized = true;
     }
@@ -1309,6 +1269,9 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     public void destroy() {
       Java2D.invokeWithOGLContextCurrent(null, new Runnable() {
           public void run() {
+            if(DEBUG) {
+                System.err.println(getThreadName()+": J2DOGL: destroy() - joglContext: "+(null!=joglContext)+" - joglDrawable: "+(null!=joglDrawable));
+            }
             if (joglContext != null) {
               joglContext.destroy();
               joglContext = null;
@@ -1327,9 +1290,10 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
     }
 
     public GLContext createContext(GLContext shareWith) {
-      // FIXME: should implement this, but it was not properly
-      // implemented before the refactoring anyway
-      throw new GLException("Not yet implemented");
+      if(null != shareWith) {
+          throw new GLException("J2DOGLBackend cannot create context w/ additional shared context, since it already needs to share the context w/ J2D.");
+      }
+      return (null != joglDrawable && null != j2dContext) ? joglDrawable.createContext(j2dContext) : null;
     }
 
     public void setContext(GLContext ctx) {
@@ -1351,7 +1315,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
 
     public GLProfile getGLProfile() {
       // FIXME: should do better than this; is it possible to using only platform-independent code?
-      return GLProfile.getDefault(GLProfile.getDefaultDesktopDevice());
+      return GLProfile.getDefault(GLProfile.getDefaultDevice());
     }
 
     public void handleReshape() {
@@ -1365,13 +1329,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
       Rectangle r = Java2D.getOGLScissorBox(g);
 
       if (r == null) {
-        if (DEBUG && VERBOSE) {
-          System.err.println("Java2D.getOGLScissorBox() returned null");
+        if (DEBUG) {
+          System.err.println(getThreadName()+": Java2D.getOGLScissorBox() returned null");
         }
         return false;
       }
-      if (DEBUG && VERBOSE) {
-        System.err.println("GLJPanel: gl.glScissor(" + r.x + ", " + r.y + ", " + r.width + ", " + r.height + ")");
+      if (DEBUG) {
+        System.err.println(getThreadName()+": GLJPanel: gl.glScissor(" + r.x + ", " + r.y + ", " + r.width + ", " + r.height + ")");
       }
 
       gl.glScissor(r.x, r.y, r.width, r.height);
@@ -1383,7 +1347,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
           (viewportY != oglViewport.y)) {
         sendReshape = true;
         if (DEBUG) {
-          System.err.println("Sending reshape because viewport changed");
+          System.err.println(getThreadName()+": Sending reshape because viewport changed");
           System.err.println("  viewportX (" + viewportX + ") ?= oglViewport.x (" + oglViewport.x + ")");
           System.err.println("  viewportY (" + viewportY + ") ?= oglViewport.y (" + oglViewport.y + ")");
         }
@@ -1411,15 +1375,15 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
               // Need to do workarounds
               fbObjectWorkarounds = true;
               createNewDepthBuffer = true;
-              if (DEBUG || VERBOSE) {
-                  System.err.println("GLJPanel: ERR GL_FRAMEBUFFER_BINDING: Discovered Invalid J2D FBO("+frameBuffer[0]+"): "+FBObject.getStatusString(status) +
+              if (DEBUG) {
+                  System.err.println(getThreadName()+": GLJPanel: ERR GL_FRAMEBUFFER_BINDING: Discovered Invalid J2D FBO("+frameBuffer[0]+"): "+FBObject.getStatusString(status) +
                                      ", frame_buffer_object workarounds to be necessary");
               }
           } else {
             // Don't need the frameBufferTexture temporary any more
             frameBufferTexture = null;
-            if (DEBUG || VERBOSE) {
-              System.err.println("GLJPanel: OK GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]);
+            if (DEBUG) {
+              System.err.println(getThreadName()+": GLJPanel: OK GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]);
             }
           }
         }
@@ -1443,7 +1407,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                     
           gl.glGenRenderbuffers(1, frameBufferDepthBuffer, 0);
           if (DEBUG) {
-            System.err.println("GLJPanel: Generated frameBufferDepthBuffer " + frameBufferDepthBuffer[0] +
+            System.err.println(getThreadName()+": GLJPanel: Generated frameBufferDepthBuffer " + frameBufferDepthBuffer[0] +
                                " with width " + width[0] + ", height " + height[0]);
           }
                     
@@ -1465,8 +1429,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                                     fboTextureTarget,
                                     frameBufferTexture[0],
                                     0);
-          if (DEBUG && VERBOSE) {
-            System.err.println("GLJPanel: frameBufferDepthBuffer: " + frameBufferDepthBuffer[0]);
+          if (DEBUG) {
+            System.err.println(getThreadName()+": GLJPanel: frameBufferDepthBuffer: " + frameBufferDepthBuffer[0]);
           }
           gl.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER,
                                        GL.GL_DEPTH_ATTACHMENT,
@@ -1482,8 +1446,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
           }
         }
       } else {
-        if (DEBUG && VERBOSE) {
-          System.err.println("GLJPanel: Setting up drawBuffer " + drawBuffer[0] +
+        if (DEBUG) {
+          System.err.println(getThreadName()+": GLJPanel: Setting up drawBuffer " + drawBuffer[0] +
                              " and readBuffer " + readBuffer[0]);
         }
 
@@ -1540,15 +1504,15 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
 
       Java2D.invokeWithOGLContextCurrent(g, new Runnable() {
           public void run() {
-            if (DEBUG && VERBOSE) {
-              System.err.println("-- In invokeWithOGLContextCurrent");
+            if (DEBUG) {
+              System.err.println(getThreadName()+": GLJPanel.invokeWithOGLContextCurrent");
             }
 
             // Create no-op context representing Java2D context
             if (j2dContext == null) {
               j2dContext = factory.createExternalGLContext();
-              if (DEBUG||VERBOSE) {
-                System.err.println("-- Created External Context: "+j2dContext);
+              if (DEBUG) {
+                System.err.println(getThreadName()+": GLJPanel.Created External Context: "+j2dContext);
               }
               if (DEBUG) {
 //                j2dContext.setGL(new DebugGL2(j2dContext.getGL().getGL2()));
@@ -1571,7 +1535,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                   //          (getGLInteger(gl, GL2.GL_DEPTH_BITS)       < offscreenCaps.getDepthBits())      ||
                   (getGLInteger(gl, GL.GL_STENCIL_BITS)     < offscreenCaps.getStencilBits())) {
                 if (DEBUG) {
-                  System.err.println("GLJPanel: Falling back to pbuffer-based support because Java2D context insufficient");
+                  System.err.println(getThreadName()+": GLJPanel: Falling back to pbuffer-based support because Java2D context insufficient");
                   System.err.println("                    Available              Required");
                   System.err.println("GL_RED_BITS         " + getGLInteger(gl, GL.GL_RED_BITS)         + "              " + offscreenCaps.getRedBits());
                   System.err.println("GL_GREEN_BITS       " + getGLInteger(gl, GL.GL_GREEN_BITS)       + "              " + offscreenCaps.getGreenBits());
@@ -1588,15 +1552,13 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                 backend = null;
                 oglPipelineEnabled = false;
                 handleReshape = true;
-                j2dContext.release();
                 j2dContext.destroy();
                 j2dContext = null;
                 return;
               }
-              j2dContext.release();
+            } else {
+              j2dContext.makeCurrent();
             }
-
-            j2dContext.makeCurrent();
             try {
               captureJ2DState(j2dContext.getGL(), g);
               Object curSurface = Java2D.getOGLSurfaceIdentifier(g);
@@ -1607,14 +1569,14 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                     joglContext = null;
                     joglDrawable = null;
                     sendReshape = true;
-                    if (DEBUG||VERBOSE) {
-                      System.err.println("Sending reshape because surface changed");
+                    if (DEBUG) {
+                      System.err.println(getThreadName()+": Sending reshape because surface changed");
                       System.err.println("New surface = " + curSurface);
                     }
                   }
                   j2dSurface = curSurface;
-                  if (DEBUG || VERBOSE) {
-                      System.err.print("-- Surface type: ");
+                  if (DEBUG) {
+                      System.err.print(getThreadName()+": Surface type: ");
                       int surfaceType = Java2D.getOGLSurfaceType(g);
                       if (surfaceType == Java2D.UNDEFINED) {
                         System.err.println("UNDEFINED");
@@ -1637,19 +1599,17 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                   AbstractGraphicsDevice device = j2dContext.getGLDrawable().getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
                   if (factory.canCreateExternalGLDrawable(device)) {
                     joglDrawable = factory.createExternalGLDrawable();
-                    // FIXME: Need to share with j2d context, due to FBO resource .. 
-                    // - ORIG: joglContext = joglDrawable.createContext(shareWith);
                     joglContext = joglDrawable.createContext(j2dContext);
-                    if (DEBUG||VERBOSE) {
+                    joglContext.setSynchronized(true);
+                    if (DEBUG) {
                         System.err.println("-- Created External Drawable: "+joglDrawable);
                         System.err.println("-- Created Context: "+joglContext);
                     }
                   } else if (factory.canCreateContextOnJava2DSurface(device)) {
                     // Mac OS X code path
-                    // FIXME: Need to share with j2d context, due to FBO resource .. 
-                    // - ORIG: joglContext = factory.createContextOnJava2DSurface(g, shareWith);
                     joglContext = factory.createContextOnJava2DSurface(g, j2dContext);
-                    if (DEBUG||VERBOSE) {
+                    joglContext.setSynchronized(true);
+                    if (DEBUG) {
                         System.err.println("-- Created Context: "+joglContext);
                     }
                   }
@@ -1668,7 +1628,7 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                   ((Java2DGLContext) joglContext).setGraphics(g);
                 }
 
-                drawableHelper.invokeGL(joglDrawable, joglContext, displayAction, initAction);
+                drawableHelper.invokeGL(joglDrawable, joglContext, updaterDisplayAction, updaterInitAction);
               }
             } finally {
               j2dContext.release();
@@ -1687,12 +1647,12 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
           checkedForFBObjectWorkarounds=true;
           fbObjectWorkarounds = true;
           createNewDepthBuffer = true;
-          if (DEBUG || VERBOSE) {
-              System.err.println("GLJPanel: Fetched ERR GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]+" - NOT A FBO"+
+          if (DEBUG) {
+              System.err.println(getThreadName()+": GLJPanel: Fetched ERR GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]+" - NOT A FBO"+
                                  ", frame_buffer_object workarounds to be necessary");
           }
         } else if (DEBUG) {
-          System.err.println("GLJPanel: Fetched OK GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]);
+          System.err.println(getThreadName()+": GLJPanel: Fetched OK GL_FRAMEBUFFER_BINDING: "+frameBuffer[0]);
         }
 
         if(fbObjectWorkarounds || !checkedForFBObjectWorkarounds) {
@@ -1706,8 +1666,8 @@ public class GLJPanel extends JPanel implements AWTGLAutoDrawable, WindowClosing
                                                      GL.GL_COLOR_ATTACHMENT0,
                                                      GL.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                                      frameBufferTexture, 0);
-            if (DEBUG && VERBOSE) {
-                System.err.println("GLJPanel: FBO COLOR_ATTACHMENT0: " + frameBufferTexture[0]);
+            if (DEBUG) {
+                System.err.println(getThreadName()+": GLJPanel: FBO COLOR_ATTACHMENT0: " + frameBufferTexture[0]);
             }
         }
 
diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java
index 0217a63..117faaf 100755
--- a/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java
+++ b/src/jogl/classes/jogamp/graph/curve/opengl/RegionRendererImpl01.java
@@ -56,17 +56,17 @@ public class RegionRendererImpl01 extends RegionRenderer {
     protected boolean initShaderProgram(GL2ES2 gl) {
         final ShaderState st = rs.getShaderState();
         
-        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RegionRendererImpl01.class,
-                "shader", "shader/bin", getVertexShaderName(gl));
-        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RegionRendererImpl01.class,
-                "shader", "shader/bin", getFragmentShaderName(gl));
+        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RegionRendererImpl01.class, "shader",
+                "shader/bin", getVertexShaderName(gl), false);
+        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RegionRendererImpl01.class, "shader",
+                "shader/bin", getFragmentShaderName(gl), false);
     
         ShaderProgram sp = new ShaderProgram();
         sp.add(rsVp);
         sp.add(rsFp);
 
         sp.init(gl);
-        st.attachShaderProgram(gl, sp);        
+        st.attachShaderProgram(gl, sp, false);        
         st.bindAttribLocation(gl, AttributeNames.VERTEX_ATTR_IDX, AttributeNames.VERTEX_ATTR_NAME);
         st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME);        
         
@@ -87,7 +87,7 @@ public class RegionRendererImpl01 extends RegionRenderer {
     }
 
     @Override
-    protected void drawImpl(GL2ES2 gl, Region region, float[] position, int texSize) {
+    protected void drawImpl(GL2ES2 gl, Region region, float[] position, int[] texSize) {
         ((GLRegion)region).draw(gl, rs, vp_width, vp_height, texSize);
     }    
 }
diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java b/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java
index 5ed3529..158f024 100644
--- a/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java
+++ b/src/jogl/classes/jogamp/graph/curve/opengl/TextRendererImpl01.java
@@ -49,17 +49,17 @@ public class TextRendererImpl01 extends TextRenderer {
     protected boolean initShaderProgram(GL2ES2 gl){
         final ShaderState st = rs.getShaderState();
 
-        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, TextRendererImpl01.class,
-                "shader", "shader/bin", getVertexShaderName(gl));
-        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, TextRendererImpl01.class,
-                "shader", "shader/bin", getFragmentShaderName(gl));
+        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, TextRendererImpl01.class, "shader",
+                "shader/bin", getVertexShaderName(gl), false);
+        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, TextRendererImpl01.class, "shader",
+                "shader/bin", getFragmentShaderName(gl), false);
         
         ShaderProgram sp = new ShaderProgram();
         sp.add(rsVp);
         sp.add(rsFp);
         
         sp.init(gl);
-        st.attachShaderProgram(gl, sp);        
+        st.attachShaderProgram(gl, sp, false);        
         st.bindAttribLocation(gl, AttributeNames.VERTEX_ATTR_IDX, AttributeNames.VERTEX_ATTR_NAME);
         st.bindAttribLocation(gl, AttributeNames.TEXCOORD_ATTR_IDX, AttributeNames.TEXCOORD_ATTR_NAME);        
         
@@ -80,7 +80,7 @@ public class TextRendererImpl01 extends TextRenderer {
     }
     
     @Override
-    public void drawString3D(GL2ES2 gl, Font font, String str, float[] position, int fontSize, int texSize) {
+    public void drawString3D(GL2ES2 gl, Font font, String str, float[] position, int fontSize, int[/*1*/] texSize) {
         if(!isInitialized()){
             throw new GLException("TextRendererImpl01: not initialized!");
         }
@@ -92,5 +92,4 @@ public class TextRendererImpl01 extends TextRenderer {
         
         glyphString.renderString3D(gl, rs, vp_width, vp_height, texSize);
     }
-    
 }
diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java
index 758d0e9..804e9ee 100644
--- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java
+++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegion2PES2.java
@@ -81,16 +81,16 @@ public class VBORegion2PES2  extends GLRegion {
         }
 
         if(null == indicesFbo) {
-            final int initialSize = 256;
+            final int initialElementCount = 256;
             final ShaderState st = rs.getShaderState();
             
-            indicesFbo = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialSize, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);                
+            indicesFbo = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);                
             indicesFbo.puts((short) 0); indicesFbo.puts((short) 1); indicesFbo.puts((short) 3);
             indicesFbo.puts((short) 1); indicesFbo.puts((short) 2); indicesFbo.puts((short) 3);
             indicesFbo.seal(true);
             
             texCoordFboAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, 
-                                                           false, initialSize, GL.GL_STATIC_DRAW);
+                                                           false, initialElementCount, GL.GL_STATIC_DRAW);
             st.ownAttribute(texCoordFboAttr, true);
             texCoordFboAttr.putf(5); texCoordFboAttr.putf(5);        
             texCoordFboAttr.putf(5); texCoordFboAttr.putf(6);        
@@ -99,18 +99,18 @@ public class VBORegion2PES2  extends GLRegion {
             texCoordFboAttr.seal(true);
             
             verticeFboAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, 
-                                                          false, initialSize, GL.GL_STATIC_DRAW); 
+                                                          false, initialElementCount, GL.GL_STATIC_DRAW); 
             st.ownAttribute(verticeFboAttr, true);
             
             
-            indicesTxt = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialSize, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);                
+            indicesTxt = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);                
             
             verticeTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, 
-                                                          false, initialSize, GL.GL_STATIC_DRAW);
+                                                          false, initialElementCount, GL.GL_STATIC_DRAW);
             st.ownAttribute(verticeTxtAttr, true);
             
             texCoordTxtAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, 
-                                                           false, initialSize, GL.GL_STATIC_DRAW);
+                                                           false, initialElementCount, GL.GL_STATIC_DRAW);
             st.ownAttribute(texCoordTxtAttr, true);
             
             if(DEBUG_INSTANCE) {
@@ -190,12 +190,20 @@ public class VBORegion2PES2  extends GLRegion {
         // the buffers were disabled, since due to real/fbo switching and other vbo usage
     }
     
-    protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int width) {
-        if(vp_width <=0 || vp_height <= 0 || width <= 0){
+    int[] maxTexSize = new int[] { -1 } ;
+    
+    protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) {
+        if(vp_width <=0 || vp_height <= 0 || null==texWidth || texWidth[0] <= 0){
             renderRegion(gl);
         } else {
-            if(width != tex_width_c) {
-                renderRegion2FBO(gl, rs, width);                
+            if(0 > maxTexSize[0]) {
+                gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, maxTexSize, 0);
+            }
+            if(texWidth[0] != tex_width_c) {
+                if(texWidth[0] > maxTexSize[0]) {
+                    texWidth[0] = maxTexSize[0]; // clip to max - write-back user value!
+                }
+                renderRegion2FBO(gl, rs, texWidth); 
             }
             // System.out.println("Scale: " + matrix.glGetMatrixf().get(1+4*3) +" " + matrix.glGetMatrixf().get(2+4*3));
             renderFBO(gl, rs, vp_width, vp_height);
@@ -222,15 +230,19 @@ public class VBORegion2PES2  extends GLRegion {
         // setback: gl.glActiveTexture(currentActiveTextureEngine[0]);
     }
     
-    private void renderRegion2FBO(GL2ES2 gl, RenderState rs, int tex_width) {
+    private void renderRegion2FBO(GL2ES2 gl, RenderState rs, int[/*1*/] texWidth) {
         final ShaderState st = rs.getShaderState();
         
-        tex_width_c = tex_width;        
+        if(0>=texWidth[0]) {
+            throw new IllegalArgumentException("texWidth must be greater than 0: "+texWidth[0]);
+        }
+        
+        tex_width_c  = texWidth[0];
         tex_height_c = (int) ( ( ( tex_width_c * box.getHeight() ) / box.getWidth() ) + 0.5f );
         
-        // System.out.println("FBO Size: "+tex_width+" -> "+tex_height_c+"x"+tex_width_c);
+        // System.out.println("FBO Size: "+texWidth[0]+" -> "+tex_width_c+"x"+tex_height_c);
         // System.out.println("FBO Scale: " + m.glGetMatrixf().get(0) +" " + m.glGetMatrixf().get(5));
-
+        
         if(null != fbo && fbo.getWidth() != tex_width_c && fbo.getHeight() != tex_height_c ) {
             fbo.destroy(gl);
             fbo = null;
diff --git a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java
index 2167138..14ff038 100644
--- a/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java
+++ b/src/jogl/classes/jogamp/graph/curve/opengl/VBORegionSPES2.java
@@ -54,17 +54,17 @@ public class VBORegionSPES2 extends GLRegion {
         }
 
         if(null == indices) {
-            final int initialSize = 256;
+            final int initialElementCount = 256;
             final ShaderState st = rs.getShaderState();
 
-            indices = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialSize, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);
+            indices = GLArrayDataServer.createData(3, GL2ES2.GL_SHORT, initialElementCount, GL.GL_STATIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER);
 
             verticeAttr = GLArrayDataServer.createGLSL(AttributeNames.VERTEX_ATTR_NAME, 3, GL2ES2.GL_FLOAT, 
-                    false, initialSize, GL.GL_STATIC_DRAW);         
+                    false, initialElementCount, GL.GL_STATIC_DRAW);         
             st.ownAttribute(verticeAttr, true);
 
             texCoordAttr = GLArrayDataServer.createGLSL(AttributeNames.TEXCOORD_ATTR_NAME, 2, GL2ES2.GL_FLOAT, 
-                    false, initialSize, GL.GL_STATIC_DRAW);
+                    false, initialElementCount, GL.GL_STATIC_DRAW);
             st.ownAttribute(texCoordAttr, true);
 
             if(DEBUG_INSTANCE) {
@@ -125,7 +125,7 @@ public class VBORegionSPES2 extends GLRegion {
         setDirty(false);
     }
 
-    protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int width) {
+    protected void drawImpl(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) {
         verticeAttr.enableBuffer(gl, true);       
         texCoordAttr.enableBuffer(gl, true);
         indices.enableBuffer(gl, true);
diff --git a/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java b/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java
index bc9a930..f86d02f 100644
--- a/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java
+++ b/src/jogl/classes/jogamp/graph/curve/text/GlyphString.java
@@ -45,6 +45,7 @@ import com.jogamp.graph.curve.OutlineShape;
 import com.jogamp.graph.curve.Region;
 import com.jogamp.graph.curve.opengl.GLRegion;
 import com.jogamp.graph.curve.opengl.RenderState;
+import com.jogamp.opengl.util.PMVMatrix;
 
 public class GlyphString {
     /** Static font size for all default font OutlineShape generations via {@link #createString(OutlineShape, Factory, Font, String)}.
@@ -171,13 +172,19 @@ public class GlyphString {
      *  previously generated.
      */
     public void renderString3D(GL2ES2 gl) {
-        region.draw(gl, null, 0, 0, 0);
+        region.draw(gl, null, 0, 0, null);
     }
     /** Render the Object based using the associated Region
      *  previously generated.
+     * @param matrix current {@link PMVMatrix}.
+     * @param rs the RenderState to be used
+     * @param vp_width current screen width
+     * @param vp_height current screen height
+     * @param texWidth desired texture width for multipass-rendering. 
+     *        The actual used texture-width is written back when mp rendering is enabled, otherwise the store is untouched.
      */
-    public void renderString3D(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int size) {
-        region.draw(gl, rs, vp_width, vp_height, size);
+    public void renderString3D(GL2ES2 gl, RenderState rs, int vp_width, int vp_height, int[/*1*/] texWidth) {
+        region.draw(gl, rs, vp_width, vp_height, texWidth);
     }
     
     /** Get the Origin of this GlyphString
diff --git a/src/jogl/classes/jogamp/graph/font/FontConstructor.java b/src/jogl/classes/jogamp/graph/font/FontConstructor.java
index 721b207..b452ae5 100644
--- a/src/jogl/classes/jogamp/graph/font/FontConstructor.java
+++ b/src/jogl/classes/jogamp/graph/font/FontConstructor.java
@@ -29,11 +29,11 @@ package jogamp.graph.font;
 
 import java.io.File;
 import java.io.IOException;
-import java.net.URL;
+import java.net.URLConnection;
 
 import com.jogamp.graph.font.Font;
 
 public interface FontConstructor {
     Font create(File file) throws IOException ;
-    Font create(URL url) throws IOException ;
+    Font create(URLConnection url) throws IOException ;
 }
diff --git a/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java b/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java
index 6b82606..a00e957 100644
--- a/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java
+++ b/src/jogl/classes/jogamp/graph/font/JavaFontLoader.java
@@ -81,11 +81,11 @@ public class JavaFontLoader implements FontSet {
         return 0 != ( bits & bit ) ;
     }
     
-    public Font getDefault() {
+    public Font getDefault() throws IOException {
         return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular 
     }
     
-    public Font get(int family, int style)    {
+    public Font get(int family, int style) throws IOException {
         Font font = (Font)fontMap.get( ( family << 8 ) | style );
         if (font != null) {
             return font;
@@ -135,7 +135,7 @@ public class JavaFontLoader implements FontSet {
         return font;
     }
     
-    Font abspath(String fname, int family, int style) {
+    Font abspath(String fname, int family, int style) throws IOException {
         if(null == javaFontPath) {
             throw new GLException("java font path undefined");
         }
@@ -147,9 +147,9 @@ public class JavaFontLoader implements FontSet {
                 fontMap.put( ( family << 8 ) | style, f );
                 return f;
             }
-            throw new GLException(err);            
+            throw new IOException (err);            
         } catch (IOException ioe) {
-            throw new GLException(err, ioe);            
+            throw new IOException(err, ioe);            
         }
     }    
 }
diff --git a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java
index 572955f..0772cc4 100644
--- a/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java
+++ b/src/jogl/classes/jogamp/graph/font/UbuntuFontLoader.java
@@ -36,7 +36,7 @@ import com.jogamp.common.util.IOUtil;
 import com.jogamp.graph.font.Font;
 import com.jogamp.graph.font.FontSet;
 import com.jogamp.graph.font.FontFactory;
-import java.net.URL;
+import java.net.URLConnection;
 
 public class UbuntuFontLoader implements FontSet {
     
@@ -71,12 +71,11 @@ public class UbuntuFontLoader implements FontSet {
         return 0 != ( bits & bit ) ;
     }
     
-    public Font getDefault() {
+    public Font getDefault() throws IOException {
         return get(FAMILY_REGULAR, 0) ; // Sans Serif Regular 
     }
     
-    public Font get(int family, int style)
-    {
+    public Font get(int family, int style) throws IOException {
         Font font = (Font)fontMap.get( ( family << 8 ) | style );
         if (font != null) {
             return font;
@@ -119,21 +118,21 @@ public class UbuntuFontLoader implements FontSet {
         return font;
     }
         
-    Font abspath(String fname, int family, int style) {
+    Font abspath(String fname, int family, int style) throws IOException {
         final String err = "Problem loading font "+fname+", stream "+relPath+fname;
         try {
-            URL url = IOUtil.getResource(UbuntuFontLoader.class, relPath+fname);
-            if(null == url) {
+            URLConnection conn = IOUtil.getResource(UbuntuFontLoader.class, relPath+fname);
+            if(null == conn) {
                 throw new GLException(err);
             }
-            final Font f= FontFactory.get ( url ) ;
+            final Font f= FontFactory.get ( conn ) ;
             if(null != f) {
                 fontMap.put( ( family << 8 ) | style, f );
                 return f;
             }        
-            throw new GLException(err);
+            throw new IOException(err);
         } catch(IOException ioe) {
-            throw new GLException(err, ioe);            
+            throw new IOException(err, ioe);            
         }
     }           
 }
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java
index a9e5524..e8b62bd 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/TypecastFontConstructor.java
@@ -29,7 +29,7 @@ package jogamp.graph.font.typecast;
 
 import java.io.File;
 import java.io.IOException;
-import java.net.URL;
+import java.net.URLConnection;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
@@ -44,32 +44,38 @@ import com.jogamp.graph.font.Font;
 public class TypecastFontConstructor implements FontConstructor  {
 
     public Font create(final File ffile) throws IOException {
-        return AccessController.doPrivileged(new PrivilegedAction<Font>() {
-            public Font run() {
+        Object o = AccessController.doPrivileged(new PrivilegedAction<Object>() {
+            public Object run() {
                 OTFontCollection fontset;        
                 try {
                     fontset = OTFontCollection.create(ffile);
                     return new TypecastFont(fontset);
                 } catch (IOException e) {
-                    e.printStackTrace();
+                    return e;
                 }
-                return null;
             }
-        });        
+        });
+        if(o instanceof Font) {
+            return (Font)o;
+        }
+        if(o instanceof IOException) {
+            throw (IOException)o;
+        }
+        throw new InternalError("Unexpected Object: "+o);
     }
     
-    public Font create(final URL furl) throws IOException {
+    public Font create(final URLConnection fconn) throws IOException {
         return AccessController.doPrivileged(new PrivilegedAction<Font>() {
             public Font run() {
                 File tf = null;
                 int len=0;
                 Font f = null;
                 try {         
-                    tf = IOUtil.createTempFile( "joglfont", ".ttf");
-                    len = IOUtil.copyURL2File(furl, tf);
+                    tf = IOUtil.createTempFile( "joglfont", ".ttf", null);
+                    len = IOUtil.copyURLConn2File(fconn, tf);
                     if(len==0) {
                         tf.delete();
-                        throw new GLException("Font of stream "+furl+" was zero bytes");
+                        throw new GLException("Font of stream "+fconn.getURL()+" was zero bytes");
                     }
                     f = create(tf);
                     tf.delete();
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java
index 0ac5f0b..b553575 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/Disassembler.java
@@ -82,7 +82,7 @@ public class Disassembler {
     }
 
      public static String disassemble(short[] instructions, int leadingSpaces) {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         int ip = 0;
         while (ip < instructions.length) {
             for (int i = 0; i < leadingSpaces; i++) {
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java
index 53a8890..4a04160 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/OTFontCollection.java
@@ -107,7 +107,7 @@ public class OTFontCollection {
         _fileName = file.getName();
 
         if (!file.exists()) {
-            throw new IOException();
+            throw new IOException("File <"+file.getName()+"> doesn't exist.");
         }
 
         // Do we need to modify the path name to deal with font resources
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java
index 969aa96..1c7e24c 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/mac/ResourceType.java
@@ -60,7 +60,7 @@ public class ResourceType {
     }
     
     public String getTypeAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((type>>24)&0xff))
             .append((char)((type>>16)&0xff))
             .append((char)((type>>8)&0xff))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java
index 659b0cd..ed615eb 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/BaseTable.java
@@ -212,7 +212,7 @@ public class BaseTable implements Table {
         }
 
         public String toString() {
-            StringBuffer sb = new StringBuffer()
+            StringBuilder sb = new StringBuilder()
                 .append("\nBaseScript BaseScriptT").append(Integer.toHexString(_thisOffset))
                 .append("\nBaseValuesT").append(Integer.toHexString(_thisOffset + _baseValuesOffset))
                 .append("\nMinMaxT").append(Integer.toHexString(_thisOffset + _defaultMinMaxOffset))
@@ -274,7 +274,7 @@ public class BaseTable implements Table {
         }
 
         public String toString() {
-            StringBuffer sb = new StringBuffer()
+            StringBuilder sb = new StringBuilder()
                 .append("\nBaseScriptList BaseScriptListT").append(Integer.toHexString(_thisOffset))
                 .append("\n").append(Integer.toHexString(_baseScriptCount));
             for (int i = 0; i < _baseScriptCount; ++i) {
@@ -306,7 +306,7 @@ public class BaseTable implements Table {
         }
 
         public String toString() {
-            StringBuffer sb = new StringBuffer()
+            StringBuilder sb = new StringBuilder()
                 .append("\nBaseTagList BaseTagListT").append(Integer.toHexString(_thisOffset))
                 .append("\n").append(Integer.toHexString(_baseTagCount));
             for (int i = 0; i < _baseTagCount; ++i) {
@@ -339,7 +339,7 @@ public class BaseTable implements Table {
         }
 
         public String toString() {
-            return new StringBuffer()
+            return new StringBuilder()
                 .append("\nAxis AxisT").append(Integer.toHexString(_thisOffset))
                 .append("\nBaseTagListT").append(Integer.toHexString(_thisOffset + _baseTagListOffset))
                 .append("\nBaseScriptListT").append(Integer.toHexString(_thisOffset + _baseScriptListOffset))
@@ -408,7 +408,7 @@ public class BaseTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer()
+        StringBuilder sb = new StringBuilder()
             .append("; 'BASE' Table - Baseline\n;-------------------------------------\n\n")
             .append("BASEHeader BASEHeaderT").append(Integer.toHexString(0))
             .append("\n").append(Integer.toHexString(_version))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java
index 0c54c27..966f6e1 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CffTable.java
@@ -132,7 +132,7 @@ public class CffTable implements Table {
             } else if (b0 == 30) {
                 
                 // Real number
-                StringBuffer fString = new StringBuffer();
+                StringBuilder fString = new StringBuilder();
                 int nibble1 = 0;
                 int nibble2 = 0;
                 ++_index;
@@ -165,7 +165,7 @@ public class CffTable implements Table {
         }
         
         public String toString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             Enumeration<Integer> keys = _entries.keys();
             while (keys.hasMoreElements()) {
                 Integer key = keys.nextElement();
@@ -221,7 +221,7 @@ public class CffTable implements Table {
         }
 
         public String toString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             sb.append("DICT\n");
             sb.append("count: ").append(_count).append("\n");
             sb.append("offSize: ").append(_offSize).append("\n");
@@ -255,7 +255,7 @@ public class CffTable implements Table {
         }
 
         public String toString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             for (int i = 0; i < getCount(); ++i) {
                 sb.append(getTopDict(i).toString()).append("\n");
             }
@@ -276,7 +276,7 @@ public class CffTable implements Table {
 
             // Ensure the name hasn't been deleted
             if (getData()[offset] != 0) {
-                StringBuffer sb = new StringBuffer();
+                StringBuilder sb = new StringBuilder();
                 for (int i = offset; i < offset + len; ++i) {
                     sb.append((char) getData()[i]);
                 }
@@ -288,7 +288,7 @@ public class CffTable implements Table {
         }
         
         public String toString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             for (int i = 0; i < getCount(); ++i) {
                 sb.append(getName(i)).append("\n");
             }
@@ -313,7 +313,7 @@ public class CffTable implements Table {
                 int offset = getOffset(index) - 1;
                 int len = getOffset(index + 1) - offset - 1;
 
-                StringBuffer sb = new StringBuffer();
+                StringBuilder sb = new StringBuilder();
                 for (int i = offset; i < offset + len; ++i) {
                     sb.append((char) getData()[i]);
                 }
@@ -323,7 +323,7 @@ public class CffTable implements Table {
         
         public String toString() {
             int nonStandardBase = CffStandardStrings.standardStrings.length;
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
             for (int i = 0; i < getCount(); ++i) {
                 sb.append(nonStandardBase + i).append(": ");
                 sb.append(getString(nonStandardBase + i)).append("\n");
@@ -591,7 +591,7 @@ public class CffTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'CFF' Table - Compact Font Format\n---------------------------------\n");
         sb.append("\nName INDEX\n");
         sb.append(_nameIndex.toString());
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java
index bed0ba4..9c40a0e 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CharstringType2.java
@@ -141,7 +141,7 @@ public class CharstringType2 extends Charstring {
         return _name;
     }
     
-    private void disassemble(StringBuffer sb) {
+    private void disassemble(StringBuilder sb) {
         Number operand = null;
         while (isOperandAtIndex()) {
             operand = nextOperand();
@@ -224,7 +224,7 @@ public class CharstringType2 extends Charstring {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         resetIP();
         while (moreBytes()) {
             disassemble(sb);
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java
index 45e21df..7ce531c 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat.java
@@ -123,7 +123,7 @@ public abstract class CmapFormat {
     public abstract int mapCharCode(int charCode);
     
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
         .append("format: ")
         .append(_format)
         .append(", length: ")
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java
index d2baf2b..c09bdc8 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapFormat4.java
@@ -143,7 +143,7 @@ public class CmapFormat4 extends CmapFormat {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append(super.toString())
             .append(", segCountX2: ")
             .append(_segCountX2)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java
index df18a7f..85fdf72 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapIndexEntry.java
@@ -91,7 +91,7 @@ public class CmapIndexEntry implements Comparable {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("platform id: ")
             .append(_platformId)
             .append(" (")
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java
index b93de50..0050fdd 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CmapTable.java
@@ -135,7 +135,7 @@ public class CmapTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer().append("cmap\n");
+        StringBuilder sb = new StringBuilder().append("cmap\n");
 
         // Get each of the index entries
         for (int i = 0; i < _numTables; i++) {
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java
index 189d080..9631635 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/CvtTable.java
@@ -38,7 +38,7 @@ public class CvtTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'cvt ' Table - Control Value Table\n----------------------------------\n");
         sb.append("Size = ").append(0).append(" bytes, ").append(values.length).append(" entries\n");
         sb.append("        Values\n        ------\n");
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java
index d2f93de..c98f03f 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DirectoryEntry.java
@@ -96,7 +96,7 @@ public class DirectoryEntry implements Cloneable {
     }
 
     public String getTagAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((_tag>>24)&0xff))
             .append((char)((_tag>>16)&0xff))
             .append((char)((_tag>>8)&0xff))
@@ -105,7 +105,7 @@ public class DirectoryEntry implements Cloneable {
     }
     
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'").append(getTagAsString())
             .append("' - chksm = 0x").append(Integer.toHexString(_checksum))
             .append(", off = 0x").append(Integer.toHexString(_offset))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java
index 34f321e..e2784f9 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/DsigTable.java
@@ -60,7 +60,7 @@ public class DsigTable implements Table {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer().append("DSIG\n");
+        StringBuilder sb = new StringBuilder().append("DSIG\n");
         for (int i = 0; i < numSigs; i++) {
             sb.append(sigBlocks[i].toString());
         }
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java
index 49a8ef9..eb61081 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/FeatureRecord.java
@@ -78,7 +78,7 @@ public class FeatureRecord {
     }
 
     public String getTagAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((_tag>>24)&0xff))
             .append((char)((_tag>>16)&0xff))
             .append((char)((_tag>>8)&0xff))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java
index fe7e9f6..2748406 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspRange.java
@@ -31,7 +31,7 @@ public class GaspRange {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("  rangeMaxPPEM:        ").append(rangeMaxPPEM)
             .append("\n  rangeGaspBehavior:   0x").append(rangeGaspBehavior);
         if ((rangeGaspBehavior & GASP_GRIDFIT) != 0) {
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java
index 611ee16..a83db5b 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GaspTable.java
@@ -39,7 +39,7 @@ public class GaspTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'gasp' Table - Grid-fitting And Scan-conversion Procedure\n---------------------------------------------------------");
         sb.append("\n  'gasp' version:      ").append(version);
         sb.append("\n  numRanges:           ").append(numRanges);
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java
index 3fc113f..a9342a4 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfDescript.java
@@ -113,7 +113,7 @@ public abstract class GlyfDescript extends Program implements GlyphDescription {
     }
     
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("          numberOfContours: ").append(_numberOfContours)
             .append("\n          xMin:             ").append(_xMin)
             .append("\n          yMin:             ").append(_yMin)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java
index c5c7671..c11d2d8 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/GlyfSimpleDescript.java
@@ -186,7 +186,7 @@ public class GlyfSimpleDescript extends GlyfDescript {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append(super.toString());
         sb.append("\n\n        EndPoints\n        ---------");
         for (int i = 0; i < _endPtsOfContours.length; i++) {
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java
index 64ac9d6..5b1fa20 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HdmxTable.java
@@ -98,7 +98,7 @@ public class HdmxTable implements Table {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'hdmx' Table - Horizontal Device Metrics\n----------------------------------------\n");
         sb.append("Size = ").append(_de.getLength()).append(" bytes\n")
             .append("\t'hdmx' version:         ").append(_version).append("\n")
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java
index 122a50f..9d7fe42 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HeadTable.java
@@ -171,7 +171,7 @@ public class HeadTable implements Table {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'head' Table - Font Header\n--------------------------")
             .append("\n  'head' version:      ").append(Fixed.floatValue(_versionNumber))
             .append("\n  fontRevision:        ").append(Fixed.roundedFloatValue(_fontRevision, 8))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java
index 6cafab4..20a21e4 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HheaTable.java
@@ -101,7 +101,7 @@ public class HheaTable implements Table {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'hhea' Table - Horizontal Header\n--------------------------------")
             .append("\n        'hhea' version:       ").append(Fixed.floatValue(version))
             .append("\n        yAscender:            ").append(ascender)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java
index c2e892e..dacd9e2 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/HmtxTable.java
@@ -111,7 +111,7 @@ public class HmtxTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'hmtx' Table - Horizontal Metrics\n---------------------------------\n");
         sb.append("Size = ").append(_de.getLength()).append(" bytes, ")
             .append(_hMetrics.length).append(" entries\n");
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java
index 5777bd6..9511f66 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LangSysRecord.java
@@ -78,7 +78,7 @@ public class LangSysRecord {
     }
 
     public String getTagAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((_tag>>24)&0xff))
             .append((char)((_tag>>16)&0xff))
             .append((char)((_tag>>8)&0xff))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java
index 8187708..5eb7c58 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LocaTable.java
@@ -54,7 +54,7 @@ public class LocaTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'loca' Table - Index To Location Table\n--------------------------------------\n")
             .append("Size = ").append(_de.getLength()).append(" bytes, ")
             .append(_offsets.length).append(" entries\n");
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java
index 2cba7ba..ace3d38 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/LtshTable.java
@@ -43,7 +43,7 @@ public class LtshTable implements Table {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'LTSH' Table - Linear Threshold Table\n-------------------------------------")
             .append("\n 'LTSH' Version:       ").append(version)
             .append("\n Number of Glyphs:     ").append(numGlyphs)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java
index 16b9f82..0e8ec44 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/MaxpTable.java
@@ -126,7 +126,7 @@ public class MaxpTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'maxp' Table - Maximum Profile\n------------------------------")
             .append("\n        'maxp' version:         ").append(Fixed.floatValue(versionNumber))
             .append("\n        numGlyphs:              ").append(numGlyphs);
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java
index cd13e9b..268d6cf 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/NameRecord.java
@@ -98,7 +98,7 @@ public class NameRecord {
     }
 
     protected void loadString(DataInput di) throws IOException {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         di.skipBytes(_stringOffset);
         if (_platformId == ID.platformUnicode) {
             
@@ -131,7 +131,7 @@ public class NameRecord {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         
         sb.append("             Platform ID:       ").append(_platformId)
             .append("\n             Specific ID:       ").append(_encodingId)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java
index f33dd27..f4fa76e 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Os2Table.java
@@ -298,7 +298,7 @@ public class Os2Table implements Table {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'OS/2' Table - OS/2 and Windows Metrics\n---------------------------------------")
             .append("\n  'OS/2' version:      ").append(_version)
             .append("\n  xAvgCharWidth:       ").append(_xAvgCharWidth)
@@ -337,7 +337,7 @@ public class Os2Table implements Table {
     }
     
     private String getVendorIDAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((_achVendorID>>24)&0xff))
             .append((char)((_achVendorID>>16)&0xff))
             .append((char)((_achVendorID>>8)&0xff))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java
index 84e6707..6127140 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/Panose.java
@@ -80,7 +80,7 @@ public class Panose {
   }
   
   public String toString() {
-    StringBuffer sb = new StringBuffer();
+    StringBuilder sb = new StringBuilder();
     sb.append(String.valueOf(bFamilyType)).append(" ")
       .append(String.valueOf(bSerifStyle)).append(" ")
       .append(String.valueOf(bWeight)).append(" ")
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java
index 792b8a8..f9dcf2c 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PcltTable.java
@@ -70,7 +70,7 @@ public class PcltTable implements Table {
     }
     
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'PCLT' Table - Printer Command Language Table\n---------------------------------------------")
             .append("\n        version:             0x").append(Integer.toHexString(version).toUpperCase())
             .append("\n        fontNumber:          ").append(fontNumber).append(" (0x").append(Long.toHexString(fontNumber).toUpperCase())
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java
index 4804c35..c913b4c 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/PostTable.java
@@ -375,7 +375,7 @@ public class PostTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'post' Table - PostScript Metrics\n---------------------------------\n")
             .append("\n        'post' version:        ").append(Fixed.floatValue(version))
             .append("\n        italicAngle:           ").append(Fixed.floatValue(italicAngle))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java
index 34a43d2..5da0608 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/ScriptRecord.java
@@ -78,7 +78,7 @@ public class ScriptRecord {
     }
 
     public String getTagAsString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append((char)((_tag>>24)&0xff))
             .append((char)((_tag>>16)&0xff))
             .append((char)((_tag>>8)&0xff))
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java
index 156d3fd..5a5de11 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/SignatureBlock.java
@@ -33,7 +33,7 @@ public class SignatureBlock {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         for (int i = 0; i < signatureLen; i += 16) {
             if (signatureLen - i >= 16) {
                 sb.append(new String(signature, i, 16)).append("\n");
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java
index cf9f1bd..bacc26d 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/TableDirectory.java
@@ -114,7 +114,7 @@ public class TableDirectory {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer()
+        StringBuilder sb = new StringBuilder()
             .append("Offset Table\n------ -----")
             .append("\n  sfnt version:     ").append(Fixed.floatValue(_version))
             .append("\n  numTables =       ").append(_numTables)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java
index 641f3ef..80579f5 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VdmxTable.java
@@ -153,7 +153,7 @@ public class VdmxTable implements Table {
     }
     
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'VDMX' Table - Precomputed Vertical Device Metrics\n")
             .append("--------------------------------------------------\n")
             .append("  Version:                 ").append(_version).append("\n")
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java
index 0fc8bea..19c9176 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VheaTable.java
@@ -114,7 +114,7 @@ public class VheaTable implements Table {
     }
 
     public String toString() {
-        return new StringBuffer()
+        return new StringBuilder()
             .append("'vhea' Table - Vertical Header\n------------------------------")
             .append("\n        'vhea' version:       ").append(Fixed.floatValue(_version))
             .append("\n        xAscender:            ").append(_ascent)
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java
index dcd1cd7..3484053 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/ot/table/VmtxTable.java
@@ -82,7 +82,7 @@ public class VmtxTable implements Table {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("'vmtx' Table - Vertical Metrics\n-------------------------------\n");
         sb.append("Size = ").append(_de.getLength()).append(" bytes, ")
             .append(_vMetrics.length).append(" entries\n");
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java b/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java
index a05bd3b..887f8c3 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/t2/T2Interpreter.java
@@ -478,7 +478,7 @@ public class T2Interpreter {
     }
     
     /**
-     * Causes two B�zier curves, as described by the arguments (as
+     * Causes two Bezier curves, as described by the arguments (as
      * shown in Figure 2 below), to be rendered as a straight line when
      * the flex depth is less than fd /100 device pixels, and as curved lines
      * when the flex depth is greater than or equal to fd/100 device
@@ -524,7 +524,7 @@ public class T2Interpreter {
     
     /**
      * Finishes a charstring outline definition, and must be the
-     * last operator in a character�s outline.
+     * last operator in a character's outline.
      */
     private void _endchar() {
         endContour();
@@ -668,7 +668,7 @@ public class T2Interpreter {
     }
     
     /**
-     * Performs a circular shift of the elements num(N�1) ... num0 on
+     * Performs a circular shift of the elements num(Nx1) ... num0 on
      * the argument stack by the amount J. Positive J indicates upward
      * motion of the stack; negative J indicates downward motion.
      * The value N must be a non-negative integer, otherwise the
diff --git a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java
index 71260b8..c5a2b6e 100644
--- a/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java
+++ b/src/jogl/classes/jogamp/graph/font/typecast/tt/engine/Parser.java
@@ -149,7 +149,7 @@ public class Parser {
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         int ip = 0;
         while (ip < instructions[0].length) {
             sb.append(Mnemonic.getMnemonic(getOpcode(ip)));
diff --git a/src/jogl/classes/jogamp/opengl/Debug.java b/src/jogl/classes/jogamp/opengl/Debug.java
index 83c79c1..4287c19 100644
--- a/src/jogl/classes/jogamp/opengl/Debug.java
+++ b/src/jogl/classes/jogamp/opengl/Debug.java
@@ -39,18 +39,17 @@
 
 package jogamp.opengl;
 
-import java.security.*;
+import com.jogamp.common.util.PropertyAccess;
 
 /** Helper routines for logging and debugging. */
 
-public class Debug {
+public class Debug extends PropertyAccess {
   // Some common properties
-  private static boolean verbose;
-  private static boolean debugAll;
-  private static AccessControlContext localACC;
+  private static final boolean verbose;
+  private static final boolean debugAll;
   
   static {
-    localACC=AccessController.getContext();
+    PropertyAccess.addTrustedPrefix("jogl.", Debug.class);
     verbose = isPropertyDefined("jogl.verbose", true);
     debugAll = isPropertyDefined("jogl.debug", true);
     if (verbose) {
@@ -61,71 +60,18 @@ public class Debug {
     }
   }
 
-  static int getIntProperty(final String property, final boolean jnlpAlias) {
-      return getIntProperty(property, jnlpAlias, localACC);
+  public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
+    return PropertyAccess.isPropertyDefined(property, jnlpAlias, null);
   }
-
-  public static int getIntProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    int i=0;
-    try {
-        Integer iv = Integer.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-        i = iv.intValue();
-    } catch (NumberFormatException nfe) {}
-    return i;
-  }
-
-  static boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
-    return getBooleanProperty(property, jnlpAlias, localACC);
-  }
-
-  public static boolean getBooleanProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    Boolean b = Boolean.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-    return b.booleanValue();
-  }
-
-  static boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
-    return isPropertyDefined(property, jnlpAlias, localACC);
-  }
-
-  public static boolean isPropertyDefined(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    return (Debug.getProperty(property, jnlpAlias, acc) != null) ? true : false;
-  }
-
-  static String getProperty(final String property, final boolean jnlpAlias) {
-    return getProperty(property, jnlpAlias, localACC);
+    
+  public static String getProperty(final String property, final boolean jnlpAlias) {
+    return PropertyAccess.getProperty(property, jnlpAlias, null);
   }
-
-  public static String getProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    String s=null;
-    if(null!=acc && acc.equals(localACC)) {
-        s = (String) AccessController.doPrivileged(new PrivilegedAction() {
-            public Object run() {
-              String val=null;
-              try {
-                  val = System.getProperty(property);
-              } catch (Exception e) {}
-              if(null==val && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-                  try {
-                      val = System.getProperty(jnlp_prefix + property);
-                  } catch (Exception e) {}
-              }
-              return val;
-            }
-          });
-    } else {
-        try {
-            s = System.getProperty(property);
-        } catch (Exception e) {}
-        if(null==s && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-            try {
-                s = System.getProperty(jnlp_prefix + property);
-            } catch (Exception e) {}
-        }
-    }
-    return s;
+  
+  public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
+      return PropertyAccess.getBooleanProperty(property, jnlpAlias, null);
   }
-  public static final String jnlp_prefix = "jnlp." ;
-
+  
   public static boolean verbose() {
     return verbose;
   }
diff --git a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java
index c0a75da..f77f113 100644
--- a/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/DesktopGLDynamicLibraryBundleInfo.java
@@ -36,7 +36,6 @@ public abstract class DesktopGLDynamicLibraryBundleInfo extends GLDynamicLibrary
     static {
         glueLibNames = new ArrayList<String>();
 
-        glueLibNames.addAll(getGlueLibNamesPreload());
         glueLibNames.add("jogl_desktop");
     }
 
@@ -44,10 +43,12 @@ public abstract class DesktopGLDynamicLibraryBundleInfo extends GLDynamicLibrary
         super();
     }
 
+    @Override
     public final List<String> getGlueLibNames() {
         return glueLibNames;
     }
     
+    @Override
     public boolean useToolGetProcAdressFirst(String funcName) {
         return true;
     }
diff --git a/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java b/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java
index a35137f..610f08e 100644
--- a/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java
+++ b/src/jogl/classes/jogamp/opengl/ExtensionAvailabilityCache.java
@@ -51,63 +51,83 @@ import java.util.*;
  */
 final class ExtensionAvailabilityCache {
   protected static final boolean DEBUG = GLContextImpl.DEBUG;
-  private static final boolean DEBUG_AVAILABILITY = Debug.isPropertyDefined("jogl.debug.ExtensionAvailabilityCache", true);
 
-  ExtensionAvailabilityCache(GLContextImpl context)
-  {
-    this.context = context;
+  ExtensionAvailabilityCache() {
+      flush();
   }
 
   /**
-   * Flush the cache. The cache will be rebuilt lazily as calls to {@link
-   * #isExtensionAvailable(String)} are received.
+   * Flush the cache. 
    */
   final void flush()
   {
-    if(DEBUG) {
-        System.out.println("ExtensionAvailabilityCache: Flush availability OpenGL "+context.getGLVersion());
-    }
-    availableExtensionCache.clear();
     initialized = false;
+    glExtensions = null;
+    glExtensionCount = 0;
+    glXExtensions = null;
+    glXExtensionCount = 0;
+    availableExtensionCache.clear();
   }
 
   /**
-   * Flush the cache and rebuild the cache.
+   * Flush and rebuild the cache.
    */
-  final void reset() {
+  final void reset(GLContextImpl context) {
     flush();
-    initAvailableExtensions();
+    initAvailableExtensions(context);
   }
 
   final boolean isInitialized() {
     return initialized && !availableExtensionCache.isEmpty() ;
   }
 
+  final int getTotalExtensionCount() {
+    validateInitialization();
+    return availableExtensionCache.size();
+  }
+  
   final boolean isExtensionAvailable(String glExtensionName) {
-    initAvailableExtensions();
-    return availableExtensionCache.contains(mapGLExtensionName(glExtensionName));
+    validateInitialization();
+    return availableExtensionCache.contains(glExtensionName);
   }
 
+  final int getPlatformExtensionCount() {
+    validateInitialization();
+    return glXExtensionCount;
+  }
+  
   final String getPlatformExtensionsString() {
-    initAvailableExtensions();
+    validateInitialization();
     return glXExtensions;
   }
 
+  final int getGLExtensionCount() {
+    validateInitialization();
+    return glExtensionCount;
+  }
+  
   final String getGLExtensionsString() {
-    initAvailableExtensions();
+    validateInitialization();
     if(DEBUG) {
         System.err.println("ExtensionAvailabilityCache: getGLExtensions() called");
     }
     return glExtensions;
   }
 
-  private final void initAvailableExtensions() {
-    GL gl = context.getGL();
-    // if hash is empty (meaning it was flushed), pre-cache it with the list
-    // of extensions that are in the GL_EXTENSIONS string
-    if (availableExtensionCache.isEmpty() || !initialized) {
+  private final void validateInitialization() {
+      if (!isInitialized()) {
+          throw new InternalError("ExtensionAvailabilityCache not initialized!");
+      }
+  }
+  private final void initAvailableExtensions(GLContextImpl context) {
+      GL gl = context.getGL();
+      // if hash is empty (meaning it was flushed), pre-cache it with the list
+      // of extensions that are in the GL_EXTENSIONS string
+      if (isInitialized()) {
+          throw new InternalError("ExtensionAvailabilityCache already initialized!");
+      }
       if (DEBUG) {
-         System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Pre-caching init "+gl+", OpenGL "+context.getGLVersion());
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Pre-caching init "+gl+", OpenGL "+context.getGLVersion());
       }
 
       boolean useGetStringi = false;
@@ -116,86 +136,96 @@ final class ExtensionAvailabilityCache {
       // on GL2 platforms the function might be available, but not working.
       if ( context.isGL3() ) {
           if ( ! context.isFunctionAvailable("glGetStringi") ) {
-            if(DEBUG) {
-                System.err.println("GLContext: GL >= 3.1 usage, but no glGetStringi");
-            }
+              if(DEBUG) {
+                  System.err.println("GLContext: GL >= 3.1 usage, but no glGetStringi");
+              }
           } else {
               useGetStringi = true;
           }
       }
 
       if (DEBUG) {
-        System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Pre-caching extension availability OpenGL "+context.getGLVersion()+
-                           ", use "+ ( useGetStringi ? "glGetStringi" : "glGetString" ) );
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Pre-caching extension availability OpenGL "+context.getGLVersion()+
+                  ", use "+ ( useGetStringi ? "glGetStringi" : "glGetString" ) );
       }
 
-      StringBuffer sb = new StringBuffer();
+      HashSet<String> glExtensionSet = new HashSet<String>(gl.isGLES() ? 50 : 320); // far less gl extension expected on mobile 
       if(useGetStringi) {
-        GL2GL3 gl2gl3 = gl.getGL2GL3();
-        int[] numExtensions = { 0 } ;
-        gl2gl3.glGetIntegerv(GL2GL3.GL_NUM_EXTENSIONS, numExtensions, 0);
-        for (int i = 0; i < numExtensions[0]; i++) {
-            sb.append(gl2gl3.glGetStringi(GL.GL_EXTENSIONS, i));
-            if(i < numExtensions[0]) {
-                sb.append(" ");
-            }
-        }
-        if (DEBUG) {
-            System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GL_EXTENSIONS: "+numExtensions[0]);
-        }
-        if(0==numExtensions[0]) {
-            // fall back ..
-            useGetStringi=false;
-        }
+          GL2GL3 gl2gl3 = gl.getGL2GL3();
+          final int count;
+          {
+              int[] val = { 0 } ;
+              gl2gl3.glGetIntegerv(GL2GL3.GL_NUM_EXTENSIONS, val, 0);
+              count = val[0];
+          }
+          StringBuilder sb = new StringBuilder();
+          for (int i = 0; i < count; i++) {
+              if(i > 0) {
+                  sb.append(" ");                
+              }
+              final String ext = gl2gl3.glGetStringi(GL.GL_EXTENSIONS, i);
+              glExtensionSet.add(ext);
+              sb.append(ext);
+          }
+          if(0==count || sb.length()==0) {
+              // fall back ..
+              useGetStringi=false;
+          } else {
+              glExtensions = sb.toString();
+          }
       }
       if(!useGetStringi) {
-        sb.append(gl.glGetString(GL.GL_EXTENSIONS));
+          glExtensions = gl.glGetString(GL.GL_EXTENSIONS);
+          if(null != glExtensions) {
+              StringTokenizer tok = new StringTokenizer(glExtensions);
+              while (tok.hasMoreTokens()) {
+                  glExtensionSet.add(tok.nextToken().trim());
+              }
+          }
       }
-      glExtensions = sb.toString();
-      
+      glExtensionCount = glExtensionSet.size(); 
+      if (DEBUG) {
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GL_EXTENSIONS: "+glExtensionCount+
+                                               ", used "+ ( useGetStringi ? "glGetStringi" : "glGetString" ) );
+      }
+
       // Platform Extensions
+      HashSet<String> glXExtensionSet = new HashSet<String>(50);
       {         
-          // unify platform extension .. might have duplicates
-          HashSet<String> platformSet = new HashSet<String>(50);
+          // unify platform extension .. might have duplicates          
           StringTokenizer tok = new StringTokenizer(context.getPlatformExtensionsStringImpl().toString());
           while (tok.hasMoreTokens()) {
-              platformSet.add(tok.nextToken().trim());              
+              glXExtensionSet.add(tok.nextToken().trim());              
           }
-          final StringBuffer sb2 = new StringBuffer();
-          for(Iterator<String> iter = platformSet.iterator(); iter.hasNext(); ) {
-              sb2.append(iter.next()).append(" ");
+          final StringBuilder sb = new StringBuilder();
+          for(Iterator<String> iter = glXExtensionSet.iterator(); iter.hasNext(); ) {
+              sb.append(iter.next());
+              if(iter.hasNext()) {
+                  sb.append(" ");                
+              }
           }
-          glXExtensions = sb2.toString();
+          glXExtensions = sb.toString();
+          glXExtensionCount = glXExtensionSet.size();
       }
-      sb.append(" ");
-      sb.append(glXExtensions);
 
-      String allAvailableExtensions = sb.toString();
-      if (DEBUG_AVAILABILITY) {
-        System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GL vendor: " + gl.glGetString(GL.GL_VENDOR));
-      }
-      StringTokenizer tok = new StringTokenizer(allAvailableExtensions);
-      while (tok.hasMoreTokens()) {
-        String availableExt = tok.nextToken().trim();
-        availableExt = availableExt.intern();
-        availableExtensionCache.add(availableExt);
-        if (DEBUG_AVAILABILITY) {
-          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Available: " + availableExt);
-        }
-      }
+      availableExtensionCache.addAll(glExtensionSet);
+      availableExtensionCache.addAll(glXExtensionSet);
+
       if (DEBUG) {
-        System.err.println(getThreadName() + ":ExtensionAvailabilityCache: ALL EXTENSIONS: "+availableExtensionCache.size());
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GLX_EXTENSIONS: "+glXExtensionCount);
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: GL vendor: " + gl.glGetString(GL.GL_VENDOR));
+          System.err.println(getThreadName() + ":ExtensionAvailabilityCache: ALL EXTENSIONS: "+availableExtensionCache.size());
       }
 
       if(!context.isGLES()) {
           int major[] = new int[] { context.getGLVersionMajor() };
           int minor[] = new int[] { context.getGLVersionMinor() };
           while (GLContext.isValidGLVersion(major[0], minor[0])) {
-            availableExtensionCache.add("GL_VERSION_" + major[0] + "_" + minor[0]);
-            if (DEBUG) {
-                System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Added GL_VERSION_" + major[0] + "_" + minor[0] + " to known extensions");
-            }
-            if(!GLContext.decrementGLVersion(major, minor)) break;
+              availableExtensionCache.add("GL_VERSION_" + major[0] + "_" + minor[0]);
+              if (DEBUG) {
+                  System.err.println(getThreadName() + ":ExtensionAvailabilityCache: Added GL_VERSION_" + major[0] + "_" + minor[0] + " to known extensions");
+              }
+              if(!GLContext.decrementGLVersion(major, minor)) break;
           }
       }
 
@@ -204,17 +234,6 @@ final class ExtensionAvailabilityCache {
       availableExtensionCache.add("<INTERNAL_DUMMY_PLACEHOLDER>");
 
       initialized = true;
-    }
-  }
-
-  // FIXME: hack to re-enable GL_NV_vertex_array_range extension after
-  // recent upgrade to new wglext.h and glxext.h headers
-  private static String mapGLExtensionName(String extensionName) {
-    if (extensionName != null &&
-        (extensionName.equals("WGL_NV_vertex_array_range") ||
-         extensionName.equals("GLX_NV_vertex_array_range"))) 
-      return "GL_NV_vertex_array_range";
-    return extensionName;
   }
 
   //----------------------------------------------------------------------
@@ -223,9 +242,10 @@ final class ExtensionAvailabilityCache {
 
   private boolean initialized = false;
   private String glExtensions = null;
+  private int glExtensionCount = 0;
   private String glXExtensions = null;
+  private int glXExtensionCount = 0;
   private HashSet<String> availableExtensionCache = new HashSet<String>(50);
-  private GLContextImpl context;
 
   static String getThreadName() {
     return Thread.currentThread().getName();
diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java
index 28bb11f..f348564 100644
--- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java
+++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java
@@ -47,8 +47,6 @@ import java.util.Map;
 
 import com.jogamp.common.os.DynamicLookupHelper;
 import com.jogamp.common.util.ReflectionUtil;
-import com.jogamp.common.util.locks.LockFactory;
-import com.jogamp.common.util.locks.RecursiveLock;
 import com.jogamp.gluegen.runtime.FunctionAddressResolver;
 import com.jogamp.gluegen.runtime.ProcAddressTable;
 import com.jogamp.gluegen.runtime.opengl.GLExtensionNames;
@@ -69,9 +67,6 @@ import javax.media.opengl.GLPipelineFactory;
 import javax.media.opengl.GLProfile;
 
 public abstract class GLContextImpl extends GLContext {
-  // RecursiveLock maintains a queue of waiting Threads, ensuring the longest waiting thread will be notified at unlock.  
-  protected RecursiveLock lock = LockFactory.createRecursiveLock();
-
   /**
    * Context full qualified name: display_type + display_connection + major + minor + ctp.
    * This is the key for all cached GL ProcAddressTables, etc, to support multi display/device setups.
@@ -87,6 +82,9 @@ public abstract class GLContextImpl extends GLContext {
   // OpenGL functions.
   private ProcAddressTable glProcAddressTable;
 
+  private String glRenderer;
+  private String glRendererLowerCase;
+  
   // Tracks creation and initialization of buffer objects to avoid
   // repeated glGet calls upon glMapBuffer operations
   private GLBufferSizeTracker bufferSizeTracker; // Singleton - Set by GLContextShareSet
@@ -156,6 +154,9 @@ public abstract class GLContextImpl extends GLContext {
       contextFQN = null;
       additionalCtxCreationFlags = 0;
 
+      glRenderer = "";
+      glRendererLowerCase = glRenderer;
+      
       super.resetStates();
   }
 
@@ -213,74 +214,96 @@ public abstract class GLContextImpl extends GLContext {
    */
   protected void drawableUpdatedNotify() throws GLException { }
 
-  boolean lockFailFast = true;
-  Object lockFailFastSync = new Object();
+  volatile boolean lockFailFast = true;
   
   public boolean isSynchronized() {
-    synchronized (lockFailFastSync) {
-        return !lockFailFast;
-    }
+    return !lockFailFast; // volatile: ok
   }
 
   public void setSynchronized(boolean isSynchronized) {
-    synchronized (lockFailFastSync) {
-        lockFailFast = !isSynchronized;
-    }
+    lockFailFast = !isSynchronized; // volatile: ok
   }
 
-  private final void lockConsiderFailFast()  {
-      synchronized (lockFailFastSync) {
-          if(lockFailFast && lock.isLockedByOtherThread()) {
-                throw new GLException("Error: Attempt to make context current on thread " + Thread.currentThread() +
-                                      " which is already current on thread " + lock.getOwner());
+  private final void lockConsiderFailFast() {
+      if( lockFailFast ) { // volatile: ok
+          try {
+              if( !lock.tryLock(0) ) { // immediate return w/ false, if lock is already held by other thread
+                    throw new GLException("Error: Attempt to make context current on thread " + Thread.currentThread().getName() +
+                                          " which is already current on thread " + lock.getOwner().getName());              
+              }
+          } catch (InterruptedException ie) {
+              throw new GLException(ie);
           }
+      } else {
+          lock.lock();
       }
-      lock.lock();
   }
     
   public abstract Object getPlatformGLExtensions();
 
   // Note: the surface is locked within [makeCurrent .. swap .. release]
   public void release() throws GLException {
+    release(false);
+  }
+  private void release(boolean force) throws GLException {
+    if(TRACE_SWITCH) {
+        System.err.println(getThreadName() +": GLContext.ContextSwitch: - release() - force: "+force+", "+lock);
+    }
     if ( !lock.isOwner() ) {
-      throw new GLException("Context not current on current thread");
+      throw new GLException("Context not current on current thread "+Thread.currentThread().getName()+": "+this);
     }
-    setCurrent(null);
-    try {
-        releaseImpl();
+    final boolean actualRelease = force || lock.getHoldCount() == 1 ;
+    try {        
+        if( actualRelease ) {
+            if (contextHandle != 0) { // allow dbl-release
+                releaseImpl();
+            }
+        }
     } finally {
-      if (drawable.isSurfaceLocked()) {
-          drawable.unlockSurface();
+      // exception prone ..
+      if( actualRelease ) {
+          setCurrent(null);
       }
+      drawable.unlockSurface();
       lock.unlock();
+      if(TRACE_SWITCH) {
+          System.err.println(getThreadName() +": GLContext.ContextSwitch: - "+(actualRelease?"switch":"keep  ")+" - CONTEXT_RELEASE - "+lock);
+      }
     }
   }
   protected abstract void releaseImpl() throws GLException;
 
   public final void destroy() {
-    if ( lock.isOwner() ) {
-        // release current context
-        if(null != glDebugHandler) {
-            glDebugHandler.enable(false);
-        }
-        release();
-    }
-
     // Must hold the lock around the destroy operation to make sure we
     // don't destroy the context out from under another thread rendering to it
-    lockConsiderFailFast();
+    lockConsiderFailFast(); // holdCount++ -> 1 or 2
     try {
+      if(lock.getHoldCount() > 2) {
+          throw new GLException("XXX: "+lock);
+      }
+      if (DEBUG || TRACE_SWITCH) {          
+          System.err.println(getThreadName() + ": GLContextImpl.destroy.0: " + toHexString(contextHandle) +
+                  ", isShared "+GLContextShareSet.isShared(this)+" - "+lock);
+      }
       if (contextHandle != 0) {
           int lockRes = drawable.lockSurface();
           if (NativeSurface.LOCK_SURFACE_NOT_READY == lockRes) {
                 // this would be odd ..
                 throw new GLException("Surface not ready to lock: "+drawable);
           }
-          try {
-              if (DEBUG) {
-                  System.err.println("GLContextImpl.destroy: " + toHexString(contextHandle) +
-                          ", isShared "+GLContextShareSet.isShared(this));
+          // release current context
+          if(null != glDebugHandler) {
+              if(lock.getHoldCount() == 1) {
+                  // needs current context to disable debug handler
+                  makeCurrent();
               }
+              glDebugHandler.enable(false);
+          }
+          if(lock.getHoldCount() > 1) {
+              // pending release() after makeCurrent()
+              release(true); 
+          }
+          try {
               destroyImpl();
               contextHandle = 0;
               glDebugHandler = null;
@@ -294,6 +317,10 @@ public abstract class GLContextImpl extends GLContext {
       }
     } finally {
       lock.unlock();
+      if (TRACE_SWITCH) {
+          System.err.println(getThreadName() + ": GLContextImpl.destroy.X: " + toHexString(contextHandle) +
+                  ", isShared "+GLContextShareSet.isShared(this)+" - "+lock);
+      }
     }
 
     resetStates();
@@ -362,55 +389,69 @@ public abstract class GLContextImpl extends GLContext {
    * @see #destroyContextARBImpl
    */
   public int makeCurrent() throws GLException {
-    // One context can only be current by one thread,
-    // and one thread can only have one context current!
-    final GLContext current = getCurrent();
-    if (current != null) {
-      if (current == this) {
-        // Assume we don't need to make this context current again
-        // For Mac OS X, however, we need to update the context to track resizes
-        drawableUpdatedNotify();
-        return CONTEXT_CURRENT;
-      } else {
-        current.release();
-      }
-    }
-
-    if (GLWorkerThread.isStarted() &&
-        !GLWorkerThread.isWorkerThread()) {
-      // Kick the GLWorkerThread off its current context
-      GLWorkerThread.invokeLater(new Runnable() { public void run() {} });
-    }
-
-    if (!isCreated()) {
-        // verify if the drawable has chosen Capabilities
-        if (null == getGLDrawable().getChosenGLCapabilities()) {
-            throw new GLException("drawable has no chosen GLCapabilities: "+getGLDrawable());
-        }
-        if(DEBUG_GL) {
-            // only impacts w/ createContextARB(..)
-            additionalCtxCreationFlags |= GLContext.CTX_OPTION_DEBUG ;
-        }
-    }
-
+    boolean unlockContextAndDrawable = false;
     lockConsiderFailFast();
-    int res = 0;
+    int res = CONTEXT_NOT_CURRENT;
     try {
-      res = makeCurrentLocking();
-
-      /* FIXME: refactor dependence on Java 2D / JOGL bridge
-      if ((tracker != null) &&
-          (res == CONTEXT_CURRENT_NEW)) {
-        // Increase reference count of GLObjectTracker
-        tracker.ref();
-      }
-      */
-    } catch (GLException e) {
-      lock.unlock();
-      throw(e);
+        // Note: the surface is locked within [makeCurrent .. swap .. release]
+        int lockRes = drawable.lockSurface();
+        if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) {
+            return CONTEXT_NOT_CURRENT;
+        }
+        try {
+            if (NativeSurface.LOCK_SURFACE_CHANGED == lockRes) {
+                drawable.updateHandle();
+            }
+            // One context can only be current by one thread,
+            // and one thread can only have one context current!
+            final GLContext current = getCurrent();
+            if (current != null) {
+                if (current == this) {
+                    // Assume we don't need to make this context current again
+                    // For Mac OS X, however, we need to update the context to track resizes
+                    drawableUpdatedNotify();
+                    if(TRACE_SWITCH) {
+                        System.err.println(getThreadName() +": GLContext.ContextSwitch: - keep   - CONTEXT_CURRENT - "+lock);
+                    }
+                    return CONTEXT_CURRENT;
+                } else {
+                    current.release();
+                }
+            }    
+            if (0 == drawable.getHandle()) {
+                throw new GLException("drawable has invalid handle: "+drawable);
+            }
+            res = makeCurrentWithinLock(lockRes);
+            unlockContextAndDrawable = CONTEXT_NOT_CURRENT == res;
+            
+            /**
+             * FIXME: refactor dependence on Java 2D / JOGL bridge
+                if ((tracker != null) &&
+                    (res == CONTEXT_CURRENT_NEW)) {
+                    // Increase reference count of GLObjectTracker
+                    tracker.ref();
+                }
+             */
+        } catch (RuntimeException e) {
+          unlockContextAndDrawable = true;
+          throw e;
+        } finally {
+          if (unlockContextAndDrawable) {
+            drawable.unlockSurface();
+          }            
+        }
+    } catch (RuntimeException e) {
+      unlockContextAndDrawable = true;
+      throw e;
+    } finally {
+      if (unlockContextAndDrawable) {
+        lock.unlock();
+      }            
     }
     if (res == CONTEXT_NOT_CURRENT) {
-      lock.unlock();
+      if(TRACE_SWITCH) {
+          System.err.println(getThreadName() +": GLContext.ContextSwitch: - switch - CONTEXT_NOT_CURRENT - "+lock);
+      }
     } else {
       setCurrent(this);
       if(res == CONTEXT_CURRENT_NEW) {
@@ -429,6 +470,11 @@ public abstract class GLContextImpl extends GLContext {
         if(TRACE_GL) {
             gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) );
         }               
+        if(DEBUG || TRACE_SWITCH) {
+            System.err.println(getThreadName() +": GLContext.ContextSwitch: - switch - CONTEXT_CURRENT_NEW - "+lock);
+        }
+      } else if(TRACE_SWITCH) {
+        System.err.println(getThreadName() +": GLContext.ContextSwitch: - switch - CONTEXT_CURRENT - "+lock);
       }
 
       /* FIXME: refactor dependence on Java 2D / JOGL bridge
@@ -443,66 +489,80 @@ public abstract class GLContextImpl extends GLContext {
     return res;
   }
 
-  // Note: the surface is locked within [makeCurrent .. swap .. release]
-  protected final int makeCurrentLocking() throws GLException {
-    boolean shallUnlockSurface = false;
-    int lockRes = drawable.lockSurface();
-    try {
-      if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) {
-        return CONTEXT_NOT_CURRENT;
-      }
-      try {
-          if (NativeSurface.LOCK_SURFACE_CHANGED == lockRes) {
-            drawable.updateHandle();
-          }
-          if (0 == drawable.getHandle()) {
-              throw new GLException("drawable has invalid handle: "+drawable);
-          }
-          if (!isCreated()) {
-            final GLContextImpl shareWith = (GLContextImpl) GLContextShareSet.getShareContext(this);
+  private final int makeCurrentWithinLock(int surfaceLockRes) throws GLException {
+      if (!isCreated()) {
+        if(DEBUG_GL) {
+            // only impacts w/ createContextARB(..)
+            additionalCtxCreationFlags |= GLContext.CTX_OPTION_DEBUG ;
+        }
+    
+        final GLContextImpl shareWith = (GLContextImpl) GLContextShareSet.getShareContext(this);
+        if (null != shareWith) {
+            shareWith.getDrawableImpl().lockSurface();
+        }
+        final boolean created;
+        try {
+            created = createImpl(shareWith); // may throws exception if fails!
+        } finally {
             if (null != shareWith) {
-                shareWith.getDrawableImpl().lockSurface();
-            }
-            boolean created;
-            try {
-                created = createImpl(shareWith); // may throws exception if fails!
-            } finally {
-                if (null != shareWith) {
-                    shareWith.getDrawableImpl().unlockSurface();
-                }                
+                shareWith.getDrawableImpl().unlockSurface();
+            }                
+        }
+        if (DEBUG) {
+            if(created) {
+                System.err.println(getThreadName() + ": Create GL context OK: " + toHexString(contextHandle) + " for " + getClass().getName()+" - "+getGLVersion());
+            } else {
+                System.err.println(getThreadName() + ": Create GL context FAILED for " + getClass().getName());
             }
-            if (DEBUG) {
-                if(created) {
-                    System.err.println(getThreadName() + ": !!! Create GL context OK: " + toHexString(contextHandle) + " for " + getClass().getName());
+        }        
+        if(!created) {
+            return CONTEXT_NOT_CURRENT;
+        }
+        
+        // finalize mapping the available GLVersions, in case it's not done yet
+        {             
+            final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration();
+            final AbstractGraphicsDevice device = config.getScreen().getDevice();
+            
+            if( !GLContext.getAvailableGLVersionsSet(device) ) {
+                final int reqMajor;
+                final int reqProfile;
+                if( 0 != ( ctxOptions & GLContext.CTX_PROFILE_ES) ) {
+                    // ES1 or ES2
+                    reqMajor = ctxMajorVersion;
+                    reqProfile = GLContext.CTX_PROFILE_ES;
                 } else {
-                    System.err.println(getThreadName() + ": !!! Create GL context FAILED for " + getClass().getName());
+                    if(ctxMajorVersion<3 || ctxMajorVersion==3 && ctxMinorVersion==0) { 
+                        reqMajor = 2;
+                    } else {
+                        reqMajor = ctxMajorVersion;
+                    }
+                    if( 0 != ( ctxOptions & GLContext.CTX_PROFILE_CORE) ) {
+                        reqProfile = GLContext.CTX_PROFILE_CORE;
+                    } else {
+                        reqProfile = GLContext.CTX_PROFILE_COMPAT;
+                    }
+                }
+                GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile,
+                                                ctxMajorVersion, ctxMinorVersion, ctxOptions);
+                GLContext.setAvailableGLVersionsSet(device);
+                if (DEBUG) {
+                  System.err.println(getThreadName() + ": createContextOLD-MapVersionsAvailable HAVE: " + device+" -> "+reqMajor+"."+reqProfile+ " -> "+getGLVersion());
                 }
             }
-            if(!created) {
-                shallUnlockSurface = true;
-                return CONTEXT_NOT_CURRENT;
-            }
-            GLContextShareSet.contextCreated(this);
-            return CONTEXT_CURRENT_NEW;
-          }
-          makeCurrentImpl();
-          return CONTEXT_CURRENT;
-      } catch (RuntimeException e) {
-        shallUnlockSurface = true;
-        throw e;
-      }
-    } finally {
-      if (shallUnlockSurface) {
-        drawable.unlockSurface();
+        }
+        GLContextShareSet.contextCreated(this);
+        return CONTEXT_CURRENT_NEW;
       }
-    }
+      makeCurrentImpl();
+      return CONTEXT_CURRENT;
   }
   protected abstract void makeCurrentImpl() throws GLException;
   
   /** 
    * Platform dependent entry point for context creation.<br>
    *
-   * This method is called from {@link #makeCurrentLocking()} .. {@link #makeCurrent()} .<br>
+   * This method is called from {@link #makeCurrentWithinLock()} .. {@link #makeCurrent()} .<br>
    *
    * The implementation shall verify this context with a 
    * <code>MakeContextCurrent</code> call.<br>
@@ -586,12 +646,15 @@ public abstract class GLContextImpl extends GLContext {
     GLProfile glpImpl = glp.getImpl();
 
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! createContextARB: mappedVersionsAvailableSet("+device.getConnection()+"): "+
+      System.err.println(getThreadName() + ": createContextARB: mappedVersionsAvailableSet("+device.getConnection()+"): "+
                GLContext.getAvailableGLVersionsSet(device));
     }
 
     if ( !GLContext.getAvailableGLVersionsSet(device) ) {
-        mapGLVersions(device);
+        if(!mapGLVersions(device)) {
+            // none of the ARB context creation calls was successful, bail out 
+            return 0;
+        }
     }
 
     int reqMajor;
@@ -620,22 +683,29 @@ public abstract class GLContextImpl extends GLContext {
     return _ctx;
   }
 
-  private final void mapGLVersions(AbstractGraphicsDevice device) {    
+  private final boolean mapGLVersions(AbstractGraphicsDevice device) {    
     synchronized (GLContext.deviceVersionAvailable) {
-        createContextARBMapVersionsAvailable(4, true  /* compat */);  // GL4bc
-        createContextARBMapVersionsAvailable(4, false /* core   */);  // GL4
-        createContextARBMapVersionsAvailable(3, true  /* compat */);  // GL3bc
-        createContextARBMapVersionsAvailable(3, false /* core   */);  // GL3
-        createContextARBMapVersionsAvailable(2, true  /* compat */);  // GL2
-        GLContext.setAvailableGLVersionsSet(device);
-        resetStates();
+        boolean success = false;
+        // Following GLProfile.GL_PROFILE_LIST_ALL order of profile detection { GL4bc, GL3bc, GL2, GL4, GL3, GL2GL3, GLES2, GL2ES2, GLES1, GL2ES1 }
+        success |= createContextARBMapVersionsAvailable(4, true  /* compat */);  // GL4bc
+        success |= createContextARBMapVersionsAvailable(3, true  /* compat */);  // GL3bc
+        success |= createContextARBMapVersionsAvailable(2, true  /* compat */);  // GL2        
+        success |= createContextARBMapVersionsAvailable(4, false /* core   */);  // GL4
+        success |= createContextARBMapVersionsAvailable(3, false /* core   */);  // GL3
+        if(success) {
+            // only claim GL versions set [and hence detected] if ARB context creation was successful
+            GLContext.setAvailableGLVersionsSet(device);
+        } else if (DEBUG) {
+            System.err.println(getThreadName() + ": createContextARB-MapVersions NONE for :"+device);
+        }        
+        return success;
     }
   }
 
-  private final void createContextARBMapVersionsAvailable(int reqMajor, boolean compat) {
+  private final boolean createContextARBMapVersionsAvailable(int reqMajor, boolean compat) {
     long _context;
     int reqProfile = compat ? CTX_PROFILE_COMPAT : CTX_PROFILE_CORE ;
-    int ctp = CTX_IS_ARB_CREATED | CTX_PROFILE_CORE | CTX_OPTION_ANY; // default
+    int ctp = CTX_IS_ARB_CREATED | CTX_PROFILE_CORE; // default
     if(compat) {
         ctp &= ~CTX_PROFILE_CORE ;
         ctp |=  CTX_PROFILE_COMPAT ;
@@ -655,8 +725,10 @@ public abstract class GLContextImpl extends GLContext {
         majorMax=3; minorMax=GLContext.getMaxMinor(majorMax);
         majorMin=3; minorMin=1;
     } else /* if( glp.isGL2() ) */ {
+        // our minimum desktop OpenGL runtime requirements are 1.1, 
+        // nevertheless we restrict ARB context creation to 2.0 to spare us futile attempts 
         majorMax=3; minorMax=0;
-        majorMin=1; minorMin=1; // our minimum desktop OpenGL runtime requirements
+        majorMin=2; minorMin=0;
     }
     _context = createContextARBVersions(0, true, ctp, 
                                         /* max */ majorMax, minorMax,
@@ -664,9 +736,8 @@ public abstract class GLContextImpl extends GLContext {
                                         /* res */ major, minor);
 
     if(0==_context && !compat) {
-        ctp &= ~CTX_PROFILE_COMPAT ;
-        ctp |=  CTX_PROFILE_CORE ;
-        ctp &= ~CTX_OPTION_ANY ;
+        // try w/ FORWARD instead of CORE
+        ctp &= ~CTX_PROFILE_CORE ;
         ctp |=  CTX_OPTION_FORWARD ;
         _context = createContextARBVersions(0, true, ctp, 
                                             /* max */ majorMax, minorMax,
@@ -675,9 +746,8 @@ public abstract class GLContextImpl extends GLContext {
        if(0==_context) {
             // Try a compatible one .. even though not requested .. last resort
             ctp &= ~CTX_PROFILE_CORE ;
-            ctp |=  CTX_PROFILE_COMPAT ;
             ctp &= ~CTX_OPTION_FORWARD ;
-            ctp |=  CTX_OPTION_ANY ;
+            ctp |=  CTX_PROFILE_COMPAT ;
             _context = createContextARBVersions(0, true, ctp, 
                                        /* max */ majorMax, minorMax,
                                        /* min */ majorMin, minorMin,
@@ -685,18 +755,22 @@ public abstract class GLContextImpl extends GLContext {
        }
     }
     if(0!=_context) {
-        AbstractGraphicsDevice device = drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
-        if( isExtensionAvailable("GL_ARB_ES2_compatibility") ) {
-            ctp |= CTX_PROFILE_ES2_COMPAT;
-        }
-        GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, major[0], minor[0], ctp);
+        AbstractGraphicsDevice device = drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();        
+        // ctxMajorVersion, ctxMinorVersion, ctxOptions is being set by 
+        //   createContextARBVersions(..) -> setGLFunctionAvailbility(..) -> setContextVersion(..)
+        GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, ctxMajorVersion, ctxMinorVersion, ctxOptions);
         destroyContextARBImpl(_context);
         if (DEBUG) {
-          System.err.println(getThreadName() + ": !!! createContextARBMapVersionsAvailable HAVE: "+
-                  GLContext.getAvailableGLVersionAsString(device, reqMajor, reqProfile));
+          System.err.println(getThreadName() + ": createContextARB-MapVersionsAvailable HAVE: " +reqMajor+"."+reqProfile+ " -> "+getGLVersion());
         }
-    } else if (DEBUG) {
-        System.err.println(getThreadName() + ": !!! createContextARBMapVersionsAvailable NOPE: "+reqMajor+"."+reqProfile);
+        // only reset [and hence modify] this context state if ARB context creation was successful
+        resetStates(); 
+        return true;
+    } else {
+        if (DEBUG) {
+          System.err.println(getThreadName() + ": createContextARB-MapVersionsAvailable NOPE: "+reqMajor+"."+reqProfile);
+        }        
+        return false;
     }
   }
 
@@ -757,7 +831,7 @@ public abstract class GLContextImpl extends GLContext {
    * If major==0 && minor == 0 : Use GL_VERSION
    * Otherwise .. don't touch ..
    */
-  private final void setContextVersion(int major, int minor, int ctp) {
+  private final void setContextVersion(int major, int minor, int ctp, boolean setVersionString) {
       if (0==ctp) {
         throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp));
       }
@@ -769,7 +843,9 @@ public abstract class GLContextImpl extends GLContext {
           ctxMajorVersion = major;
           ctxMinorVersion = minor;
           ctxOptions = ctp;
-          ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, getGL().glGetString(GL.GL_VERSION));
+          if(setVersionString) {
+              ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, getGL().glGetString(GL.GL_VERSION));
+          }
           return;
       }
 
@@ -792,7 +868,9 @@ public abstract class GLContextImpl extends GLContext {
                 ctxMajorVersion = 3;
                 ctxMinorVersion = 0;
             }
-            ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, versionStr);
+            if(setVersionString) {
+                ctxVersionString = getGLVersion(ctxMajorVersion, ctxMinorVersion, ctxOptions, versionStr);
+            }
             return;
           }
       }
@@ -880,6 +958,30 @@ public abstract class GLContextImpl extends GLContext {
     table.reset(getDrawableImpl().getGLDynamicLookupHelper() );
   }
 
+  private final void initGLRendererStrings()  {
+    final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper();
+    final long _glGetString = glDynLookupHelper.dynamicLookupFunction("glGetString");
+    if(0 == _glGetString) {
+        // FIXME
+        System.err.println("Warning: Entry point to 'glGetString' is NULL.");
+        Thread.dumpStack();        
+    } else {
+        final String _glRenderer = glGetStringInt(GL.GL_RENDERER, _glGetString);
+        if(null == _glRenderer) {
+            // FIXME
+            System.err.println("Warning: GL_RENDERER is NULL.");
+            Thread.dumpStack();                
+        } else {
+            glRenderer = _glRenderer;
+            glRendererLowerCase = glRenderer.toLowerCase();
+        }
+    }
+  }
+  
+  protected final String getGLRendererString(boolean lowerCase) {
+      return lowerCase ? glRendererLowerCase : glRenderer;
+  }
+  
   /**
    * Sets the OpenGL implementation class and
    * the cache of which GL functions are available for calling through this
@@ -898,24 +1000,29 @@ public abstract class GLContextImpl extends GLContext {
    * @see #setContextVersion
    * @see javax.media.opengl.GLContext#CTX_OPTION_ANY
    * @see javax.media.opengl.GLContext#CTX_PROFILE_COMPAT
+   * @see javax.media.opengl.GLContext#CTX_IMPL_ES2_COMPAT
    */
   protected final void setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits) {
     if(null!=this.gl && null!=glProcAddressTable && !force) {
         return; // already done and not forced
     }
-    
+
     if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) {
         setGL(createGL(getGLDrawable().getGLProfile()));
     }
-
     updateGLXProcAddressTable();
 
-    AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration();
-    AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
-    final int ctxImplBits = drawable.getChosenGLCapabilities().getHardwareAccelerated() ? GLContext.CTX_IMPL_ACCEL_HARD : GLContext.CTX_IMPL_ACCEL_SOFT;
-    contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits, ctxImplBits);
+    initGLRendererStrings();
+    
+    if(!isCurrentContextHardwareRasterizer()) {
+        ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT;
+    }    
+    final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration();
+    final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
+    
+    contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits);
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! Context FQN: "+contextFQN);
+      System.err.println(getThreadName() + ": Context FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null));
     }
 
     //
@@ -925,35 +1032,28 @@ public abstract class GLContextImpl extends GLContext {
     synchronized(mappedContextTypeObjectLock) {
         table = mappedGLProcAddress.get( contextFQN );
         if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) {
-            throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+") -> "+
-                  table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName());
+            throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ 
+                  ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName());
         }
     }
     if(null != table) {
         glProcAddressTable = table;
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+table.hashCode());
+            System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode()));
         }
     } else {
-        if (glProcAddressTable == null) {
-          glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable",
-                                                                 new Class[] { FunctionAddressResolver.class } ,
-                                                                 new Object[] { new GLProcAddressResolver() } );
-        }
+        glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable",
+                                                               new Class[] { FunctionAddressResolver.class } ,
+                                                               new Object[] { new GLProcAddressResolver() } );
         resetProcAddressTable(getGLProcAddressTable());
         synchronized(mappedContextTypeObjectLock) {
             mappedGLProcAddress.put(contextFQN, getGLProcAddressTable());
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+getGLProcAddressTable().hashCode());
+                System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode()));
             }
         }
     }
-
-    //
-    // Set GL Version
-    //
-    setContextVersion(major, minor, ctxProfileBits);
-
+    
     //
     // Update ExtensionAvailabilityCache
     //
@@ -964,78 +1064,93 @@ public abstract class GLContextImpl extends GLContext {
     if(null !=  eCache) {
         extensionAvailability = eCache;
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+eCache.hashCode());
+            System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount());
         }
     } else {
-        if(null==extensionAvailability) {
-            extensionAvailability = new ExtensionAvailabilityCache(this);
-        }
-        extensionAvailability.reset();
+        extensionAvailability = new ExtensionAvailabilityCache();
+        setContextVersion(major, minor, ctxProfileBits, false); // pre-set of GL version, required for extension cache usage
+        extensionAvailability.reset(this);
         synchronized(mappedContextTypeObjectLock) {
             mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability);
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+extensionAvailability.hashCode());
+                System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount());
             }
         }
+    }    
+    if( isExtensionAvailable("GL_ARB_ES2_compatibility") ) {
+        ctxProfileBits |= CTX_IMPL_ES2_COMPAT;
     }
+    
+    //
+    // Set GL Version (complete w/ version string)
+    //
+    setContextVersion(major, minor, ctxProfileBits, true);
+    
+    setDefaultSwapInterval();
   }
 
   protected final void removeCachedVersion(int major, int minor, int ctxProfileBits) {
-    AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration();
-    AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
-    final int ctxImplBits = drawable.getChosenGLCapabilities().getHardwareAccelerated() ? GLContext.CTX_IMPL_ACCEL_HARD : GLContext.CTX_IMPL_ACCEL_SOFT;
-    contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits, ctxImplBits);
+    if(!isCurrentContextHardwareRasterizer()) {
+        ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT;
+    }
+    final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration();
+    final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
+    
+    contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits);
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! RM Context FQN: "+contextFQN);
+      System.err.println(getThreadName() + ": RM Context FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null));
     }
 
     synchronized(mappedContextTypeObjectLock) {
         ProcAddressTable table = mappedGLProcAddress.remove( contextFQN );
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! RM GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+table.hashCode());
+            System.err.println(getThreadName() + ": RM GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+table.hashCode());
         }
     }
 
     synchronized(mappedContextTypeObjectLock) {
-        ExtensionAvailabilityCache  eCache = mappedExtensionAvailabilityCache.get( contextFQN );
+        ExtensionAvailabilityCache  eCache = mappedExtensionAvailabilityCache.remove( contextFQN );
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! RM GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+eCache.hashCode());
+            System.err.println(getThreadName() + ": RM GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+eCache.hashCode());
         }
     }
   }
+
+  private final boolean isCurrentContextHardwareRasterizer()  {
+    boolean isHardwareRasterizer = true;
+    
+    if(!drawable.getChosenGLCapabilities().getHardwareAccelerated()) {
+        isHardwareRasterizer = false;
+    } else {
+        isHardwareRasterizer = ! ( glRendererLowerCase.contains("software") /* Mesa3D */  ||
+                                   glRendererLowerCase.contains("mesa x11") /* Mesa3D*/   ||
+                                   glRendererLowerCase.contains("softpipe") /* Gallium */ ||
+                                   glRendererLowerCase.contains("llvmpipe") /* Gallium */                                
+                                 );
+    }
+    return isHardwareRasterizer;
+  }
   
   /**
    * Updates the platform's 'GLX' function cache
    */
   protected abstract void updateGLXProcAddressTable();
 
-  protected abstract StringBuffer getPlatformExtensionsStringImpl();
+  protected abstract StringBuilder getPlatformExtensionsStringImpl();
   
-  /**
-   * Returns true if the specified OpenGL core- or extension-function can be
-   * successfully called using this GL context given the current host (OpenGL
-   * <i>client</i>) and display (OpenGL <i>server</i>) configuration.
-   *
-   * See {@link GL#isFunctionAvailable(String)} for more details.
-   *
-   * @param glFunctionName the name of the OpenGL function (e.g., use
-   * "glPolygonOffsetEXT" or "glPolygonOffset" to check if the {@link
-   * javax.media.opengl.GL#glPolygonOffset(float,float)} is available).
-   */
   public final boolean isFunctionAvailable(String glFunctionName) {
     // Check GL 1st (cached)
-    ProcAddressTable pTable = getGLProcAddressTable(); // null if ctx not created once
-    if(null!=pTable) {
+    if(null!=glProcAddressTable) { // null if this context wasn't not created
         try {
-            if(0!=pTable.getAddressFor(glFunctionName)) {
+            if(0!=glProcAddressTable.getAddressFor(glFunctionName)) {
                 return true;
             }
         } catch (Exception e) {}
     }
 
-    // Check platform extensions 2nd (cached) - had to be enabled once
-    pTable = getPlatformExtProcAddressTable(); // null if ctx not created once
-    if(null!=pTable) {
+    // Check platform extensions 2nd (cached) - context had to be enabled once
+    final ProcAddressTable pTable = getPlatformExtProcAddressTable(); 
+    if(null!=pTable) { 
         try {
             if(0!=pTable.getAddressFor(glFunctionName)) {
                 return true;
@@ -1060,16 +1175,6 @@ public abstract class GLContextImpl extends GLContext {
     return false;
   }
 
-  /**
-   * Returns true if the specified OpenGL extension can be
-   * successfully called using this GL context given the current host (OpenGL
-   * <i>client</i>) and display (OpenGL <i>server</i>) configuration.
-   *
-   * See {@link GL#isExtensionAvailable(String)} for more details.
-   *
-   * @param glExtensionName the name of the OpenGL extension (e.g.,
-   * "GL_VERTEX_PROGRAM_ARB").
-   */
   public boolean isExtensionAvailable(String glExtensionName) {
       if(null!=extensionAvailability) {
         return extensionAvailability.isExtensionAvailable(mapToRealGLExtensionName(glExtensionName));
@@ -1077,6 +1182,10 @@ public abstract class GLContextImpl extends GLContext {
       return false;
   }
 
+  public final int getPlatformExtensionCount() {
+      return null != extensionAvailability ? extensionAvailability.getPlatformExtensionCount() : 0;
+  }
+  
   public final String getPlatformExtensionsString() {
       if(null!=extensionAvailability) {
         return extensionAvailability.getPlatformExtensionsString();
@@ -1084,6 +1193,10 @@ public abstract class GLContextImpl extends GLContext {
       return null;
   }
 
+  public final int getGLExtensionCount() {
+      return null != extensionAvailability ? extensionAvailability.getGLExtensionCount() : 0;
+  }
+  
   public final String getGLExtensionsString() {
       if(null!=extensionAvailability) {
         return extensionAvailability.getGLExtensionsString();
@@ -1097,9 +1210,12 @@ public abstract class GLContextImpl extends GLContext {
       }
       return false;
   }
-
-  protected static String getContextFQN(AbstractGraphicsDevice device, int major, int minor, int ctxProfileBits, int ctxImplBits) {
-      return device.getUniqueID() + "-" + toHexString(compose8bit(major, minor, ctxProfileBits, ctxImplBits));
+  
+  protected static String getContextFQN(AbstractGraphicsDevice device, int major, int minor, int ctxProfileBits) {
+      // remove non-key values
+      ctxProfileBits &= ~( GLContext.CTX_OPTION_DEBUG | GLContext.CTX_IMPL_ES2_COMPAT ) ; 
+            
+      return device.getUniqueID() + "-" + toHexString(composeBits(major, minor, ctxProfileBits));
   }
 
   protected String getContextFQN() {
@@ -1224,4 +1340,7 @@ public abstract class GLContextImpl extends GLContext {
           gl.getGL2GL3().glDebugMessageInsertAMD(GLDebugMessage.translateARB2AMDCategory(source, type), severity, id, len, buf);
       }      
   }
+  
+  /** Internal bootstraping glGetString(GL_RENDERER) */
+  protected static native String glGetStringInt(int name, long procAddress);
 }
diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java
index e5f415a..3c60eb6 100644
--- a/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java
+++ b/src/jogl/classes/jogamp/opengl/GLDrawableFactoryImpl.java
@@ -58,7 +58,8 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLPbuffer;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
+
 
 /** Extends GLDrawableFactory with a few methods for handling
     typically software-accelerated offscreen rendering (Device
diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java
index 1453a85..c992b3c 100644
--- a/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java
+++ b/src/jogl/classes/jogamp/opengl/GLDrawableHelper.java
@@ -57,6 +57,9 @@ import com.jogamp.opengl.util.Animator;
     methods to be able to share it between GLCanvas and GLJPanel. */
 
 public class GLDrawableHelper {
+  /** true if property <code>jogl.debug.GLDrawable.PerfStats</code> is defined. */
+  private static final boolean PERF_STATS = Debug.isPropertyDefined("jogl.debug.GLDrawable.PerfStats", true);
+    
   protected static final boolean DEBUG = GLDrawableImpl.DEBUG;
   private Object listenersLock = new Object();
   private ArrayList<GLEventListener> listeners;
@@ -128,6 +131,10 @@ public class GLDrawableHelper {
   /**
    * Issues {@link javax.media.opengl.GLEventListener#dispose(javax.media.opengl.GLAutoDrawable)}
    * to all listeners.
+   * <p>
+   * Please consider using {@link #disposeGL(GLAutoDrawable, GLDrawable, GLContext, Runnable)}
+   * for correctness!
+   * </p>
    * @param drawable
    */
   public final void dispose(GLAutoDrawable drawable) {
@@ -137,7 +144,7 @@ public class GLDrawableHelper {
         }
     }
   }
-
+  
   private boolean init(GLEventListener l, GLAutoDrawable drawable, boolean sendReshape) {
       if(listenersToBeInit.remove(l)) {
           l.init(drawable);
@@ -307,6 +314,8 @@ public class GLDrawableHelper {
    *          ie. {@link Animator#getThread()}.
    * @deprecated this is an experimental feature, 
    *             intended for measuring performance in regards to GL context switch
+   *             and only being used if {@link #PERF_STATS} is enabled
+   *             by defining property <code>jogl.debug.GLDrawable.PerfStats</code>.
    */
   public final void setSkipContextReleaseThread(Thread t) {
     skipContextReleaseThread = t;
@@ -318,7 +327,7 @@ public class GLDrawableHelper {
   public final Thread getSkipContextReleaseThread() {
     return skipContextReleaseThread;
   }
-
+  
   private static final ThreadLocal<Runnable> perThreadInitAction = new ThreadLocal<Runnable>();
 
   /** Principal helper method which runs a Runnable with the context
@@ -326,10 +335,11 @@ public class GLDrawableHelper {
       desired goal is to be able to implement GLAutoDrawable's in terms of
       the GLContext's public APIs, and putting it into a separate
       class helps ensure that we don't inadvertently use private
-      methods of the GLContext or its implementing classes.<br>
-   * <br>
-   * Remark: In case this method is called to dispose the GLDrawable/GLAutoDrawable,
-   * <code>initAction</code> shall be <code>null</code> to mark this cause.<br>
+      methods of the GLContext or its implementing classes.
+      <p>
+      Note: Locking of the surface is implicit done by {@link GLContext#makeCurrent()},
+      where unlocking is performed by the latter {@link GLContext#release()}.
+      </p>
    *
    * @param drawable
    * @param context
@@ -348,13 +358,112 @@ public class GLDrawableHelper {
         return;
     }
 
-    if(null==initAction) {
-        // disposal case
-        if(!context.isCreated()) {
-            throw new GLException(Thread.currentThread().getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context is not created: "+context);
-        }
+    if(PERF_STATS) {
+        invokeGLImplStats(drawable, context, runnable, initAction, null);    
+    } else {
+        invokeGLImpl(drawable, context, runnable, initAction, null);
     }
+  }
 
+  /** 
+   * Principal helper method which runs {@link #dispose(GLAutoDrawable)} with the context
+   * made current and destroys the context afterwards while holding the lock.  
+   * 
+   * @param autoDrawable
+   * @param drawable
+   * @param context
+   * @param postAction
+   */
+  public final void disposeGL(GLAutoDrawable autoDrawable,
+                              GLDrawable drawable,
+                              GLContext context,
+                              Runnable  postAction) {
+    if(PERF_STATS) {
+        invokeGLImplStats(drawable, context, null, null, autoDrawable);    
+    } else {
+        invokeGLImpl(drawable, context, null, null, autoDrawable);
+    }
+    if(null != postAction) {
+        postAction.run();
+    }
+  }
+  
+  private final void invokeGLImpl(GLDrawable drawable,
+                                  GLContext context,
+                                  Runnable  runnable,
+                                  Runnable  initAction,
+                                  GLAutoDrawable disposeAutoDrawable) {
+    final Thread currentThread = Thread.currentThread();
+    
+    final boolean isDisposeAction = null==initAction ;
+        
+    // Support for recursive makeCurrent() calls as well as calling
+    // other drawables' display() methods from within another one's
+    GLContext lastContext = GLContext.getCurrent();
+    Runnable  lastInitAction = null;
+    if (lastContext != null) {
+        if (lastContext == context) {
+            lastContext = null; // utilize recursive locking
+        } else {
+            lastInitAction = perThreadInitAction.get();
+            lastContext.release();
+        }
+    }
+    int res = GLContext.CONTEXT_NOT_CURRENT;
+  
+    try {
+      res = context.makeCurrent();
+      if (res != GLContext.CONTEXT_NOT_CURRENT) {
+        if(!isDisposeAction) {
+            perThreadInitAction.set(initAction);
+            if (res == GLContext.CONTEXT_CURRENT_NEW) {
+              if (DEBUG) {
+                System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction");
+              }
+              initAction.run();
+            }
+            runnable.run();
+            if (autoSwapBufferMode) {
+                drawable.swapBuffers();
+            }
+        } else {
+            if(res == GLContext.CONTEXT_CURRENT_NEW) {
+                throw new GLException(currentThread.getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context was not created (new ctx): "+context);
+            }
+            if(listeners.size()>0) {
+                dispose(disposeAutoDrawable);
+            }
+        }
+      }
+    } finally {
+      try {
+          if(isDisposeAction) {
+              context.destroy();
+          } else if( res != GLContext.CONTEXT_NOT_CURRENT ) {
+              context.release();
+          }
+      } catch (Exception e) {
+          System.err.println("Catched: "+e.getMessage());
+          e.printStackTrace();
+      }
+      if (lastContext != null) {
+        final int res2 = lastContext.makeCurrent();
+        if (null != lastInitAction && res2 == GLContext.CONTEXT_CURRENT_NEW) {
+          lastInitAction.run();
+        }
+      }
+    }
+  }
+  
+  private final void invokeGLImplStats(GLDrawable drawable,
+                                       GLContext context,
+                                       Runnable  runnable,
+                                       Runnable  initAction,
+                                       GLAutoDrawable disposeAutoDrawable) {
+    final Thread currentThread = Thread.currentThread();
+    
+    final boolean isDisposeAction = null==initAction ;
+    
     // Support for recursive makeCurrent() calls as well as calling
     // other drawables' display() methods from within another one's
     int res = GLContext.CONTEXT_NOT_CURRENT;
@@ -362,7 +471,9 @@ public class GLDrawableHelper {
     Runnable  lastInitAction = null;
     if (lastContext != null) {
         if (lastContext == context) {
-            res = GLContext.CONTEXT_CURRENT;
+            if( currentThread == skipContextReleaseThread ) {
+                res = GLContext.CONTEXT_CURRENT;
+            } // else: utilize recursive locking
             lastContext = null;
         } else {
             lastInitAction = perThreadInitAction.get();
@@ -370,20 +481,21 @@ public class GLDrawableHelper {
         }
     }
   
-    /**
     long t0 = System.currentTimeMillis();
-    long td1 = 0; // makeCurrent
+    long tdA = 0; // makeCurrent
     long tdR = 0; // render time
-    long td2 = 0; // swapBuffers
-    long td3 = 0; // release
-    boolean scr = true; */
-    
+    long tdS = 0; // swapBuffers
+    long tdX = 0; // release
+    boolean ctxClaimed = false;
+    boolean ctxReleased = false;
+    boolean ctxDestroyed = false;    
     try {
       if (res == GLContext.CONTEXT_NOT_CURRENT) {
           res = context.makeCurrent();
+          ctxClaimed = true;
       }
       if (res != GLContext.CONTEXT_NOT_CURRENT) {
-        if(null!=initAction) {
+        if(!isDisposeAction) {
             perThreadInitAction.set(initAction);
             if (res == GLContext.CONTEXT_CURRENT_NEW) {
               if (DEBUG) {
@@ -391,41 +503,50 @@ public class GLDrawableHelper {
               }
               initAction.run();
             }
-        }
-        // tdR = System.currentTimeMillis();        
-        // td1 = tdR - t0; // makeCurrent
-        if(null!=runnable) {
+            tdR = System.currentTimeMillis();        
+            tdA = tdR - t0; // makeCurrent
             runnable.run();
-            // td2 = System.currentTimeMillis();
-            // tdR = td2 - tdR; // render time
-            if (autoSwapBufferMode && null != initAction) {
-              if (drawable != null) {
+            tdS = System.currentTimeMillis();
+            tdR = tdS - tdR; // render time
+            if (autoSwapBufferMode) {
                 drawable.swapBuffers();
-                // td3 = System.currentTimeMillis();
-                // td2 = td3 - td2; // swapBuffers
-              }
+                tdX = System.currentTimeMillis();
+                tdS = tdX - tdS; // swapBuffers
+            }
+        } else {
+            if(res == GLContext.CONTEXT_CURRENT_NEW) {
+                throw new GLException(currentThread.getName()+" GLDrawableHelper " + this + ".invokeGL(): Dispose case (no init action given): Native context was not created (new ctx): "+context);
+            }
+            if(listeners.size()>0) {
+                dispose(disposeAutoDrawable);
             }
         }
       }
     } finally {
-      if(res != GLContext.CONTEXT_NOT_CURRENT &&
-         (null == skipContextReleaseThread || Thread.currentThread()!=skipContextReleaseThread) ) {
-          try {
+      try {
+          if(isDisposeAction) {
+              context.destroy();
+              ctxDestroyed = true;
+          } else if( res != GLContext.CONTEXT_NOT_CURRENT &&
+                     (null == skipContextReleaseThread || currentThread != skipContextReleaseThread) ) {
               context.release();
-              // scr = false;
-          } catch (Exception e) {
+              ctxReleased = true;
           }
+      } catch (Exception e) {
+          System.err.println("Catched: "+e.getMessage());
+          e.printStackTrace();
       }
-      // td3 = System.currentTimeMillis() - td3; // release
+
+      tdX = System.currentTimeMillis() - tdX; // release / destroy
       if (lastContext != null) {
-        int res2 = lastContext.makeCurrent();
+        final int res2 = lastContext.makeCurrent();
         if (null != lastInitAction && res2 == GLContext.CONTEXT_CURRENT_NEW) {
           lastInitAction.run();
         }
       }
     }
-    // long td0 = System.currentTimeMillis() - t0;
-    // System.err.println("td0 "+td0+"ms, fps "+(1.0/(td0/1000.0))+", td-makeCurrent: "+td1+"ms, td-render "+tdR+"ms, td-swap "+td2+"ms, td-release "+td3+"ms, skip ctx release: "+scr);
+    long td = System.currentTimeMillis() - t0;
+    System.err.println("td0 "+td+"ms, fps "+(1.0/(td/1000.0))+", td-makeCurrent: "+tdA+"ms, td-render "+tdR+"ms, td-swap "+tdS+"ms, td-release "+tdX+"ms, ctx claimed: "+ctxClaimed+", ctx release: "+ctxReleased+", ctx destroyed "+ctxDestroyed);
   }
-
+    
 }
diff --git a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java
index b9c216e..36f17e5 100644
--- a/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java
+++ b/src/jogl/classes/jogamp/opengl/GLDrawableImpl.java
@@ -148,7 +148,7 @@ public abstract class GLDrawableImpl implements GLDrawable {
   public final synchronized void setRealized(boolean realizedArg) {
     if ( realized != realizedArg ) {
         if(DEBUG) {
-            System.err.println("setRealized: "+getClass().getName()+" "+realized+" -> "+realizedArg);
+            System.err.println(getThreadName() + ": setRealized: "+getClass().getSimpleName()+" "+realized+" -> "+realizedArg);
         }
         realized = realizedArg;
         AbstractGraphicsDevice aDevice = surface.getGraphicsConfiguration().getScreen().getDevice();
@@ -174,7 +174,7 @@ public abstract class GLDrawableImpl implements GLDrawable {
             }
         }
     } else if(DEBUG) {
-        System.err.println("setRealized: "+getClass().getName()+" "+this.realized+" == "+realizedArg);
+        System.err.println(getThreadName() + ": setRealized: "+getClass().getName()+" "+this.realized+" == "+realizedArg);
     }
   }
   protected abstract void setRealizedImpl();
@@ -210,6 +210,10 @@ public abstract class GLDrawableImpl implements GLDrawable {
                 ",\n\tWindow    "+getNativeSurface()+"]";
   }
 
+  protected static String getThreadName() {
+    return Thread.currentThread().getName();
+  }
+  
   protected GLDrawableFactory factory;
   protected NativeSurface surface;
   protected GLCapabilitiesImmutable requestedCapabilities;
diff --git a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java
index 4334841..4c82fc2 100644
--- a/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/GLDynamicLibraryBundleInfo.java
@@ -28,27 +28,25 @@
  
 package jogamp.opengl;
 
+import com.jogamp.common.os.DynamicLibraryBundle;
 import com.jogamp.common.os.DynamicLibraryBundleInfo;
-import java.util.*;
+import com.jogamp.common.util.RunnableExecutor;
 
 public abstract class GLDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo {
-    static List<String> glueLibNamesPreload;
-    static {
-        glueLibNamesPreload = new ArrayList<String>();
-        glueLibNamesPreload.add("nativewindow_x11");
-    }
-
     protected GLDynamicLibraryBundleInfo() {
     }
 
     /** default **/
+    @Override
     public boolean shallLinkGlobal() { return false; }
 
     /** default **/
+    @Override
     public boolean shallLookupGlobal() { return false; }
 
-    public static List<String> getGlueLibNamesPreload() {
-        return glueLibNamesPreload;
-    }
+    @Override
+    public RunnableExecutor getLibLoaderExecutor() {
+        return DynamicLibraryBundle.getDefaultRunnableExecutor();
+    }    
 }
 
diff --git a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java
index 6e2b7b7..d7958c7 100644
--- a/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java
+++ b/src/jogl/classes/jogamp/opengl/GLGraphicsConfigurationUtil.java
@@ -40,9 +40,9 @@ public class GLGraphicsConfigurationUtil {
     public static final int PBUFFER_BIT = 1 << 2;
     public static final int ALL_BITS    = WINDOW_BIT | BITMAP_BIT | PBUFFER_BIT ;
 
-    public static final StringBuffer winAttributeBits2String(StringBuffer sb, int winattrbits) {
+    public static final StringBuilder winAttributeBits2String(StringBuilder sb, int winattrbits) {
         if(null==sb) {
-            sb = new StringBuffer();
+            sb = new StringBuilder();
         }
         boolean seperator = false;
         if( 0 != ( WINDOW_BIT & winattrbits )  )  {
diff --git a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java
index e785d57..10d5a3f 100644
--- a/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java
+++ b/src/jogl/classes/jogamp/opengl/GLPbufferImpl.java
@@ -42,6 +42,8 @@ package jogamp.opengl;
 
 import com.jogamp.common.util.locks.LockFactory;
 import com.jogamp.common.util.locks.RecursiveLock;
+
+import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.NativeSurface;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLAnimatorControl;
@@ -97,26 +99,25 @@ public class GLPbufferImpl implements GLPbuffer {
     return true;
   }
 
-  class DisposeAction implements Runnable {
-    public void run() {
-        // Lock: Covered by DestroyAction ..
-        drawableHelper.dispose(GLPbufferImpl.this);
-    }
-  }
-  DisposeAction disposeAction = new DisposeAction();
-
   public void destroy() {
     if(pbufferDrawable.isRealized()) {
+        final AbstractGraphicsDevice adevice = pbufferDrawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice();
+        
         if (null != context && context.isCreated()) {
             try {
-                drawableHelper.invokeGL(pbufferDrawable, context, disposeAction, null);
+                drawableHelper.disposeGL(GLPbufferImpl.this, pbufferDrawable, context, null);
             } catch (GLException gle) {
                 gle.printStackTrace();
             }
-            context.destroy();
+            context = null;
             // drawableHelper.reset();
         }
         pbufferDrawable.destroy();
+        pbufferDrawable = null;
+        
+        if(null != adevice) {
+            adevice.close();
+        }
     }
   }
 
diff --git a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
index ac9655f..f7d59e1 100644
--- a/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
+++ b/src/jogl/classes/jogamp/opengl/GLWorkerThread.java
@@ -40,8 +40,10 @@
 package jogamp.opengl;
 
 import java.lang.reflect.InvocationTargetException;
-import java.util.*;
-import javax.media.opengl.*;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.media.opengl.GLContext;
 
 /** Singleton thread upon which all OpenGL work is performed by
     default. Unfortunately many vendors' OpenGL drivers are not really
@@ -64,7 +66,7 @@ public class GLWorkerThread {
   // The Runnable to execute immediately on the worker thread
   private static volatile Runnable work;
   // Queue of Runnables to be asynchronously invoked
-  private static List queue = new LinkedList();
+  private static List<Runnable> queue = new ArrayList<Runnable>();
   
   /** Should only be called by Threading class if creation of the
       GLWorkerThread was requested via the opengl.1thread system
@@ -77,7 +79,7 @@ public class GLWorkerThread {
         if (!started) {
           lock = new Object();
           thread = new Thread(new WorkerRunnable(),
-                              "JOGL GLWorkerThread");
+                              "JOGL-GLWorkerThread-");
           thread.setDaemon(true);
           started = true;
           synchronized (lock) {
@@ -141,16 +143,25 @@ public class GLWorkerThread {
           */
 
         } else {
-          throw new RuntimeException("Should not start GLWorkerThread twice");
+          throw new RuntimeException(getThreadName()+": Should not start GLWorkerThread twice");
         }
       }
     }
   }
 
+  public static void invoke(boolean wait, Runnable runnable) 
+      throws InvocationTargetException, InterruptedException {
+      if(wait) {
+          invokeAndWait(runnable);
+      } else {
+          invokeLater(runnable);
+      }
+  }
+  
   public static void invokeAndWait(Runnable runnable)
     throws InvocationTargetException, InterruptedException {
     if (!started) {
-      throw new RuntimeException("May not invokeAndWait on worker thread without starting it first");
+      throw new RuntimeException(getThreadName()+": May not invokeAndWait on worker thread without starting it first");
     }
 
     Object lockTemp = lock;
@@ -177,7 +188,7 @@ public class GLWorkerThread {
 
   public static void invokeLater(Runnable runnable) {
     if (!started) {
-      throw new RuntimeException("May not invokeLater on worker thread without starting it first");
+      throw new RuntimeException(getThreadName()+": May not invokeLater on worker thread without starting it first");
     }
 
     Object lockTemp = lock;
@@ -208,6 +219,10 @@ public class GLWorkerThread {
     return (Thread.currentThread() == thread);
   }
 
+  protected static String getThreadName() {
+    return Thread.currentThread().getName();
+  }
+  
   static class WorkerRunnable implements Runnable {
     public void run() {
       // Notify starting thread that we're ready
@@ -252,10 +267,10 @@ public class GLWorkerThread {
 
           while (!queue.isEmpty()) {
             try {
-              Runnable curAsync = (Runnable) queue.remove(0);
+              Runnable curAsync = queue.remove(0);
               curAsync.run();
             } catch (Throwable t) {
-              System.err.println("Exception occurred on JOGL OpenGL worker thread:");
+              System.err.println(getThreadName()+": Exception occurred on JOGL OpenGL worker thread:");
               t.printStackTrace();
             }
           }
diff --git a/src/jogl/classes/jogamp/opengl/MemoryObject.java b/src/jogl/classes/jogamp/opengl/MemoryObject.java
index 8b2cf0c..2927007 100644
--- a/src/jogl/classes/jogamp/opengl/MemoryObject.java
+++ b/src/jogl/classes/jogamp/opengl/MemoryObject.java
@@ -110,8 +110,8 @@ public class MemoryObject {
      * @param obj0 the MemoryObject
      * @return either the already mapped MemoryObject - not changing the map, or the newly mapped one.
      */
-    public static MemoryObject getOrAddSafe(HashMap/*<MemoryObject,MemoryObject>*/ map, MemoryObject obj0) {
-        MemoryObject obj1 = (MemoryObject) map.get(obj0); // get identity (fast)
+    public static MemoryObject getOrAddSafe(HashMap<MemoryObject,MemoryObject> map, MemoryObject obj0) {
+        MemoryObject obj1 = map.get(obj0); // get identity (fast)
         if(null == obj1) {
             map.put(obj0, obj0);
             obj1 = obj0;
diff --git a/src/jogl/classes/jogamp/opengl/ProjectFloat.java b/src/jogl/classes/jogamp/opengl/ProjectFloat.java
index 1c69fa3..bce3f3c 100644
--- a/src/jogl/classes/jogamp/opengl/ProjectFloat.java
+++ b/src/jogl/classes/jogamp/opengl/ProjectFloat.java
@@ -79,6 +79,7 @@
 
 /*
  * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2011 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -114,36 +115,28 @@
  */
 package jogamp.opengl;
 
-import java.nio.*;
+import java.nio.Buffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
 
-import javax.media.opengl.*;
 import javax.media.opengl.fixedfunc.GLMatrixFunc;
+
 import com.jogamp.common.nio.Buffers;
+import com.jogamp.opengl.FloatUtil;
 
 /**
  * ProjectFloat.java
- * <p/>
- * <p/>
+ * <p>
  * Created 11-jan-2004
+ * </p>
  * 
  * @author Erik Duijs
  * @author Kenneth Russell
+ * @author Sven Gothel
  */
 public class ProjectFloat {
-  private static final float[] IDENTITY_MATRIX =
-    new float[] {
-      1.0f, 0.0f, 0.0f, 0.0f,
-      0.0f, 1.0f, 0.0f, 0.0f,
-      0.0f, 0.0f, 1.0f, 0.0f,
-      0.0f, 0.0f, 0.0f, 1.0f };
-
-  private static final float[] ZERO_MATRIX =
-    new float[] {
-      0.0f, 0.0f, 0.0f, 0.0f,
-      0.0f, 0.0f, 0.0f, 0.0f,
-      0.0f, 0.0f, 0.0f, 0.0f,
-      0.0f, 0.0f, 0.0f, 0.0f };
-
+  public static final int getRequiredFloatBufferSize() { return 2*16+2*4+3*3; }
+  
   // Note that we have cloned parts of the implementation in order to
   // support incoming Buffers. The reason for this is to avoid loading
   // non-direct buffer subclasses unnecessarily, because doing so can
@@ -159,132 +152,63 @@ public class ProjectFloat {
   private final float[] in = new float[4];
   private final float[] out = new float[4];
 
-  private final float[] forward = new float[3];
-  private final float[] side = new float[3];
-  private final float[] up = new float[3];
-  
   // Buffer-based implementation
-  private FloatBuffer locbuf;
-  private final FloatBuffer matrixBuf;
-  private final FloatBuffer tempInvertMatrixBuf;
+  private FloatBuffer matrixBuf;
+  private FloatBuffer tempInvertMatrixBuf;
 
-  private final FloatBuffer inBuf;
-  private final FloatBuffer outBuf;
+  private FloatBuffer inBuf;
+  private FloatBuffer outBuf;
 
-  private final FloatBuffer forwardBuf;
-  private final FloatBuffer sideBuf;
-  private final FloatBuffer upBuf;
+  private FloatBuffer forwardBuf;
+  private FloatBuffer sideBuf;
+  private FloatBuffer upBuf;
 
   public ProjectFloat() {
-    // Use direct buffers to avoid loading indirect buffer
-    // implementations for applications trying to avoid doing so.
-    // Slice up one big buffer because some NIO implementations
-    // allocate a huge amount of memory to back even the smallest of
-    // buffers.
-    locbuf = Buffers.newDirectFloatBuffer(2*16+2*4+3*3);
-    int pos = 0;
-    int sz = 16;
-    matrixBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    tempInvertMatrixBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    sz = 4;
-    inBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    outBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    sz = 3;
-    forwardBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    sideBuf = slice(locbuf, pos, sz);
-    pos += sz;
-    upBuf = slice(locbuf, pos, sz);
-  }
-
-  public void destroy() {
-    if(locbuf!=null) {
-        locbuf.clear();
-        locbuf=null;
-    }
-  }
-
-  private static FloatBuffer slice(FloatBuffer buf, int pos, int len) {
-    buf.position(pos);
-    buf.limit(pos + len);
-    return buf.slice();
-  }
-
-  /**
-   * Make matrix an identity matrix
-   */
-  public static void gluMakeIdentityf(FloatBuffer m) {
-    int oldPos = m.position();
-    m.put(IDENTITY_MATRIX);
-    m.position(oldPos);
-  }
-
-  /**
-   * Make matrix an zero matrix
-   */
-  public static void gluMakeZero(FloatBuffer m) {
-    int oldPos = m.position();
-    m.put(ZERO_MATRIX);
-    m.position(oldPos);
+      this(false);
   }
-
-  /**
-   * Make matrix an identity matrix
-   */
-  public static void gluMakeIdentityf(float[] m, int offset) {
-    for (int i = 0; i < 16; i++) {
-      m[i+offset] = IDENTITY_MATRIX[i];
-    }
-  }
-
-  /**
-   * Make matrix an zero matrix
-   */
-  public static void gluMakeZero(float[] m, int offset) {
-    for (int i = 0; i < 16; i++) {
-      m[i+offset] = 0;
-    }
+  
+  public ProjectFloat(boolean useBackingArray) {
+      this(useBackingArray ? null : Buffers.newDirectByteBuffer(getRequiredFloatBufferSize() * Buffers.SIZEOF_FLOAT), 
+           useBackingArray ? new float[getRequiredFloatBufferSize()] : null, 
+           0);
   }
 
   /**
-   * Method __gluMultMatrixVecf
-   * 
-   * @param matrix
-   * @param in
-   * @param out
+   * @param floatBuffer source buffer, may be ByteBuffer (recommended) or FloatBuffer or <code>null</code>.
+   *                    If used, shall be ≥ {@link #getRequiredFloatBufferSize()} + floatOffset. 
+   *                    Buffer's position is ignored and floatPos is being used.
+   * @param floatArray source float array or <code>null</code>.
+   *                   If used, size shall be ≥ {@link #getRequiredFloatBufferSize()} + floatOffset.
+   * @param floatOffset Offset for either of the given sources (buffer or array)
    */
-  private void __gluMultMatrixVecf(float[] matrix, int matrix_offset, float[] in, float[] out) {
-    for (int i = 0; i < 4; i++) {
-      out[i] =
-        in[0] * matrix[0*4+i+matrix_offset] +
-        in[1] * matrix[1*4+i+matrix_offset] +
-        in[2] * matrix[2*4+i+matrix_offset] +
-        in[3] * matrix[3*4+i+matrix_offset];
-    }
+  public ProjectFloat(Buffer floatBuffer, float[] floatArray, int floatOffset) {    
+    int floatPos = floatOffset;
+    int floatSize = 16;
+    matrixBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    tempInvertMatrixBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    floatSize = 4;
+    inBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    outBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    floatSize = 3;
+    forwardBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    sideBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
+    floatPos += floatSize;
+    upBuf = Buffers.slice2Float(floatBuffer, floatArray, floatPos, floatSize);
   }
 
-  /**
-   * Method __gluMultMatrixVecf
-   * 
-   * @param matrix
-   * @param in
-   * @param out
-   */
-  private void __gluMultMatrixVecf(FloatBuffer matrix, FloatBuffer in, FloatBuffer out) {
-    int inPos = in.position();
-    int outPos = out.position();
-    int matrixPos = matrix.position();
-    for (int i = 0; i < 4; i++) {
-      out.put(i + outPos,
-              in.get(0+inPos) * matrix.get(0*4+i+matrixPos) +
-              in.get(1+inPos) * matrix.get(1*4+i+matrixPos) +
-              in.get(2+inPos) * matrix.get(2*4+i+matrixPos) +
-              in.get(3+inPos) * matrix.get(3*4+i+matrixPos));
-    }
+  public void destroy() {
+    matrixBuf = null;
+    tempInvertMatrixBuf = null;
+    inBuf = null;
+    outBuf = null;
+    forwardBuf = null;
+    sideBuf = null;
+    upBuf = null;
   }
 
   /**
@@ -304,7 +228,7 @@ public class ProjectFloat {
         temp[i][j] = src[i*4+j+srcOffset];
       }
     }
-    gluMakeIdentityf(inverse, inverseOffset);
+    FloatUtil.makeIdentityf(inverse, inverseOffset);
 
     for (i = 0; i < 4; i++) {
       //
@@ -378,7 +302,7 @@ public class ProjectFloat {
         temp.put(i*4+j, src.get(i*4+j + srcPos));
       }
     }
-    gluMakeIdentityf(inverse);
+    FloatUtil.makeIdentityf(inverse);
 
     for (i = 0; i < 4; i++) {
       //
@@ -434,122 +358,6 @@ public class ProjectFloat {
 
 
   /**
-   * @param a
-   * @param b
-   * @param r
-   */
-  private void gluMultMatricesf(float[] a, int a_offset, float[] b, int b_offset, float[] r) {
-    for (int i = 0; i < 4; i++) {
-      for (int j = 0; j < 4; j++) {
-        r[i*4+j] =
-          a[i*4+0+a_offset]*b[0*4+j+b_offset] +
-          a[i*4+1+a_offset]*b[1*4+j+b_offset] +
-          a[i*4+2+a_offset]*b[2*4+j+b_offset] +
-          a[i*4+3+a_offset]*b[3*4+j+b_offset];
-      }
-    }
-  }
-
-
-  /**
-   * @param a
-   * @param b
-   * @param r
-   */
-  public static void gluMultMatricesf(FloatBuffer a, FloatBuffer b, FloatBuffer r) {
-    int aPos = a.position();
-    int bPos = b.position();
-    int rPos = r.position();
-
-    for (int i = 0; i < 4; i++) {
-      for (int j = 0; j < 4; j++) {
-        r.put(i*4+j + rPos,
-          a.get(i*4+0+aPos)*b.get(0*4+j+bPos) +
-          a.get(i*4+1+aPos)*b.get(1*4+j+bPos) +
-          a.get(i*4+2+aPos)*b.get(2*4+j+bPos) +
-          a.get(i*4+3+aPos)*b.get(3*4+j+bPos));
-      }
-    }
-  }
-
-  /**
-   * Normalize vector
-   *
-   * @param v
-   */
-  public static void normalize(float[] v) {
-    float r;
-
-    r = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
-    if ( r == 0.0 || r == 1.0)
-      return;
-
-    r = 1.0f / r;
-
-    v[0] *= r;
-    v[1] *= r;
-    v[2] *= r;
-
-    return;
-  }
-
-  /**
-   * Normalize vector
-   *
-   * @param v
-   */
-  public static void normalize(FloatBuffer v) {
-    float r;
-
-    int vPos = v.position();
-
-    r = (float) Math.sqrt(v.get(0+vPos) * v.get(0+vPos) +
-                          v.get(1+vPos) * v.get(1+vPos) +
-                          v.get(2+vPos) * v.get(2+vPos));
-    if ( r == 0.0 || r == 1.0)
-      return;
-
-    r = 1.0f / r;
-
-    v.put(0+vPos, v.get(0+vPos) * r);
-    v.put(1+vPos, v.get(1+vPos) * r);
-    v.put(2+vPos, v.get(2+vPos) * r);
-
-    return;
-  }
-
-
-  /**
-   * Calculate cross-product
-   *
-   * @param v1
-   * @param v2
-   * @param result
-   */
-  private static void cross(float[] v1, float[] v2, float[] result) {
-    result[0] = v1[1] * v2[2] - v1[2] * v2[1];
-    result[1] = v1[2] * v2[0] - v1[0] * v2[2];
-    result[2] = v1[0] * v2[1] - v1[1] * v2[0];
-  }
-
-  /**
-   * Calculate cross-product
-   *
-   * @param v1
-   * @param v2
-   * @param result
-   */
-  private static void cross(FloatBuffer v1, FloatBuffer v2, FloatBuffer result) {
-    int v1Pos = v1.position();
-    int v2Pos = v2.position();
-    int rPos  = result.position();
-
-    result.put(0+rPos, v1.get(1+v1Pos) * v2.get(2+v2Pos) - v1.get(2+v1Pos) * v2.get(1+v2Pos));
-    result.put(1+rPos, v1.get(2+v1Pos) * v2.get(0+v2Pos) - v1.get(0+v1Pos) * v2.get(2+v2Pos));
-    result.put(2+rPos, v1.get(0+v1Pos) * v2.get(1+v2Pos) - v1.get(1+v1Pos) * v2.get(0+v2Pos));
-  }
-
-  /**
    * Method gluOrtho2D.
    * 
    * @param left
@@ -582,7 +390,7 @@ public class ProjectFloat {
 
     cotangent = (float) Math.cos(radians) / sine;
 
-    gluMakeIdentityf(matrixBuf);
+    FloatUtil.makeIdentityf(matrixBuf);
 
     matrixBuf.put(0 * 4 + 0, cotangent / aspect);
     matrixBuf.put(1 * 4 + 1, cotangent);
@@ -608,15 +416,9 @@ public class ProjectFloat {
    * @param upz
    */
   public void gluLookAt(GLMatrixFunc gl,
-                        float eyex,
-                        float eyey,
-                        float eyez,
-                        float centerx,
-                        float centery,
-                        float centerz,
-                        float upx,
-                        float upy,
-                        float upz) {
+                        float eyex, float eyey, float eyez,
+                        float centerx, float centery, float centerz,
+                        float upx, float upy, float upz) {
     FloatBuffer forward = this.forwardBuf;
     FloatBuffer side = this.sideBuf;
     FloatBuffer up = this.upBuf;
@@ -629,16 +431,16 @@ public class ProjectFloat {
     up.put(1, upy);
     up.put(2, upz);
 
-    normalize(forward);
+    FloatUtil.normalize(forward);
 
     /* Side = forward x up */
-    cross(forward, up, side);
-    normalize(side);
+    FloatUtil.cross(forward, up, side);
+    FloatUtil.normalize(side);
 
     /* Recompute up as: up = side x forward */
-    cross(side, forward, up);
+    FloatUtil.cross(side, forward, up);
 
-    gluMakeIdentityf(matrixBuf);
+    FloatUtil.makeIdentityf(matrixBuf);
     matrixBuf.put(0 * 4 + 0, side.get(0));
     matrixBuf.put(1 * 4 + 0, side.get(1));
     matrixBuf.put(2 * 4 + 0, side.get(2));
@@ -668,17 +470,11 @@ public class ProjectFloat {
    * 
    * @return
    */
-  public boolean gluProject(float objx,
-                            float objy,
-                            float objz,
-                            float[] modelMatrix,
-                            int modelMatrix_offset,
-                            float[] projMatrix,
-                            int projMatrix_offset,
-                            int[] viewport,
-                            int viewport_offset,
-                            float[] win_pos,
-                            int win_pos_offset ) {
+  public boolean gluProject(float objx, float objy, float objz,
+                            float[] modelMatrix, int modelMatrix_offset,
+                            float[] projMatrix, int projMatrix_offset,
+                            int[] viewport, int viewport_offset,
+                            float[] win_pos, int win_pos_offset ) {
 
     float[] in = this.in;
     float[] out = this.out;
@@ -688,11 +484,12 @@ public class ProjectFloat {
     in[2] = objz;
     in[3] = 1.0f;
 
-    __gluMultMatrixVecf(modelMatrix, modelMatrix_offset, in, out);
-    __gluMultMatrixVecf(projMatrix, projMatrix_offset, out, in);
+    FloatUtil.multMatrixVecf(modelMatrix, modelMatrix_offset, in, 0, out);
+    FloatUtil.multMatrixVecf(projMatrix, projMatrix_offset, out, 0, in);
 
-    if (in[3] == 0.0f)
+    if (in[3] == 0.0f) {
       return false;
+    }
 
     in[3] = (1.0f / in[3]) * 0.5f;
 
@@ -709,6 +506,42 @@ public class ProjectFloat {
     return true;
   }
 
+  public boolean gluProject(float objx, float objy, float objz,
+                            FloatBuffer modelMatrix,
+                            FloatBuffer projMatrix,
+                            int[] viewport, int viewport_offset,
+                            float[] win_pos, int win_pos_offset ) {
+
+    FloatBuffer in = this.inBuf;
+    FloatBuffer out = this.outBuf;
+
+    in.put(0, objx);
+    in.put(1, objy);
+    in.put(2, objz);
+    in.put(3, 1.0f);
+
+    FloatUtil.multMatrixVecf(modelMatrix, in, out);
+    FloatUtil.multMatrixVecf(projMatrix, out, in);
+
+    if (in.get(3) == 0.0f) {
+      return false;
+    }
+
+    in.put(3, (1.0f / in.get(3)) * 0.5f);
+
+    // Map x, y and z to range 0-1
+    in.put(0, in.get(0) * in.get(3) + 0.5f);
+    in.put(1, in.get(1) * in.get(3) + 0.5f);
+    in.put(2, in.get(2) * in.get(3) + 0.5f);
+
+    // Map x,y to viewport
+    win_pos[0+win_pos_offset] = in.get(0) * viewport[2+viewport_offset] + viewport[0+viewport_offset];
+    win_pos[1+win_pos_offset] = in.get(1) * viewport[3+viewport_offset] + viewport[1+viewport_offset];
+    win_pos[2+win_pos_offset] = in.get(2);
+
+    return true;
+  }
+  
   /**
    * Method gluProject
    * 
@@ -722,9 +555,7 @@ public class ProjectFloat {
    * 
    * @return
    */
-  public boolean gluProject(float objx,
-                            float objy,
-                            float objz,
+  public boolean gluProject(float objx, float objy, float objz,
                             FloatBuffer modelMatrix,
                             FloatBuffer projMatrix,
                             IntBuffer viewport,
@@ -738,11 +569,12 @@ public class ProjectFloat {
     in.put(2, objz);
     in.put(3, 1.0f);
 
-    __gluMultMatrixVecf(modelMatrix, in, out);
-    __gluMultMatrixVecf(projMatrix, out, in);
+    FloatUtil.multMatrixVecf(modelMatrix, in, out);
+    FloatUtil.multMatrixVecf(projMatrix, out, in);
 
-    if (in.get(3) == 0.0f)
+    if (in.get(3) == 0.0f) {
       return false;
+    }
 
     in.put(3, (1.0f / in.get(3)) * 0.5f);
 
@@ -775,24 +607,19 @@ public class ProjectFloat {
    * 
    * @return
    */
-  public boolean gluUnProject(float winx,
-                              float winy,
-                              float winz,
-                              float[] modelMatrix,
-                              int modelMatrix_offset,
-                              float[] projMatrix,
-                              int projMatrix_offset,
-                              int[] viewport,
-                              int viewport_offset,
-                              float[] obj_pos,
-                              int obj_pos_offset) {
+  public boolean gluUnProject(float winx, float winy, float winz,
+                              float[] modelMatrix, int modelMatrix_offset,
+                              float[] projMatrix, int projMatrix_offset,
+                              int[] viewport, int viewport_offset,
+                              float[] obj_pos, int obj_pos_offset) {
     float[] in = this.in;
     float[] out = this.out;
 
-    gluMultMatricesf(modelMatrix, modelMatrix_offset, projMatrix, projMatrix_offset, matrix);
+    FloatUtil.multMatrixf(modelMatrix, modelMatrix_offset, projMatrix, projMatrix_offset, matrix, 0);
 
-    if (!gluInvertMatrixf(matrix, 0, matrix, 0))
+    if (!gluInvertMatrixf(matrix, 0, matrix, 0)) {
       return false;
+    }
 
     in[0] = winx;
     in[1] = winy;
@@ -808,10 +635,11 @@ public class ProjectFloat {
     in[1] = in[1] * 2 - 1;
     in[2] = in[2] * 2 - 1;
 
-    __gluMultMatrixVecf(matrix, 0, in, out);
+    FloatUtil.multMatrixVecf(matrix, in, out);
 
-    if (out[3] == 0.0)
+    if (out[3] == 0.0) {
       return false;
+    }
 
     out[3] = 1.0f / out[3];
 
@@ -823,6 +651,49 @@ public class ProjectFloat {
   }
 
 
+  public boolean gluUnProject(float winx, float winy, float winz,
+                              FloatBuffer modelMatrix, 
+                              FloatBuffer projMatrix,
+                              int[] viewport, int viewport_offset,
+                              float[] obj_pos, int obj_pos_offset) {
+    FloatBuffer in = this.inBuf;
+    FloatBuffer out = this.outBuf;
+
+    FloatUtil.multMatrixf(modelMatrix, projMatrix, matrixBuf);
+
+    if (!gluInvertMatrixf(matrixBuf, matrixBuf)) {
+      return false;
+    }
+
+    in.put(0, winx);
+    in.put(1, winy);
+    in.put(2, winz);
+    in.put(3, 1.0f);
+
+    // Map x and y from window coordinates
+    in.put(0, (in.get(0) - viewport[0+viewport_offset]) / viewport[2+viewport_offset]);
+    in.put(1, (in.get(1) - viewport[1+viewport_offset]) / viewport[3+viewport_offset]);
+    
+    // Map to range -1 to 1
+    in.put(0, in.get(0) * 2 - 1);
+    in.put(1, in.get(1) * 2 - 1);
+    in.put(2, in.get(2) * 2 - 1);
+
+    FloatUtil.multMatrixVecf(matrixBuf, in, out);
+
+    if (out.get(3) == 0.0f) {
+      return false;
+    }
+
+    out.put(3, 1.0f / out.get(3));
+
+    obj_pos[0+obj_pos_offset] = out.get(0) * out.get(3);
+    obj_pos[1+obj_pos_offset] = out.get(1) * out.get(3);
+    obj_pos[2+obj_pos_offset] = out.get(2) * out.get(3);
+
+    return true;
+  }
+  
   /**
    * Method gluUnproject
    * 
@@ -836,20 +707,19 @@ public class ProjectFloat {
    * 
    * @return
    */
-  public boolean gluUnProject(float winx,
-                              float winy,
-                              float winz,
-                              FloatBuffer modelMatrix,
+  public boolean gluUnProject(float winx, float winy, float winz,
+                              FloatBuffer modelMatrix, 
                               FloatBuffer projMatrix,
                               IntBuffer viewport,
                               FloatBuffer obj_pos) {
     FloatBuffer in = this.inBuf;
     FloatBuffer out = this.outBuf;
 
-    gluMultMatricesf(modelMatrix, projMatrix, matrixBuf);
+    FloatUtil.multMatrixf(modelMatrix, projMatrix, matrixBuf);
 
-    if (!gluInvertMatrixf(matrixBuf, matrixBuf))
+    if (!gluInvertMatrixf(matrixBuf, matrixBuf)) {
       return false;
+    }
 
     in.put(0, winx);
     in.put(1, winy);
@@ -867,10 +737,11 @@ public class ProjectFloat {
     in.put(1, in.get(1) * 2 - 1);
     in.put(2, in.get(2) * 2 - 1);
 
-    __gluMultMatrixVecf(matrixBuf, in, out);
+    FloatUtil.multMatrixVecf(matrixBuf, in, out);
 
-    if (out.get(3) == 0.0f)
+    if (out.get(3) == 0.0f) {
       return false;
+    }
 
     out.put(3, 1.0f / out.get(3));
 
@@ -915,7 +786,7 @@ public class ProjectFloat {
     float[] in = this.in;
     float[] out = this.out;
 
-    gluMultMatricesf(modelMatrix, modelMatrix_offset, projMatrix, projMatrix_offset, matrix);
+    FloatUtil.multMatrixf(modelMatrix, modelMatrix_offset, projMatrix, projMatrix_offset, matrix, 0);
 
     if (!gluInvertMatrixf(matrix, 0, matrix, 0))
       return false;
@@ -935,7 +806,7 @@ public class ProjectFloat {
     in[1] = in[1] * 2 - 1;
     in[2] = in[2] * 2 - 1;
 
-    __gluMultMatrixVecf(matrix, 0, in, out);
+    FloatUtil.multMatrixVecf(matrix, in, out);
 
     if (out[3] == 0.0f)
       return false;
@@ -976,7 +847,7 @@ public class ProjectFloat {
     FloatBuffer in = this.inBuf;
     FloatBuffer out = this.outBuf;
 
-    gluMultMatricesf(modelMatrix, projMatrix, matrixBuf);
+    FloatUtil.multMatrixf(modelMatrix, projMatrix, matrixBuf);
 
     if (!gluInvertMatrixf(matrixBuf, matrixBuf))
       return false;
@@ -997,7 +868,7 @@ public class ProjectFloat {
     in.put(1, in.get(1) * 2 - 1);
     in.put(2, in.get(2) * 2 - 1);
 
-    __gluMultMatrixVecf(matrixBuf, in, out);
+    FloatUtil.multMatrixVecf(matrixBuf, in, out);
 
     if (out.get(3) == 0.0f)
       return false;
@@ -1065,4 +936,5 @@ public class ProjectFloat {
                     0);
     gl.glScalef(viewport[2+viewport_offset] / deltaX, viewport[3+viewport_offset] / deltaY, 1.0f);
   }
+
 }
diff --git a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java
index a33e03a..0528d30 100644
--- a/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java
+++ b/src/jogl/classes/jogamp/opengl/SharedResourceRunner.java
@@ -260,7 +260,9 @@ public class SharedResourceRunner implements Runnable {
                         try {
                             sr = impl.createSharedResource(initConnection);
                         } catch (Exception e) {
-                            e.printStackTrace();
+                            if(DEBUG) {
+                                e.printStackTrace();
+                            }
                         }
                         if (null != sr) {
                             impl.mapPut(initConnection, sr);
diff --git a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java
index 67a9501..61a4767 100644
--- a/src/jogl/classes/jogamp/opengl/ThreadingImpl.java
+++ b/src/jogl/classes/jogamp/opengl/ThreadingImpl.java
@@ -38,34 +38,46 @@ import java.lang.reflect.InvocationTargetException;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
-import com.jogamp.common.JogampRuntimeException;
-import com.jogamp.common.util.*;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
+import com.jogamp.common.JogampRuntimeException;
+import com.jogamp.common.util.ReflectionUtil;
+
 /** Implementation of the {@link javax.media.opengl.Threading} class. */
 
 public class ThreadingImpl {
-    public static final int AWT    = 1;
-    public static final int WORKER = 2;
+    public enum Mode {
+        MT(0), ST_AWT(1), ST_WORKER(2); 
+        
+        public final int id;
+
+        Mode(int id){
+            this.id = id;
+        }
+    }    
 
     protected static final boolean DEBUG = Debug.debug("Threading");
 
-    private static boolean singleThreaded = true;
-    private static int mode;
+    private static boolean singleThreaded;
+    private static Mode mode;
     private static boolean hasAWT;
     // We need to know whether we're running on X11 platforms to change
     // our behavior when the Java2D/JOGL bridge is active
     private static boolean _isX11;
 
-    private static final ThreadingPlugin threadingPlugin;
+    private static final ToolkitThreadingPlugin threadingPlugin;
   
     static {
-        Object threadingPluginTmp =
-            AccessController.doPrivileged(new PrivilegedAction() {
-                    public Object run() {
-                        String workaround = Debug.getProperty("jogl.1thread", true);
+        threadingPlugin =
+            AccessController.doPrivileged(new PrivilegedAction<ToolkitThreadingPlugin>() {
+                    public ToolkitThreadingPlugin run() {
+                        final String singleThreadProp;
+                        {
+                            final String w = Debug.getProperty("jogl.1thread", true);
+                            singleThreadProp = null != w ? w.toLowerCase() : null;
+                        }
                         ClassLoader cl = ThreadingImpl.class.getClassLoader();
                         // Default to using the AWT thread on all platforms except
                         // Windows. On OS X there is instability apparently due to
@@ -80,51 +92,53 @@ public class ThreadingImpl {
                         String osType = NativeWindowFactory.getNativeWindowType(false);
                         _isX11 = NativeWindowFactory.TYPE_X11.equals(osType);
 
-                        int defaultMode = ( hasAWT ? AWT : WORKER );
-
-                        mode = defaultMode;
-                        if (workaround != null) {
-                            workaround = workaround.toLowerCase();
-                            if (workaround.equals("true") ||
-                                workaround.equals("auto")) {
-                                // Nothing to do; singleThreaded and mode already set up
-                            } else if (workaround.equals("worker")) {
+                        // default setting
+                        singleThreaded = true;
+                        mode  = ( hasAWT ? Mode.ST_AWT : Mode.ST_WORKER );
+                        
+                        if (singleThreadProp != null) {
+                            if (singleThreadProp.equals("true") ||
+                                singleThreadProp.equals("auto")) {
                                 singleThreaded = true;
-                                mode = WORKER;
-                            } else if (hasAWT && workaround.equals("awt")) {
+                                mode  = ( hasAWT ? Mode.ST_AWT : Mode.ST_WORKER );
+                            } else if (singleThreadProp.equals("worker")) {
                                 singleThreaded = true;
-                                mode = AWT;
-                            } else {
+                                mode = Mode.ST_WORKER;
+                            } else if (hasAWT && singleThreadProp.equals("awt")) {
+                                singleThreaded = true;
+                                mode = Mode.ST_AWT;
+                            } else if (singleThreadProp.equals("false")) {
                                 singleThreaded = false;
+                                mode = Mode.MT;
+                            } else {
+                                throw new RuntimeException("Unsupported value for property jogl.1thread: "+singleThreadProp+", should be [true/auto, worker, awt or false]");
                             }
                         }
-                        printWorkaroundNotice();
-
-                        Object threadingPluginObj=null;
+                        
+                        ToolkitThreadingPlugin threadingPlugin=null;
                         if(hasAWT) {
                             // try to fetch the AWTThreadingPlugin
                             Exception error=null;
                             try {
-                                threadingPluginObj = ReflectionUtil.createInstance("jogamp.opengl.awt.AWTThreadingPlugin", cl);
+                                threadingPlugin = (ToolkitThreadingPlugin) ReflectionUtil.createInstance("jogamp.opengl.awt.AWTThreadingPlugin", cl);
                             } catch (JogampRuntimeException jre) { error = jre; }
-                            if(AWT == mode && null==threadingPluginObj) {                                
+                            if( Mode.ST_AWT == mode && null==threadingPlugin ) {
                                 throw new GLException("Mode is AWT, but class 'jogamp.opengl.awt.AWTThreadingPlugin' is not available", error);
                             }
                         }
-                        return threadingPluginObj;
+                        if(DEBUG) {
+                            System.err.println("Threading: jogl.1thread "+singleThreadProp+", singleThreaded "+singleThreaded+", hasAWT "+hasAWT+", mode "+mode+", plugin "+threadingPlugin);
+                        }
+                        return threadingPlugin;
                     }
                 });
-        threadingPlugin = (ThreadingPlugin) threadingPluginTmp;
-        if(DEBUG) {
-            System.err.println("Threading: hasAWT "+hasAWT+", mode "+((mode==AWT)?"AWT":"WORKER")+", plugin "+threadingPlugin);
-        }
     }
 
     /** No reason to ever instantiate this class */
     private ThreadingImpl() {}
 
     public static boolean isX11() { return _isX11; }
-    public static int getMode() { return mode; }
+    public static Mode getMode() { return mode; }
 
     /** If an implementation of the javax.media.opengl APIs offers a 
         multithreading option but the default behavior is single-threading, 
@@ -139,7 +153,7 @@ public class ThreadingImpl {
         once disabled, partly to discourage careless use of this
         method. This method should be called as early as possible in an
         application. */ 
-    public static void disableSingleThreading() {
+    public static final void disableSingleThreading() {
         singleThreaded = false;
         if (Debug.verbose()) {
             System.err.println("Application forced disabling of single-threading of javax.media.opengl implementation");
@@ -148,7 +162,7 @@ public class ThreadingImpl {
 
     /** Indicates whether OpenGL work is being automatically forced to a
         single thread in this implementation. */
-    public static boolean isSingleThreaded() {
+    public static final boolean isSingleThreaded() {
         return singleThreaded;
     }
 
@@ -156,24 +170,27 @@ public class ThreadingImpl {
         which this implementation of the javax.media.opengl APIs
         performs all of its OpenGL-related work. This method should only
         be called if the single-thread model is in effect. */
-    public static boolean isOpenGLThread() throws GLException {
-        if (!isSingleThreaded()) {
-            throw new GLException("Should only call this in single-threaded mode");
-        }
-
+    public static final boolean isOpenGLThread() throws GLException {
         if(null!=threadingPlugin) {
             return threadingPlugin.isOpenGLThread();
         }
 
         switch (mode) {
-            case AWT:
+            case ST_AWT:
                 throw new InternalError();
-            case WORKER:
+            case ST_WORKER:
                 return GLWorkerThread.isWorkerThread();
             default:
                 throw new InternalError("Illegal single-threading mode " + mode);
         }
     }
+    
+    public static final boolean isToolkitThread() throws GLException {
+        if(null!=threadingPlugin) {
+            return threadingPlugin.isToolkitThread();
+        }
+        return false;
+    }
 
     /** Executes the passed Runnable on the single thread used for all
         OpenGL work in this javax.media.opengl API implementation. It is
@@ -184,51 +201,30 @@ public class ThreadingImpl {
         false). It is up to the end user to check to see whether the
         current thread is the OpenGL thread and either execute the
         Runnable directly or perform the work inside it. */
-    public static void invokeOnOpenGLThread(Runnable r) throws GLException {
-        if (!isSingleThreaded()) {
-            throw new GLException ("Should only call this in single-threaded mode");
-        }
-
-        if (isOpenGLThread()) {
-            throw new GLException ("Should only call this from other threads than the OpenGL thread");
-        }    
-
+    public static final void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException {
         if(null!=threadingPlugin) {
-            threadingPlugin.invokeOnOpenGLThread(r);
+            threadingPlugin.invokeOnOpenGLThread(wait, r);
             return;
         }
 
         switch (mode) {
-            case AWT:
-                throw new InternalError();
-
-            case WORKER:
-                GLWorkerThread.start(); // singleton start via volatile-dbl-checked-locking
-                try {
-                    GLWorkerThread.invokeAndWait(r);
-                } catch (InvocationTargetException e) {
-                    throw new GLException(e.getTargetException());
-                } catch (InterruptedException e) {
-                    throw new GLException(e);
-                }
+            case ST_WORKER:
+                invokeOnWorkerThread(wait, r);
                 break;
 
             default:
                 throw new InternalError("Illegal single-threading mode " + mode);
         }
     }
-
-    /** This is a workaround for AWT-related deadlocks which only seem
-        to show up in the context of applets */
-    public static boolean isAWTMode() {
-        return (mode == AWT);
-    }
-
-    private static void printWorkaroundNotice() {
-        if (singleThreaded && Debug.verbose()) {
-            System.err.println("Using " +
-                               (mode == AWT ? "AWT" : "OpenGL worker") +
-                               " thread for performing OpenGL work in javax.media.opengl implementation");
-        }
+    
+    public static final void invokeOnWorkerThread(boolean wait, Runnable r) throws GLException {
+        GLWorkerThread.start(); // singleton start via volatile-dbl-checked-locking
+        try {
+            GLWorkerThread.invoke(wait, r);
+        } catch (InvocationTargetException e) {
+            throw new GLException(e.getTargetException());
+        } catch (InterruptedException e) {
+            throw new GLException(e);
+        }        
     }
 }
diff --git a/src/jogl/classes/jogamp/opengl/ThreadingPlugin.java b/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java
similarity index 87%
rename from src/jogl/classes/jogamp/opengl/ThreadingPlugin.java
rename to src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java
index 0b0748b..2297295 100644
--- a/src/jogl/classes/jogamp/opengl/ThreadingPlugin.java
+++ b/src/jogl/classes/jogamp/opengl/ToolkitThreadingPlugin.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2012 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -41,8 +42,12 @@ package jogamp.opengl;
 
 import javax.media.opengl.*;
 
-public interface ThreadingPlugin {
-  /** Indicates whether the current thread is the single thread on
+public interface ToolkitThreadingPlugin {
+  /** Indicates whether the current thread is the designated toolkit thread,
+      if such semantics exists. */
+  public boolean isToolkitThread() throws GLException;
+  
+  /** Indicates whether the current thread is the thread on
       which this implementation of the javax.media.opengl APIs
       performs all of its OpenGL-related work. This method should only
       be called if the single-thread model is in effect. */
@@ -57,6 +62,6 @@ public interface ThreadingPlugin {
       false). It is up to the end user to check to see whether the
       current thread is the OpenGL thread and either execute the
       Runnable directly or perform the work inside it. */
-  public void invokeOnOpenGLThread(Runnable r) throws GLException;
+  public void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException;
 }
 
diff --git a/src/jogl/classes/jogamp/opengl/android/av/AndroidGLMediaPlayerAPI14.java b/src/jogl/classes/jogamp/opengl/android/av/AndroidGLMediaPlayerAPI14.java
new file mode 100644
index 0000000..23f9161
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/android/av/AndroidGLMediaPlayerAPI14.java
@@ -0,0 +1,262 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package jogamp.opengl.android.av;
+
+import java.io.IOException;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GLES2;
+
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+import jogamp.common.os.android.StaticContext;
+import jogamp.opengl.util.av.GLMediaPlayerImpl;
+
+import android.graphics.SurfaceTexture;
+import android.graphics.SurfaceTexture.OnFrameAvailableListener;
+import android.media.MediaPlayer;
+import android.net.Uri;
+import android.view.Surface;
+
+/***
+ * Android implementation utilizes API level 14 (4.0.? ICS) features
+ * as listed below.
+ * <p>
+ * We utilize the {@link MediaPlayer} with direct to texture streaming.
+ * The MediaPlayer uses <code>libstagefright</code> to access the OpenMAX AL implementation
+ * for hardware decoding.
+ * </p>
+ * <ul>
+ *   <li>Android API Level 14: {@link MediaPlayer#setSurface(Surface)}</li>
+ *   <li>Android API Level 14: {@link Surface#Surface(android.graphics.SurfaceTexture)}</li>
+ * </ul>
+ */
+public class AndroidGLMediaPlayerAPI14 extends GLMediaPlayerImpl {
+    static final boolean available;
+    
+    static {
+        available = true; // default .. TODO: May restrict availability ? 
+    }
+    
+    public static final boolean isAvailable() { return available; }
+    
+    MediaPlayer mp;
+    volatile boolean updateSurface = false;
+    Object updateSurfaceLock = new Object();
+    TextureSequence.TextureFrame lastTexFrame = null;
+
+    /**
+    private static String toString(MediaPlayer m) {
+        if(null == m) return "<nil>";
+        return "MediaPlayer[playing "+m.isPlaying()+", pos "+m.getCurrentPosition()/1000.0f+"s, "+m.getVideoWidth()+"x"+m.getVideoHeight()+"]";
+    } */
+    
+    public AndroidGLMediaPlayerAPI14() {
+        super();
+        if(!available) {
+            throw new RuntimeException("AndroidGLMediaPlayerAPI14 not available");
+        }
+        this.setTextureTarget(GLES2.GL_TEXTURE_EXTERNAL_OES);
+        this.setTextureCount(1);
+        mp = new MediaPlayer();
+    }
+
+    @Override
+    protected boolean setPlaySpeedImpl(float rate) {
+        return false;
+    }
+
+    @Override
+    protected boolean startImpl() {
+        if(null != mp) {        
+            try {
+                mp.start();
+                return true;
+            } catch (IllegalStateException ise) {
+                if(DEBUG) {
+                    ise.printStackTrace();
+                }
+            }
+        }
+        return false;
+    }
+
+    @Override
+    protected boolean pauseImpl() {
+        if(null != mp) {
+            wakeUp(false);
+            try {
+                mp.pause();
+                return true;
+            } catch (IllegalStateException ise) {
+                if(DEBUG) {
+                    ise.printStackTrace();
+                }
+            }
+        }
+        return false;
+    }
+
+    @Override
+    protected boolean stopImpl() {
+        if(null != mp) {
+            wakeUp(false);
+            try {
+                mp.stop();
+                return true;
+            } catch (IllegalStateException ise) {
+                if(DEBUG) {
+                    ise.printStackTrace();
+                }
+            }
+        }
+        return false;
+    }
+    
+    @Override
+    protected int seekImpl(int msec) {
+        if(null != mp) {
+            mp.seekTo(msec);
+            return mp.getCurrentPosition();
+        }
+        return 0;
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame getLastTextureImpl() {
+        return lastTexFrame;
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) {
+        if(null != stex && null != mp) {
+            // Only block once, no while-loop. 
+            // This relaxes locking code of non crucial resources/events.
+            boolean update = updateSurface;
+            if(!update && blocking) {
+                synchronized(updateSurfaceLock) {
+                    if(!updateSurface) { // volatile OK.
+                        try {
+                            updateSurfaceLock.wait();
+                        } catch (InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                    updateSurface = false;
+                    update = true;
+                }
+            }
+            if(update) {
+                stex.updateTexImage();
+                // stex.getTransformMatrix(atex.getSTMatrix());
+                lastTexFrame=texFrames[0];
+            }
+            
+        }
+        return lastTexFrame;
+    }
+    
+    private void wakeUp(boolean newFrame) {
+        synchronized(updateSurfaceLock) {
+            if(newFrame) {
+                updateSurface = true;
+            }
+            updateSurfaceLock.notifyAll();
+        }
+    }
+    
+    @Override
+    protected int getCurrentPositionImpl() {
+        return null != mp ? mp.getCurrentPosition() : 0;
+    }
+
+    @Override
+    protected void destroyImpl(GL gl) {
+        if(null != mp) {
+            wakeUp(false);
+            mp.release();
+            mp = null;
+        }
+    }
+    
+    SurfaceTexture stex = null;
+    
+    @Override
+    protected void initGLStreamImpl(GL gl, int[] texNames) throws IOException {
+        if(null!=mp && null!=urlConn) {
+            try {
+                final Uri uri = Uri.parse(urlConn.getURL().toExternalForm());        
+                mp.setDataSource(StaticContext.getContext(), uri);
+            } catch (IllegalArgumentException e) {
+                throw new RuntimeException(e);
+            } catch (SecurityException e) {
+                throw new RuntimeException(e);
+            } catch (IllegalStateException e) {
+                throw new RuntimeException(e);
+            }
+            stex = new SurfaceTexture(texNames[0]); // only 1 texture
+            stex.setOnFrameAvailableListener(onFrameAvailableListener);
+            final Surface surf = new Surface(stex);
+            mp.setSurface(surf);
+            surf.release();
+            try {
+                mp.prepare();
+            } catch (IOException ioe) {
+                throw new IOException("MediaPlayer failed to process stream <"+urlConn.getURL().toExternalForm()+">: "+ioe.getMessage(), ioe);
+            }
+            updateAttributes(mp.getVideoWidth(), mp.getVideoHeight(), 
+                             0, 0, 0, 
+                             0f, 0, mp.getDuration(), 
+                             null, null);
+        }
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        lastTexFrame = new TextureSequence.TextureFrame( createTexImageImpl(gl, idx, tex, width, height, true) );
+        return lastTexFrame; 
+    }
+    
+    @Override
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        if(null != stex) {
+            stex.release();
+            stex = null;
+        }
+        lastTexFrame = null;
+        super.destroyTexImage(gl, imgTex);
+    }
+    
+    protected OnFrameAvailableListener onFrameAvailableListener = new OnFrameAvailableListener() {
+        @Override
+        public void onFrameAvailable(SurfaceTexture surfaceTexture) {
+            wakeUp(true);
+            AndroidGLMediaPlayerAPI14.this.newFrameAvailable();
+        }        
+    };        
+}
diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java
index dd493f5..983f111 100644
--- a/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java
+++ b/src/jogl/classes/jogamp/opengl/awt/AWTThreadingPlugin.java
@@ -40,29 +40,33 @@
 
 package jogamp.opengl.awt;
 
-import javax.media.opengl.*;
-
-import java.awt.event.*;
-
 import java.awt.EventQueue;
-import java.lang.reflect.InvocationTargetException;
 
-import jogamp.opengl.*;
+import javax.media.opengl.GLException;
 
-public class AWTThreadingPlugin implements ThreadingPlugin {
+import jogamp.common.awt.AWTEDTExecutor;
+import jogamp.opengl.GLWorkerThread;
+import jogamp.opengl.ThreadingImpl;
+import jogamp.opengl.ToolkitThreadingPlugin;
+
+public class AWTThreadingPlugin implements ToolkitThreadingPlugin {
 
   public AWTThreadingPlugin() {}
 
-  public boolean isOpenGLThread() throws GLException {
+  public final boolean isToolkitThread() throws GLException {
+      return EventQueue.isDispatchThread();
+  }
+  
+  public final boolean isOpenGLThread() throws GLException {
     switch (ThreadingImpl.getMode()) {
-      case ThreadingImpl.AWT:
+      case ST_AWT:
         // FIXME: See the FIXME below in 'invokeOnOpenGLThread'
         if (Java2D.isOGLPipelineActive() && !ThreadingImpl.isX11()) {
           return Java2D.isQueueFlusherThread();
         } else {
           return EventQueue.isDispatchThread();
         }
-      case ThreadingImpl.WORKER:
+      case ST_WORKER:
         if (Java2D.isOGLPipelineActive()) {
           // FIXME: ideally only the QFT would be considered to be the
           // "OpenGL thread", but we can not currently run all of
@@ -78,9 +82,9 @@ public class AWTThreadingPlugin implements ThreadingPlugin {
     }
   }
 
-  public void invokeOnOpenGLThread(Runnable r) throws GLException {
+  public final void invokeOnOpenGLThread(boolean wait, Runnable r) throws GLException {
     switch (ThreadingImpl.getMode()) {
-      case ThreadingImpl.AWT:
+      case ST_AWT:
         // FIXME: ideally should run all OpenGL work on the Java2D QFT
         // thread when it's enabled, but unfortunately there are
         // deadlock issues on X11 platforms when making our
@@ -89,28 +93,19 @@ public class AWTThreadingPlugin implements ThreadingPlugin {
         // implementation, which attempts to grab the AWT lock on the
         // QFT which is not allowed. For now, on X11 platforms,
         // continue to perform this work on the EDT.
-        if (Java2D.isOGLPipelineActive() && !ThreadingImpl.isX11()) {
-          Java2D.invokeWithOGLContextCurrent(null, r);
-        } else {
-          try {
-            EventQueue.invokeAndWait(r);
-          } catch (InvocationTargetException e) {
-            throw new GLException(e.getTargetException());
-          } catch (InterruptedException e) {
-            throw new GLException(e);
+        if (wait && Java2D.isOGLPipelineActive() && !ThreadingImpl.isX11()) {
+          if(wait) {
+              Java2D.invokeWithOGLContextCurrent(null, r);
+          } else {
+              
           }
+        } else {
+          AWTEDTExecutor.singleton.invoke(wait, r);
         }
         break;
 
-      case ThreadingImpl.WORKER:
-        GLWorkerThread.start(); // singleton start via volatile-dbl-checked-locking
-        try {
-          GLWorkerThread.invokeAndWait(r);
-        } catch (InvocationTargetException e) {
-          throw new GLException(e.getTargetException());
-        } catch (InterruptedException e) {
-          throw new GLException(e);
-        }
+      case ST_WORKER:
+        ThreadingImpl.invokeOnWorkerThread(wait, r);
         break;
 
       default:
diff --git a/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java b/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java
index 51143ab..e15e538 100644
--- a/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java
+++ b/src/jogl/classes/jogamp/opengl/awt/AWTUtil.java
@@ -37,17 +37,15 @@
 
 package jogamp.opengl.awt;
 
-import jogamp.nativewindow.jawt.*;
-
-import javax.media.opengl.*;
-
-import java.lang.reflect.*;
 import java.awt.GraphicsEnvironment;
+import java.lang.reflect.Method;
+
+import javax.media.nativewindow.NativeWindowFactory;
+import javax.media.opengl.GLException;
 
 public class AWTUtil {
   // See whether we're running in headless mode
   private static boolean headlessMode;
-  private static Class j2dClazz = null;
   private static Method isOGLPipelineActive = null;
   private static Method isQueueFlusherThread = null;
   private static boolean j2dOk = false;
@@ -57,7 +55,7 @@ public class AWTUtil {
     headlessMode = GraphicsEnvironment.isHeadless();
     if(!headlessMode) {
         try {
-            j2dClazz = Class.forName("jogamp.opengl.awt.Java2D");
+            final Class<?> j2dClazz = Class.forName("jogamp.opengl.awt.Java2D");
             isOGLPipelineActive = j2dClazz.getMethod("isOGLPipelineActive", (Class[])null);
             isQueueFlusherThread = j2dClazz.getMethod("isQueueFlusherThread", (Class[])null);
             j2dOk = true;
@@ -84,12 +82,12 @@ public class AWTUtil {
       try {
         if( !((Boolean)isOGLPipelineActive.invoke(null, (Object[])null)).booleanValue() ||
             !((Boolean)isQueueFlusherThread.invoke(null, (Object[])null)).booleanValue() ) {
-          JAWTUtil.lockToolkit();
+          NativeWindowFactory.getAWTToolkitLock().lock();
         }
       } catch (Exception e) { j2dOk=false; }
     } 
     if(!j2dOk) {
-      JAWTUtil.lockToolkit();
+      NativeWindowFactory.getAWTToolkitLock().lock();
     }
   }
 
@@ -107,12 +105,12 @@ public class AWTUtil {
           try {
             if( !((Boolean)isOGLPipelineActive.invoke(null, (Object[])null)).booleanValue() ||
                 !((Boolean)isQueueFlusherThread.invoke(null, (Object[])null)).booleanValue() ) {
-              JAWTUtil.unlockToolkit();
+              NativeWindowFactory.getAWTToolkitLock().unlock();
             }
           } catch (Exception e) { j2dOk=false; }
         } 
         if(!j2dOk) {
-          JAWTUtil.unlockToolkit();
+          NativeWindowFactory.getAWTToolkitLock().unlock();
         }
     }
   }
diff --git a/src/jogl/classes/jogamp/opengl/awt/Java2D.java b/src/jogl/classes/jogamp/opengl/awt/Java2D.java
index e240169..3dbfefb 100644
--- a/src/jogl/classes/jogamp/opengl/awt/Java2D.java
+++ b/src/jogl/classes/jogamp/opengl/awt/Java2D.java
@@ -39,23 +39,34 @@
 
 package jogamp.opengl.awt;
 
-import jogamp.opengl.*;
+import java.awt.Graphics;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.HeadlessException;
+import java.awt.Rectangle;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 
-import java.awt.*;
-import java.awt.image.*;
-import java.lang.reflect.*;
-import java.security.*;
+import javax.media.opengl.GL;
+import javax.media.opengl.GLContext;
+import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+import com.jogamp.common.os.Platform;
+
+import jogamp.opengl.Debug;
 
-import javax.media.opengl.*;
-import javax.media.nativewindow.*;
-import javax.media.nativewindow.awt.*;
 
 /** Defines integration with the Java2D OpenGL pipeline. This
     integration is only supported in 1.6 and is highly experimental. */
 
 public class Java2D {
   private static boolean DEBUG = Debug.debug("Java2D");
-  private static boolean VERBOSE = Debug.verbose();
   private static boolean isHeadless;
   private static boolean isOGLPipelineActive;
   private static Method invokeWithOGLContextCurrentMethod;
@@ -103,11 +114,12 @@ public class Java2D {
   private static Method destroyOGLContextMethod;
 
   static {
-    AccessController.doPrivileged(new PrivilegedAction() {
+    AccessController.doPrivileged(new PrivilegedAction<Object>() {
         public Object run() {
-          if (DEBUG && VERBOSE) {
+          if (DEBUG) {
             System.err.println("Checking for Java2D/OpenGL support");
           }
+          Throwable catched = null;
           try {
             isHeadless = true;
             // Figure out whether the default graphics configuration is an
@@ -119,15 +131,16 @@ public class Java2D {
             // If we get here, we aren't running in headless mode
             isHeadless = false;
             String name = cfg.getClass().getName();
-            if (DEBUG && VERBOSE) {
+            if (DEBUG) {
               System.err.println("Java2D support: default GraphicsConfiguration = " + name);
             }
-            isOGLPipelineActive = (name.startsWith("sun.java2d.opengl"));
+            isOGLPipelineActive = Platform.OS_TYPE != Platform.OSType.MACOS &&
+                                  (name.startsWith("sun.java2d.opengl"));
 
             if (isOGLPipelineActive) {
               try {
                 // Try to get methods we need to integrate
-                Class utils = Class.forName("sun.java2d.opengl.OGLUtilities");
+                Class<?> utils = Class.forName("sun.java2d.opengl.OGLUtilities");
                 invokeWithOGLContextCurrentMethod = utils.getDeclaredMethod("invokeWithOGLContextCurrent",
                                                                             new Class[] {
                                                                               Graphics.class,
@@ -176,7 +189,7 @@ public class Java2D {
                   getOGLSurfaceTypeMethod.setAccessible(true);
                 } catch (Exception e) {
                   fbObjectSupportInitialized = false;
-                  if (DEBUG && VERBOSE) {
+                  if (DEBUG) {
                     e.printStackTrace();
                     System.err.println("Info: Disabling Java2D/JOGL FBO support");
                   }
@@ -190,7 +203,7 @@ public class Java2D {
                                                                     });
                   getOGLTextureTypeMethod.setAccessible(true);
                 } catch (Exception e) {
-                  if (DEBUG && VERBOSE) {
+                  if (DEBUG) {
                     e.printStackTrace();
                     System.err.println("Info: GL_ARB_texture_rectangle FBO support disabled");
                   }
@@ -199,11 +212,11 @@ public class Java2D {
                 // Try to set up APIs for enabling the bridge on OS X,
                 // where it isn't possible to create generalized
                 // external GLDrawables
-                Class cglSurfaceData = null;
+                Class<?> cglSurfaceData = null;
                 try {
                   cglSurfaceData = Class.forName("sun.java2d.opengl.CGLSurfaceData");
                 } catch (Exception e) {
-                  if (DEBUG && VERBOSE) {
+                  if (DEBUG) {
                     e.printStackTrace();
                     System.err.println("Info: Unable to find class sun.java2d.opengl.CGLSurfaceData for OS X");
                   }
@@ -234,8 +247,8 @@ public class Java2D {
                   destroyOGLContextMethod.setAccessible(true);
                 }
               } catch (Exception e) {
-                if (DEBUG && VERBOSE) {
-                  e.printStackTrace();
+                catched = e;
+                if (DEBUG) {
                   System.err.println("Info: Disabling Java2D/JOGL integration");
                 }
                 isOGLPipelineActive = false;
@@ -243,9 +256,15 @@ public class Java2D {
             }
           } catch (HeadlessException e) {
             // The AWT is running in headless mode, so the Java 2D / JOGL bridge is clearly disabled
+          } catch (Error e) {
+            // issued on OSX Java7: java.lang.Error: Could not find class: sun.awt.HeadlessGraphicsEnvironment
+            catched = e;
           }
 
           if (DEBUG) {
+            if(null != catched) {
+                catched.printStackTrace();
+            }
             System.err.println("JOGL/Java2D integration " + (isOGLPipelineActive ? "enabled" : "disabled"));
           }
           return null;
@@ -513,15 +532,15 @@ public class Java2D {
   }
 
   private static int getOGLUtilitiesIntField(final String name) {
-    Integer i = (Integer) AccessController.doPrivileged(new PrivilegedAction() {
-        public Object run() {
+    Integer i = AccessController.doPrivileged(new PrivilegedAction<Integer>() {
+        public Integer run() {
           try {
-            Class utils = Class.forName("sun.java2d.opengl.OGLUtilities");
+            Class<?> utils = Class.forName("sun.java2d.opengl.OGLUtilities");
             Field f = utils.getField(name);
             f.setAccessible(true);
-            return f.get(null);
+            return (Integer) f.get(null);
           } catch (Exception e) {
-            if (DEBUG && VERBOSE) {
+            if (DEBUG) {
               e.printStackTrace();
             }
             return null;
@@ -530,7 +549,7 @@ public class Java2D {
       });
     if (i == null)
       return 0;
-    if (DEBUG && VERBOSE) {
+    if (DEBUG) {
       System.err.println("OGLUtilities." + name + " = " + i.intValue());
     }
     return i.intValue();
@@ -558,7 +577,7 @@ public class Java2D {
       }
       invokeWithOGLSharedContextCurrent(device.getDefaultConfiguration(), new Runnable() {
           public void run() {
-            j2dFBOShareContext = GLDrawableFactory.getFactory(GLProfile.getDefault(GLProfile.getDefaultDesktopDevice())).createExternalGLContext();
+            j2dFBOShareContext = GLDrawableFactory.getFactory(GLProfile.getDefault(GLProfile.getDefaultDevice())).createExternalGLContext();
           }
         });
       if (DEBUG) {
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java
similarity index 67%
copy from src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java
copy to src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java
index eb6c17c..cddd142 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/egl/DesktopES2DynamicLibraryBundleInfo.java
@@ -1,5 +1,5 @@
 /**
- * Copyright 2010 JogAmp Community. All rights reserved.
+ * Copyright 2012 JogAmp Community. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without modification, are
  * permitted provided that the following conditions are met:
@@ -26,16 +26,51 @@
  * or implied, of JogAmp Community.
  */
  
-package jogamp.opengl.x11.glx;
+package jogamp.opengl.egl;
 
-import jogamp.opengl.*;
 import java.util.*;
 
-public class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBundleInfo  {
-    protected X11GLXDynamicLibraryBundleInfo() {
+import jogamp.opengl.*;
+
+/**
+ * Implementation of the DynamicLookupHelper for Desktop ES2 (AMD, ..)
+ * where EGL and ES2 functions reside within the desktop OpenGL library.
+ */
+public class DesktopES2DynamicLibraryBundleInfo extends GLDynamicLibraryBundleInfo {
+    static List<String> glueLibNames;
+    static {
+        glueLibNames = new ArrayList<String>();
+        glueLibNames.add("jogl_mobile");
+    }
+
+    protected DesktopES2DynamicLibraryBundleInfo() {
         super();
     }
 
+    /** 
+     * Might be a desktop GL library, and might need to allow symbol access to subsequent libs.
+     * 
+     * This respects old DRI requirements:<br>
+     * <pre>
+     * http://dri.sourceforge.net/doc/DRIuserguide.html
+     * </pre>
+     */
+    public boolean shallLinkGlobal() { return true; }
+    
+    public final List<String> getToolGetProcAddressFuncNameList() {
+        List<String> res = new ArrayList<String>();
+        res.add("eglGetProcAddress");
+        return res;
+    }
+
+    public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
+        return EGL.eglGetProcAddress(toolGetProcAddressHandle, funcName);
+    }
+
+    public final boolean useToolGetProcAdressFirst(String funcName) {
+        return true;
+    }
+    
     public List<List<String>> getToolLibNames() {
         final List<List<String>> libsList = new ArrayList<List<String>>();
         final List<String> libsGL = new ArrayList<String>();
@@ -46,37 +81,26 @@ public class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBundl
         //    export LIBGL_DRIVERS_PATH=/usr/lib/fglrx/dri:/usr/lib32/fglrx/dri
         //
 
-        // this is the default lib name, according to the spec
+        // X11: this is the default lib name, according to the spec
         libsGL.add("libGL.so.1");
 
-        // try this one as well, if spec fails
+        // X11: try this one as well, if spec fails
         libsGL.add("libGL.so");
 
+        // Windows default
+        libsGL.add("OpenGL32");
+
+        // OSX (guess ES2 on OSX will never happen)
+        libsGL.add("/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib");
+        
         // last but not least .. the generic one
         libsGL.add("GL");
         
-        libsList.add(libsGL);        
+        libsList.add(libsGL);
         return libsList;
     }    
-    
-    /** 
-     * This respects old DRI requirements:<br>
-     * <pre>
-     * http://dri.sourceforge.net/doc/DRIuserguide.html
-     * </pre>
-     */
-    public boolean shallLinkGlobal() { return true; }
-
-    public final List<String> getToolGetProcAddressFuncNameList() {
-        List<String> res = new ArrayList<String>();
-        res.add("glXGetProcAddressARB");
-        res.add("glXGetProcAddress");
-        return res;
-    }
-
-    public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
-        return GLX.glXGetProcAddress(toolGetProcAddressHandle, funcName);
-    }
+        
+    public final List<String> getGlueLibNames() {
+        return glueLibNames;
+    }    
 }
-
-
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java
index 62ee20f..f5f9f62 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLContext.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2011 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -36,6 +37,7 @@
 package jogamp.opengl.egl;
 
 import java.nio.ByteBuffer;
+import java.nio.IntBuffer;
 import java.util.Map;
 
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
@@ -47,6 +49,8 @@ import javax.media.opengl.GLProfile;
 import jogamp.opengl.GLContextImpl;
 import jogamp.opengl.GLDrawableImpl;
 
+import com.jogamp.common.nio.Buffers;
+import com.jogamp.common.os.Platform;
 import com.jogamp.gluegen.runtime.ProcAddressTable;
 import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver;
 
@@ -67,6 +71,7 @@ public abstract class EGLContext extends GLContextImpl {
     protected void resetStates() {
         eglQueryStringInitialized = false;
         eglQueryStringAvailable = false;
+        eglExtProcAddressTable = null;
         // no inner state _eglExt = null;
         super.resetStates();
     }
@@ -108,7 +113,7 @@ public abstract class EGLContext extends GLContextImpl {
                                     drawableRead.getHandle(),
                                     contextHandle)) {
                 throw new GLException("Error making context 0x" +
-                                      Long.toHexString(contextHandle) + " current: error code " + EGL.eglGetError());
+                                      Long.toHexString(contextHandle) + " current: error code 0x" + Integer.toHexString(EGL.eglGetError()));
             }
         }
     }
@@ -119,14 +124,17 @@ public abstract class EGLContext extends GLContextImpl {
                               EGL.EGL_NO_SURFACE,
                               EGL.EGL_NO_CONTEXT)) {
             throw new GLException("Error freeing OpenGL context 0x" +
-                                  Long.toHexString(contextHandle) + ": error code " + EGL.eglGetError());
+                                  Long.toHexString(contextHandle) + ": error code 0x" + Integer.toHexString(EGL.eglGetError()));
       }
     }
 
     protected void destroyImpl() throws GLException {
       if (!EGL.eglDestroyContext(((EGLDrawable)drawable).getDisplay(), contextHandle)) {
-          throw new GLException("Error destroying OpenGL context 0x" +
-                                Long.toHexString(contextHandle) + ": error code " + EGL.eglGetError());
+          final int eglError = EGL.eglGetError();
+          if(EGL.EGL_SUCCESS != eglError) { /* oops, Mesa EGL impl. may return false, but has no EGL error */
+              throw new GLException("Error destroying OpenGL context 0x" +
+                                    Long.toHexString(contextHandle) + ": error code 0x" + Integer.toHexString(eglError));
+          }
       }
     }
 
@@ -155,7 +163,7 @@ public abstract class EGLContext extends GLContextImpl {
         try {
             // might be unavailable on EGL < 1.2
             if(!EGL.eglBindAPI(EGL.EGL_OPENGL_ES_API)) {
-                throw new GLException("eglBindAPI to ES failed , error 0x"+Integer.toHexString(EGL.eglGetError()));
+                throw new GLException("Catched: eglBindAPI to ES failed , error 0x"+Integer.toHexString(EGL.eglGetError()));
             }
         } catch (GLException glex) {
             if (DEBUG) {
@@ -170,24 +178,28 @@ public abstract class EGLContext extends GLContextImpl {
             }
         }
 
-        int[] contextAttrs = new int[] {
-                EGL.EGL_CONTEXT_CLIENT_VERSION, -1,
-                EGL.EGL_NONE
-        };
-        if (glProfile.usesNativeGLES2()) {
-            contextAttrs[1] = 2;
-        } else if (glProfile.usesNativeGLES1()) {
-            contextAttrs[1] = 1;
-        } else {
-            throw new GLException("Error creating OpenGL context - invalid GLProfile: "+glProfile);
+        final IntBuffer contextAttrsNIO; 
+        {
+            final int[] contextAttrs = new int[] {
+                    EGL.EGL_CONTEXT_CLIENT_VERSION, -1,
+                    EGL.EGL_NONE
+            };
+            if (glProfile.usesNativeGLES2()) {
+                contextAttrs[1] = 2;
+            } else if (glProfile.usesNativeGLES1()) {
+                contextAttrs[1] = 1;
+            } else {
+                throw new GLException("Error creating OpenGL context - invalid GLProfile: "+glProfile);
+            }
+            contextAttrsNIO = Buffers.newDirectIntBuffer(contextAttrs);
         }
-        contextHandle = EGL.eglCreateContext(eglDisplay, eglConfig, shareWithHandle, contextAttrs, 0);
+        contextHandle = EGL.eglCreateContext(eglDisplay, eglConfig, shareWithHandle, contextAttrsNIO);
         if (contextHandle == 0) {
             throw new GLException("Error creating OpenGL context: eglDisplay "+toHexString(eglDisplay)+
                                   ", eglConfig "+config+", "+glProfile+", shareWith "+toHexString(shareWithHandle)+", error "+toHexString(EGL.eglGetError()));
         }
         if (DEBUG) {
-            System.err.println(getThreadName() + ": !!! Created OpenGL context 0x" +
+            System.err.println(getThreadName() + ": Created OpenGL context 0x" +
                                Long.toHexString(contextHandle) + 
                                ",\n\twrite surface 0x" + Long.toHexString(drawable.getHandle()) +
                                ",\n\tread  surface 0x" + Long.toHexString(drawableRead.getHandle())+
@@ -201,10 +213,10 @@ public abstract class EGLContext extends GLContextImpl {
             throw new GLException("Error making context 0x" +
                                   Long.toHexString(contextHandle) + " current: error code " + EGL.eglGetError());
         }
-        int ctp = CTX_PROFILE_ES|CTX_OPTION_ANY;
+        int ctp = CTX_PROFILE_ES;
         int major;
         if(glProfile.usesNativeGLES2()) {
-            ctp |= CTX_PROFILE_ES2_COMPAT;
+            ctp |= CTX_IMPL_ES2_COMPAT;
             major = 2;
         } else {            
             major = 1;
@@ -218,7 +230,7 @@ public abstract class EGLContext extends GLContextImpl {
         final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
         final String key = "EGL-"+adevice.getUniqueID();
         if (DEBUG) {
-          System.err.println(getThreadName() + ": !!! Initializing EGLextension address table: "+key);
+          System.err.println(getThreadName() + ": Initializing EGLextension address table: "+key);
         }
         eglQueryStringInitialized = false;
         eglQueryStringAvailable = false;
@@ -230,26 +242,22 @@ public abstract class EGLContext extends GLContextImpl {
         if(null != table) {
             eglExtProcAddressTable = (EGLExtProcAddressTable) table;
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext EGL ProcAddressTable reusing key("+key+") -> "+table.hashCode());
+                System.err.println(getThreadName() + ": GLContext EGL ProcAddressTable reusing key("+key+") -> "+toHexString(table.hashCode()));
             }
         } else {
-            if (eglExtProcAddressTable == null) {
-              // FIXME: cache ProcAddressTables by capability bits so we can
-              // share them among contexts with the same capabilities
-              eglExtProcAddressTable = new EGLExtProcAddressTable(new GLProcAddressResolver());
-            }
+            eglExtProcAddressTable = new EGLExtProcAddressTable(new GLProcAddressResolver());
             resetProcAddressTable(getEGLExtProcAddressTable());
             synchronized(mappedContextTypeObjectLock) {
                 mappedGLXProcAddress.put(key, getEGLExtProcAddressTable());
                 if(DEBUG) {
-                    System.err.println(getThreadName() + ": !!! GLContext EGL ProcAddressTable mapping key("+key+") -> "+getEGLExtProcAddressTable().hashCode());
+                    System.err.println(getThreadName() + ": GLContext EGL ProcAddressTable mapping key("+key+") -> "+toHexString(getEGLExtProcAddressTable().hashCode()));
                 }
             }
         }
     }
   
-    protected final StringBuffer getPlatformExtensionsStringImpl() {
-        StringBuffer sb = new StringBuffer();        
+    protected final StringBuilder getPlatformExtensionsStringImpl() {
+        StringBuilder sb = new StringBuilder();        
         if (!eglQueryStringInitialized) {
           eglQueryStringAvailable =
             getDrawableImpl().getGLDynamicLookupHelper().dynamicLookupFunction("eglQueryString") != 0;
@@ -259,23 +267,39 @@ public abstract class EGLContext extends GLContextImpl {
             final String ret = EGL.eglQueryString(((EGLDrawable)drawable).getDisplay(), 
                                                   EGL.EGL_EXTENSIONS);
             if (DEBUG) {
-              System.err.println("!!! EGL extensions: " + ret);
+              System.err.println("EGL extensions: " + ret);
             }
             sb.append(ret);
         }
         return sb;
     }
 
-    protected void setSwapIntervalImpl(int interval) {
-        if (EGL.eglSwapInterval(((EGLDrawable)drawable).getDisplay(), interval)) {
-            currentSwapInterval = interval ;
+    @Override
+    protected boolean setSwapIntervalImpl(int interval) {
+        // FIXME !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+        // eglSwapInterval(..) issued:
+        //   Android 4.0.3 / Pandaboard ES / PowerVR SGX 540: crashes
+        // FIXME !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+        if( Platform.OSType.ANDROID == Platform.getOSType() && getGLRendererString(true).contains("powervr") ) {
+            if(DEBUG) {
+                System.err.println("Ignored: eglSwapInterval("+interval+") - cause: OS "+Platform.getOSType() + " / Renderer " + getGLRendererString(false));
+            }
+            return false;
         }
+        return EGL.eglSwapInterval(((EGLDrawable)drawable).getDisplay(), interval);
     }
 
     public abstract void bindPbufferToTexture();
 
     public abstract void releasePbufferFromTexture();
 
+    protected static String toHexString(int hex) {
+        return GLContext.toHexString(hex);
+    }
+    protected static String toHexString(long hex) {
+        return GLContext.toHexString(hex);
+    }
+    
     //----------------------------------------------------------------------
     // Currently unimplemented stuff
     //
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java
new file mode 100644
index 0000000..e09400c
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLDisplayUtil.java
@@ -0,0 +1,133 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package jogamp.opengl.egl;
+
+import java.nio.IntBuffer;
+
+import javax.media.nativewindow.NativeSurface;
+import javax.media.nativewindow.NativeWindowFactory;
+
+import jogamp.opengl.Debug;
+
+import com.jogamp.common.util.LongIntHashMap;
+
+/** 
+ * This implementation provides recursive calls to  
+ * {@link EGL#eglInitialize(long, IntBuffer, IntBuffer)} and {@link EGL#eglTerminate(long)},
+ * where <code>eglInitialize(..)</code> is issued only for the 1st call per <code>eglDisplay</code>
+ * and <code>eglTerminate(..)</code> is issued only for the last call.
+ * <p>
+ * This class is required, due to implementation bugs within EGL where {@link EGL#eglTerminate(long)}
+ * does not mark the resource for deletion when still in use, bug releases them immediatly.
+ * </p>
+ */
+public class EGLDisplayUtil {
+    protected static final boolean DEBUG = Debug.debug("EGL");
+    
+    static LongIntHashMap eglDisplayCounter;
+    
+    static {
+        eglDisplayCounter = new LongIntHashMap();
+        eglDisplayCounter.setKeyNotFoundValue(0);
+    }
+
+    public static long eglGetDisplay(long nativeDisplay_id)  {
+        final long eglDisplay = EGL.eglGetDisplay(nativeDisplay_id);
+        if(DEBUG) {
+            System.err.println("EGLDisplayUtil.eglGetDisplay(): eglDisplay("+EGLContext.toHexString(nativeDisplay_id)+"): "+
+                               EGLContext.toHexString(eglDisplay)+
+                               ", "+((EGL.EGL_NO_DISPLAY != eglDisplay)?"OK":"Failed"));
+        }
+        return eglDisplay;
+    }
+    
+    public static long eglGetDisplay(NativeSurface surface, boolean allowFallBackToDefault)  {
+        final long nDisplay;
+        if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) {
+            nDisplay = surface.getSurfaceHandle(); // don't even ask ..
+        } else {
+            nDisplay = surface.getDisplayHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY
+        }
+        long eglDisplay = EGLDisplayUtil.eglGetDisplay(nDisplay);
+        if (eglDisplay == EGL.EGL_NO_DISPLAY && nDisplay != EGL.EGL_DEFAULT_DISPLAY && allowFallBackToDefault) {
+            if(DEBUG) {
+                System.err.println("EGLDisplayUtil.eglGetDisplay(): Fall back to EGL_DEFAULT_DISPLAY");
+            }
+            eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
+        }
+        return eglDisplay;
+    }
+    
+    public static synchronized boolean eglInitialize(long eglDisplay, int[] major, int major_offset, int[] minor, int minor_offset)  {
+        final boolean res;    
+        final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init
+        if(1==refCnt) {
+            res = EGL.eglInitialize(eglDisplay, major, major_offset, minor, minor_offset);
+        } else {
+            res = true;
+        }
+        eglDisplayCounter.put(eglDisplay, refCnt);
+        if(DEBUG) {
+            System.err.println("EGL.eglInitialize(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res);
+        }
+        return res;
+    }
+    
+    public static synchronized boolean eglInitialize(long eglDisplay, IntBuffer major, IntBuffer minor)  {    
+        final boolean res;    
+        final int refCnt = eglDisplayCounter.get(eglDisplay) + 1; // 0 + 1 = 1 -> 1st init
+        if(1==refCnt) { // only initialize once
+            res = EGL.eglInitialize(eglDisplay, major, minor);
+        } else {
+            res = true;
+        }
+        eglDisplayCounter.put(eglDisplay, refCnt);
+        if(DEBUG) {
+            System.err.println("EGL.eglInitialize(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res);
+        }
+        return res;
+    }
+    
+    public static synchronized boolean eglTerminate(long eglDisplay)  {
+        final boolean res;    
+        final int refCnt = eglDisplayCounter.get(eglDisplay) - 1; // 1 - 1 = 0 -> final terminate
+        if(0==refCnt) { // no terminate if still in use or already terminated
+            res = EGL.eglTerminate(eglDisplay);
+        } else {
+            res = true;
+        }
+        if(0<=refCnt) { // no negative refCount
+            eglDisplayCounter.put(eglDisplay, refCnt);
+        }
+        if(DEBUG) {
+            System.err.println("EGL.eglTerminate(0x"+Long.toHexString(eglDisplay)+" ...): #"+refCnt+" = "+res);
+        }
+        return res;
+    }
+}
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java
index 14a0a40..b2119d7 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawable.java
@@ -40,9 +40,11 @@ import jogamp.opengl.GLDynamicLookupHelper;
 import jogamp.opengl.GLDrawableImpl;
 
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.egl.*;
+import javax.media.nativewindow.VisualIDHolder.VIDType;
 import javax.media.opengl.*;
 
+import com.jogamp.nativewindow.egl.*;
+
 public abstract class EGLDrawable extends GLDrawableImpl {
     protected boolean ownEGLDisplay = false; // for destruction
     protected boolean ownEGLSurface = false; // for destruction
@@ -84,26 +86,53 @@ public abstract class EGLDrawable extends GLDrawableImpl {
         }
 
         if(DEBUG) {
-            System.err.println("createSurface using eglDisplay "+toHexString(eglDisplay)+", "+eglConfig);
+            System.err.println(getThreadName() + ": createSurface using eglDisplay "+toHexString(eglDisplay)+", "+eglConfig);
         }
 
         eglSurface = createSurface(eglDisplay, eglConfig.getNativeConfig(), surface.getSurfaceHandle());
-        if (EGL.EGL_NO_SURFACE==eglSurface) {
-            throw new GLException("Creation of window surface failed: "+eglConfig+", error "+toHexString(EGL.eglGetError()));
+        int eglError0 = EGL.EGL_SUCCESS; 
+        if (EGL.EGL_NO_SURFACE == eglSurface) {
+            eglError0 = EGL.eglGetError();
+            if(EGL.EGL_BAD_NATIVE_WINDOW == eglError0) {
+                // Try window handle if available and differs (Windows HDC / HWND). 
+                // ANGLE impl. required HWND on Windows.
+                if(surface instanceof NativeWindow) {
+                    final NativeWindow nw = (NativeWindow) surface;
+                    if(nw.getWindowHandle() != nw.getSurfaceHandle()) {
+                        if(DEBUG) {
+                            System.err.println(getThreadName() + ": Info: Creation of window surface w/ surface handle failed: "+eglConfig+", error "+toHexString(eglError0)+", retry w/ windowHandle");
+                        }
+                        eglSurface = createSurface(eglDisplay, eglConfig.getNativeConfig(), nw.getWindowHandle());
+                        if (EGL.EGL_NO_SURFACE == eglSurface) {
+                            eglError0 = EGL.eglGetError();
+                        }
+                    }
+                }
+            }
+        }
+        if (EGL.EGL_NO_SURFACE == eglSurface) {
+            throw new GLException("Creation of window surface failed: "+eglConfig+", "+surface+", error "+toHexString(eglError0));
         }
 
         if(DEBUG) {
-            System.err.println("setSurface using component: handle "+toHexString(surface.getSurfaceHandle())+" -> "+toHexString(eglSurface));
+            System.err.println(getThreadName() + ": setSurface using component: handle "+toHexString(surface.getSurfaceHandle())+" -> "+toHexString(eglSurface));
         }
     }
 
+    @Override
+    protected final void updateHandle() {
+        if(ownEGLSurface) {
+            recreateSurface();
+        }
+    }
+    
     protected void setRealizedImpl() {
         if (realized) {
             AbstractGraphicsConfiguration aConfig = surface.getGraphicsConfiguration();
             AbstractGraphicsDevice aDevice = aConfig.getScreen().getDevice();
             if(aDevice instanceof EGLGraphicsDevice) {
                 if(DEBUG) {
-                    System.err.println("EGLDrawable.setRealized(true): using existing EGL config - START");
+                    System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): using existing EGL config - START");
                 }
                 // just fetch the data .. trust but verify ..
                 eglDisplay = aDevice.getHandle();
@@ -122,67 +151,65 @@ public abstract class EGLDrawable extends GLDrawableImpl {
                         // surface holds static EGLSurface
                         eglSurface = surface.getSurfaceHandle();
                         if(DEBUG) {
-                            System.err.println("setSurface re-using component's EGLSurface: handle "+toHexString(eglSurface));
+                            System.err.println(getThreadName() + ": setSurface re-using component's EGLSurface: handle "+toHexString(eglSurface));
                         }
                     } else {
-                        // EGLSurface is ours ..
+                        // EGLSurface is ours - subsequent updateHandle() will issue recreateSurface();
                         ownEGLSurface=true;
-                        recreateSurface();
                     }
                 } else {
                     throw new GLException("EGLGraphicsDevice hold by non EGLGraphicsConfiguration: "+aConfig);
                 }
             } else {
                 if(DEBUG) {
-                    System.err.println("EGLDrawable.setRealized(true): creating new EGL config - START");
+                    System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): creating new EGL config - START");
                 }
                 // create a new EGL config ..
                 ownEGLDisplay=true;
                 // EGLSurface is ours ..
                 ownEGLSurface=true;
 
-                long nDisplay=0;
-                if( NativeWindowFactory.TYPE_WINDOWS.equals(NativeWindowFactory.getNativeWindowType(false)) ) {
-                    nDisplay = surface.getSurfaceHandle(); // don't even ask ..
-                } else {
-                    nDisplay = aDevice.getHandle(); // 0 == EGL.EGL_DEFAULT_DISPLAY
-                }
-                eglDisplay = EGL.eglGetDisplay(nDisplay);
+                eglDisplay = EGLDisplayUtil.eglGetDisplay(surface, true);
                 if (eglDisplay == EGL.EGL_NO_DISPLAY) {
-                    if(DEBUG) {
-                        System.err.println("eglDisplay("+toHexString(nDisplay)+" <surfaceHandle>): failed, using EGL_DEFAULT_DISPLAY");
-                    }
-                    nDisplay = EGL.EGL_DEFAULT_DISPLAY;
-                    eglDisplay = EGL.eglGetDisplay(nDisplay);
+                    throw new GLException("Failed to created EGL display: "+surface+", "+aDevice+", error "+toHexString(EGL.eglGetError()));
                 }
-                if (eglDisplay == EGL.EGL_NO_DISPLAY) {
-                    throw new GLException("Failed to created EGL display: nhandle "+toHexString(nDisplay)+", "+aDevice+", error "+toHexString(EGL.eglGetError()));
-                } else if(DEBUG) {
-                    System.err.println("eglDisplay("+toHexString(nDisplay)+"): "+toHexString(eglDisplay));
-                }
-                if (!EGL.eglInitialize(eglDisplay, null, null)) {
+                if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) {
                     throw new GLException("eglInitialize failed"+", error "+Integer.toHexString(EGL.eglGetError()));
                 }
                 EGLGraphicsDevice e = new EGLGraphicsDevice(eglDisplay, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT);
-                DefaultGraphicsScreen s = new DefaultGraphicsScreen(e, aConfig.getScreen().getIndex());
-                // yes, use the already chosen/requested Capabilities (x11,win32,..)
+                AbstractGraphicsScreen s = new DefaultGraphicsScreen(e, aConfig.getScreen().getIndex());
                 final GLCapabilitiesImmutable capsRequested = (GLCapabilitiesImmutable) aConfig.getRequestedCapabilities();
-                final GLCapabilitiesImmutable capsChosen = (GLCapabilitiesImmutable) aConfig.getChosenCapabilities();
-                eglConfig = (EGLGraphicsConfiguration) GraphicsConfigurationFactory.getFactory(e).chooseGraphicsConfiguration(
-                        capsChosen, capsRequested, null, s);
-                if (null == eglConfig) {
-                    throw new GLException("Couldn't create EGLGraphicsConfiguration from "+s);
-                } else if(DEBUG) {
-                    System.err.println("Chosen eglConfig: "+eglConfig);
+                if(aConfig instanceof EGLGraphicsConfiguration) {
+                    final EGLGLCapabilities capsChosen = (EGLGLCapabilities) aConfig.getChosenCapabilities();
+                    if(0 == capsChosen.getEGLConfig()) {
+                        // 'refresh' the native EGLConfig handle
+                        capsChosen.setEGLConfig(EGLGraphicsConfiguration.EGLConfigId2EGLConfig(eglDisplay, capsChosen.getEGLConfigID()));
+                        if(0 == capsChosen.getEGLConfig()) {
+                            throw new GLException("Refreshing native EGLConfig handle failed: "+capsChosen+" of "+aConfig);
+                        }
+                    }
+                    eglConfig  = new EGLGraphicsConfiguration(s, capsChosen, capsRequested, null);
+                    if(DEBUG) {
+                        System.err.println(getThreadName() + ": Reusing chosenCaps: "+eglConfig);
+                    }
+                } else {
+                    eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(
+                            capsRequested, capsRequested, null, s, aConfig.getVisualID(VIDType.NATIVE), false);
+                
+                    if (null == eglConfig) {
+                        throw new GLException("Couldn't create EGLGraphicsConfiguration from "+s);
+                    } else if(DEBUG) {
+                        System.err.println(getThreadName() + ": Chosen eglConfig: "+eglConfig);
+                    }
                 }
-                recreateSurface();
+                // subsequent updateHandle() will issue recreateSurface();
             }
             if(DEBUG) {
-                System.err.println("EGLDrawable.setRealized(true): END: ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface+" - "+this);
+                System.err.println(getThreadName() + ": EGLDrawable.setRealized(true): END: ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface);
             }
         } else if (ownEGLSurface && eglSurface != EGL.EGL_NO_SURFACE) {
             if(DEBUG) {
-                System.err.println("EGLDrawable.setRealized(false): ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface);
+                System.err.println(getThreadName() + ": EGLDrawable.setRealized(false): ownDisplay "+ownEGLDisplay+", ownSurface "+ownEGLSurface+", eglDisplay: "+toHexString(eglDisplay)+", eglSurface: "+toHexString(eglSurface));
             }
             // Destroy the window surface
             if (!EGL.eglDestroySurface(eglDisplay, eglSurface)) {
@@ -190,7 +217,7 @@ public abstract class EGLDrawable extends GLDrawableImpl {
             }
             eglSurface = EGL.EGL_NO_SURFACE;
             if (ownEGLDisplay && EGL.EGL_NO_DISPLAY!=eglDisplay) {
-                EGL.eglTerminate(eglDisplay);
+                EGLDisplayUtil.eglTerminate(eglDisplay);
             }
             eglDisplay=EGL.EGL_NO_DISPLAY;
             eglConfig=null;
@@ -200,17 +227,17 @@ public abstract class EGLDrawable extends GLDrawableImpl {
     protected final void swapBuffersImpl() {
         // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers()
         if(!EGL.eglSwapBuffers(eglDisplay, eglSurface)) {
-            if(DEBUG) {
-                System.err.println("eglSwapBuffers failed:");
-                Thread.dumpStack();
-            }
+            throw new GLException("Error swapping buffers, eglError "+toHexString(EGL.eglGetError())+", "+this);
         }
     }
 
+    /** 
+     * Surface not realizes yet (onscreen) .. Quering EGL surface size only makes sense for external drawable.
+     * Leave it here for later impl. of an EGLExternalDrawable.  
     public int getWidth() {
         int[] tmp = new int[1];
         if (!EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_WIDTH, tmp, 0)) {
-            throw new GLException("Error querying surface width");
+            throw new GLException("Error querying surface width, eglError "+toHexString(EGL.eglGetError()));
         }
         return tmp[0];
     }
@@ -218,10 +245,10 @@ public abstract class EGLDrawable extends GLDrawableImpl {
     public int getHeight() {
         int[] tmp = new int[1];
         if (!EGL.eglQuerySurface(eglDisplay, eglSurface, EGL.EGL_HEIGHT, tmp, 0)) {
-            throw new GLException("Error querying surface height");
+            throw new GLException("Error querying surface height, eglError "+toHexString(EGL.eglGetError()));
         }
         return tmp[0];
-    }
+    } */
 
     public GLDynamicLookupHelper getGLDynamicLookupHelper() {
         if (getGLProfile().usesNativeGLES2()) {
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java
index cd6d61a..4b77bfa 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLDrawableFactory.java
@@ -37,22 +37,38 @@
 package jogamp.opengl.egl;
 
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.egl.EGLGraphicsDevice;
 import javax.media.opengl.*;
 import javax.media.opengl.GLProfile.ShutdownType;
 
 import com.jogamp.common.JogampRuntimeException;
+import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.*;
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.egl.EGLGraphicsDevice;
 
 import jogamp.opengl.*;
-import jogamp.nativewindow.WrappedSurface;
 
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 
 public class EGLDrawableFactory extends GLDrawableFactoryImpl {
     private static GLDynamicLookupHelper eglES1DynamicLookupHelper = null;
     private static GLDynamicLookupHelper eglES2DynamicLookupHelper = null;
+    private static boolean isANGLE = false;
+    
+    private static final boolean isANGLE(GLDynamicLookupHelper dl) {
+        if(Platform.OSType.WINDOWS == Platform.OS_TYPE) {
+            final boolean r = 0 != dl.dynamicLookupFunction("eglQuerySurfacePointerANGLE") ||
+                              0 != dl.dynamicLookupFunction("glBlitFramebufferANGLE") ||
+                              0 != dl.dynamicLookupFunction("glRenderbufferStorageMultisampleANGLE");
+            return r;
+        } else {
+            return false;
+        }
+    }
     
     public EGLDrawableFactory() {
         super();
@@ -68,12 +84,39 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
             } catch (JogampRuntimeException jre) { /* n/a .. */ }
         }
 
+        defaultDevice = new EGLGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT);
+        
         // FIXME: Probably need to move EGL from a static model 
         // to a dynamic one, where there can be 2 instances 
         // for each ES profile with their own ProcAddressTable.
 
         synchronized(EGLDrawableFactory.class) {
-            if(null==eglES1DynamicLookupHelper) {
+            /**
+             * Currently AMD's EGL impl. crashes at eglGetDisplay(EGL_DEFAULT_DISPLAY)
+             *  
+            // Check Desktop ES2 Availability first (AMD, ..)
+            if(null==eglES2DynamicLookupHelper) {
+                GLDynamicLookupHelper tmp=null;
+                try {
+                    tmp = new GLDynamicLookupHelper(new DesktopES2DynamicLibraryBundleInfo());
+                } catch (GLException gle) {
+                    if(DEBUG) {
+                        gle.printStackTrace();
+                    }
+                }                
+                if(null!=tmp && tmp.isLibComplete()) {
+                    eglES2DynamicLookupHelper = tmp;
+                    EGL.resetProcAddressTable(eglES2DynamicLookupHelper);
+                    if (GLProfile.DEBUG) {
+                        System.err.println("Info: EGLDrawableFactory: Desktop ES2 - OK");
+                    }                    
+                } else if (GLProfile.DEBUG) {
+                    System.err.println("Info: EGLDrawableFactory: Desktop ES2 - NOPE");
+                }                    
+            } */
+            final boolean hasDesktopES2 = null != eglES2DynamicLookupHelper;
+            
+            if(!hasDesktopES2 && null==eglES1DynamicLookupHelper) {
                 GLDynamicLookupHelper tmp=null;
                 try {
                     tmp = new GLDynamicLookupHelper(new EGLES1DynamicLibraryBundleInfo());
@@ -81,16 +124,20 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
                     if(DEBUG) {
                         gle.printStackTrace();
                     }
-                }
-                eglES1DynamicLookupHelper = tmp;
-                if(null!=eglES1DynamicLookupHelper && eglES1DynamicLookupHelper.isLibComplete()) {
+                }                
+                if(null!=tmp && tmp.isLibComplete()) {
+                    eglES1DynamicLookupHelper = tmp;
                     EGL.resetProcAddressTable(eglES1DynamicLookupHelper);
-                }
+                    final boolean isANGLEES1 = isANGLE(eglES1DynamicLookupHelper);
+                    isANGLE |= isANGLEES1;
+                    if (GLProfile.DEBUG) {
+                        System.err.println("Info: EGLDrawableFactory: EGL ES1 - OK, isANGLE: "+isANGLEES1);
+                    }                    
+                } else if (GLProfile.DEBUG) {
+                    System.err.println("Info: EGLDrawableFactory: EGL ES1 - NOPE");
+                }                    
             }
-        }
-
-        synchronized(EGLDrawableFactory.class) {
-            if(null==eglES2DynamicLookupHelper) {
+            if(!hasDesktopES2 && null==eglES2DynamicLookupHelper) {
                 GLDynamicLookupHelper tmp=null;
                 try {
                     tmp = new GLDynamicLookupHelper(new EGLES2DynamicLibraryBundleInfo());
@@ -98,57 +145,72 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
                     if(DEBUG) {
                         gle.printStackTrace();
                     }
-                }
-                eglES2DynamicLookupHelper = tmp;
-                if(null!=eglES2DynamicLookupHelper && eglES2DynamicLookupHelper.isLibComplete()) {
+                }                
+                if(null!=tmp && tmp.isLibComplete()) {
+                    eglES2DynamicLookupHelper = tmp;
                     EGL.resetProcAddressTable(eglES2DynamicLookupHelper);
-                }
+                    final boolean isANGLEES2 = isANGLE(eglES2DynamicLookupHelper);
+                    isANGLE |= isANGLEES2;
+                    if (GLProfile.DEBUG) {
+                        System.err.println("Info: EGLDrawableFactory: EGL ES2 - OK, isANGLE: "+isANGLEES2);
+                    }                    
+                } else if (GLProfile.DEBUG) {
+                    System.err.println("Info: EGLDrawableFactory: EGL ES2 - NOPE");
+                }                    
             }
         }
-        if(null != eglES1DynamicLookupHelper || null != eglES2DynamicLookupHelper) {
-            defaultDevice = new EGLGraphicsDevice(AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT);
-            sharedMap = new HashMap();
-        }
     }
 
     protected final void destroy(ShutdownType shutdownType) {
         if(null != sharedMap) {
+            Collection<SharedResource> srl = sharedMap.values();
+            for(Iterator<SharedResource> sri = srl.iterator(); sri.hasNext(); ) {
+                SharedResource sr = sri.next();
+                if(DEBUG) {
+                    System.err.println("EGLDrawableFactory.destroy("+shutdownType+"): "+sr.device.toString());
+                }
+                final long eglDisplay = sr.device.getHandle();
+                if(EGL.EGL_NO_DISPLAY != eglDisplay) {
+                    EGLDisplayUtil.eglTerminate(eglDisplay);
+                }
+            }
             sharedMap.clear();
             sharedMap = null;
         }
         defaultDevice = null;
         /**
          * Pulling away the native library may cause havoc ..
-         * 
+         */
         if(ShutdownType.COMPLETE == shutdownType) {
             if(null != eglES1DynamicLookupHelper) {
-                eglES1DynamicLookupHelper.destroy();
+                // eglES1DynamicLookupHelper.destroy();
                 eglES1DynamicLookupHelper = null;
             }
             if(null != eglES2DynamicLookupHelper) {
-                eglES2DynamicLookupHelper.destroy();
+                // eglES2DynamicLookupHelper.destroy();
                 eglES2DynamicLookupHelper = null;
             }
-        } */
+        }
+        EGLGraphicsConfigurationFactory.unregisterFactory();
     }
 
-    private HashMap/*<connection, SharedResource>*/ sharedMap;
+    private HashMap<String /*connection*/, SharedResource> sharedMap = new HashMap<String /*connection*/, SharedResource>();
     private EGLGraphicsDevice defaultDevice;
 
     static class SharedResource {
-      private EGLGraphicsDevice device;
-      // private EGLDrawable drawable;
-      // private EGLContext contextES1;
-      // private EGLContext contextES2;
-      private boolean wasES1ContextCreated;
-      private boolean wasES2ContextCreated;
+      private final EGLGraphicsDevice device;
+      // private final EGLDrawable drawable;
+      // private final EGLContext contextES1;
+      // private final EGLContext contextES2;
+      private final boolean wasES1ContextCreated;
+      private final boolean wasES2ContextCreated;
 
       SharedResource(EGLGraphicsDevice dev, boolean wasContextES1Created, boolean wasContextES2Created 
                      /*EGLDrawable draw, EGLContext ctxES1, EGLContext ctxES2 */) {
-          device = dev;
-          // drawable = draw;
-          // contextES1 = ctxES1;
-          // contextES2 = ctxES2;
+          this.device = dev;
+          // this.drawable = draw;
+          // this.contextES1 = ctxES1;
+          // this.contextES2 = ctxES2;
           this.wasES1ContextCreated = wasContextES1Created;
           this.wasES2ContextCreated = wasContextES2Created;
       }
@@ -165,7 +227,8 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
     }
 
     public final boolean getIsDeviceCompatible(AbstractGraphicsDevice device) {
-      return true; // via mappings (X11/WGL/.. -> EGL) we shall be able to handle all types.
+      // via mappings (X11/WGL/.. -> EGL) we shall be able to handle all types.
+      return null!=eglES2DynamicLookupHelper || null!=eglES1DynamicLookupHelper;
     }
 
     /**
@@ -199,19 +262,22 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
     } */
     
     /* package */ SharedResource getOrCreateEGLSharedResource(AbstractGraphicsDevice adevice) {
+        if(null == eglES1DynamicLookupHelper && null == eglES2DynamicLookupHelper) {
+            return null;
+        }
         String connection = adevice.getConnection();
         SharedResource sr;
         synchronized(sharedMap) {
             sr = (SharedResource) sharedMap.get(connection);
         }
-        if(null==sr) {   
-            long eglDisplay = EGL.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
+        if(null==sr) {
+            long eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
             if (eglDisplay == EGL.EGL_NO_DISPLAY) {
                 throw new GLException("Failed to created EGL default display: error 0x"+Integer.toHexString(EGL.eglGetError()));
             } else if(DEBUG) {
                 System.err.println("EGLDrawableFactory.createShared: eglDisplay(EGL_DEFAULT_DISPLAY): 0x"+Long.toHexString(eglDisplay));
             }
-            if (!EGL.eglInitialize(eglDisplay, null, null)) {
+            if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) {
                 throw new GLException("eglInitialize failed"+", error 0x"+Integer.toHexString(EGL.eglGetError()));
             }
             final EGLGraphicsDevice sharedDevice = new EGLGraphicsDevice(eglDisplay, connection, adevice.getUnitID());            
@@ -263,16 +329,14 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
         return null;
     }
 
+    public boolean isANGLE() {
+        return isANGLE;
+    }
+    
     public GLDynamicLookupHelper getGLDynamicLookupHelper(int esProfile) {
         if (2==esProfile) {
-            if(null==eglES2DynamicLookupHelper) {
-                throw new GLException("GLDynamicLookupHelper for ES2 not available");
-            }
             return eglES2DynamicLookupHelper;
         } else if (1==esProfile) {
-            if(null==eglES1DynamicLookupHelper) {
-                throw new GLException("GLDynamicLookupHelper for ES1 not available");
-            }
             return eglES1DynamicLookupHelper;
         } else {
             throw new GLException("Unsupported: ES"+esProfile);
@@ -280,6 +344,9 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
     }
 
     protected List<GLCapabilitiesImmutable> getAvailableCapabilitiesImpl(AbstractGraphicsDevice device) {
+        if(null == eglES1DynamicLookupHelper && null == eglES2DynamicLookupHelper) {
+            return new ArrayList<GLCapabilitiesImmutable>(); // null
+        }
         return EGLGraphicsConfigurationFactory.getAvailableCapabilities(this, device);
     }
 
@@ -317,7 +384,7 @@ public class EGLDrawableFactory extends GLDrawableFactoryImpl {
         // FIXME device/windowHandle -> screen ?!
         EGLGraphicsDevice device = (EGLGraphicsDevice) adevice;
         DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0);
-        EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, -1);
+        EGLGraphicsConfiguration cfg = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(capsRequested, capsRequested, chooser, screen, VisualIDHolder.VID_UNDEFINED, false);
         WrappedSurface ns = new WrappedSurface(cfg, windowHandle);
         return ns;
     }
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java
index 1f9254b..fe9d757 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLDynamicLibraryBundleInfo.java
@@ -44,7 +44,6 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle
     static List<String> glueLibNames;
     static {
         glueLibNames = new ArrayList<String>();
-        glueLibNames.addAll(GLDynamicLibraryBundleInfo.getGlueLibNamesPreload());
         glueLibNames.add("jogl_mobile");
     }
 
@@ -52,9 +51,18 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle
         super();
     }
 
-    /** Might be a desktop GL library, and might need to allow symbol access to subsequent libs */
+    /** 
+     * Might be a desktop GL library, and might need to allow symbol access to subsequent libs.
+     * 
+     * This respects old DRI requirements:<br>
+     * <pre>
+     * http://dri.sourceforge.net/doc/DRIuserguide.html
+     * </pre>
+     */
+    @Override
     public boolean shallLinkGlobal() { return true; }
     
+    @Override
     public boolean shallLookupGlobal() {
         if ( AndroidVersion.isAvailable ) {
             // Android requires global symbol lookup
@@ -64,34 +72,46 @@ public abstract class EGLDynamicLibraryBundleInfo extends GLDynamicLibraryBundle
         return false;
     }
     
+    @Override
     public final List<String> getToolGetProcAddressFuncNameList() {
         List<String> res = new ArrayList<String>();
         res.add("eglGetProcAddress");
         return res;
     }
 
+    @Override
     public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
         return EGL.eglGetProcAddress(toolGetProcAddressHandle, funcName);
     }
 
+    @Override
     public final boolean useToolGetProcAdressFirst(String funcName) {
-        return false; // JAU / FIXME funcName.startsWith("egl");
+        if ( AndroidVersion.isAvailable ) {
+            // Android requires global dlsym lookup
+            return false;
+        } else {
+            return true;
+        }
     }
     
     protected List<String> getEGLLibNamesList() {
         List<String> eglLibNames = new ArrayList<String>();
         
-        // try default generic names first 
-        eglLibNames.add("EGL");        
+        // this is the default EGL lib name, according to the spec 
+        eglLibNames.add("libEGL.so.1");
+        
+        // try these as well, if spec fails
+        eglLibNames.add("libEGL.so");
+        eglLibNames.add("EGL");
+        
         // for windows distributions using the 'unlike' lib prefix, 
         // where our tool does not add it.
         eglLibNames.add("libEGL");
-        // this is the default EGL lib name, according to the spec 
-        eglLibNames.add("libEGL.so.1");
         
         return eglLibNames;
     }
-    
+
+    @Override
     public final List<String> getGlueLibNames() {
         return glueLibNames;
     }    
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java
index 63109f4..0a373eb 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLES1DynamicLibraryBundleInfo.java
@@ -40,11 +40,12 @@ public class EGLES1DynamicLibraryBundleInfo extends EGLDynamicLibraryBundleInfo
         {
             final List<String> libsGL = new ArrayList<String>();
             
-            // GLESv2
-            libsGL.add("GLESv1_CM");
-            libsGL.add("libGLESv1_CM.so");
             // this is the default lib name, according to the spec 
             libsGL.add("libGLESv1_CM.so.2");
+            
+            // try these as well, if spec fails
+            libsGL.add("libGLESv1_CM.so");
+            libsGL.add("GLESv1_CM");            
 
             // alternative names
             libsGL.add("GLES_CM");
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java
index b0748ad..d4ee852 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLES2DynamicLibraryBundleInfo.java
@@ -40,11 +40,12 @@ public class EGLES2DynamicLibraryBundleInfo extends EGLDynamicLibraryBundleInfo
         {
             final List<String> libsGL = new ArrayList<String>();
             
-            // GLESv2
-            libsGL.add("GLESv2");
-            libsGL.add("libGLESv2.so");
             // this is the default lib name, according to the spec 
             libsGL.add("libGLESv2.so.2");
+            
+            // try these as well, if spec fails
+            libsGL.add("libGLESv2.so");            
+            libsGL.add("GLESv2");
 
             // alternative names
             libsGL.add("GLES20");
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java b/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java
index 796a431..ff60a52 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLExternalContext.java
@@ -45,7 +45,7 @@ public class EGLExternalContext extends EGLContext {
     public EGLExternalContext(AbstractGraphicsScreen screen) {
         super(null, null);
         GLContextShareSet.contextCreated(this);
-        setGLFunctionAvailability(false, 0, 0, CTX_IS_ARB_CREATED|CTX_PROFILE_ES|CTX_OPTION_ANY);
+        setGLFunctionAvailability(false, 0, 0, CTX_IS_ARB_CREATED|CTX_PROFILE_ES);
         getGLStateTracker().setEnabled(false); // external context usage can't track state in Java
     }
 
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java
index bd5eb1b..f813edf 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLGLCapabilities.java
@@ -28,44 +28,29 @@
 
 package jogamp.opengl.egl;
 
-import java.util.Comparator;
+import javax.media.nativewindow.NativeWindowException;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
+
 public class EGLGLCapabilities extends GLCapabilities {
-  final long eglcfg;
-  final int  eglcfgid;
-  final int renderableType;  
-  int nativeVisualID;
+  private long eglcfg;
+  final private int  eglcfgid;
+  final private int  renderableType;  
+  final private int  nativeVisualID;
   
-  /** Comparing EGLConfig ID only */
-  public static class EglCfgIDComparator implements Comparator<EGLGLCapabilities> {
-
-      public int compare(EGLGLCapabilities caps1, EGLGLCapabilities caps2) {
-        final long id1 = caps1.getEGLConfigID();
-
-        final long id2 = caps2.getEGLConfigID();
-
-        if(id1 > id2) {
-            return 1;
-        } else if(id1 < id2) {
-            return -1;
-        }
-        return 0;
-      }
-  }
-
   /**
    * 
    * @param eglcfg
    * @param eglcfgid
+   * @param visualID native visualID if valid, otherwise VisualIDHolder.VID_UNDEFINED
    * @param glp desired GLProfile, or null if determined by renderableType
    * @param renderableType actual EGL renderableType
    * 
    * May throw GLException if given GLProfile is not compatible w/ renderableType
    */
-  public EGLGLCapabilities(long eglcfg, int eglcfgid, GLProfile glp, int renderableType) {
+  public EGLGLCapabilities(long eglcfg, int eglcfgid, int visualID, GLProfile glp, int renderableType) {
       super( ( null != glp ) ? glp : getCompatible(renderableType) );
       this.eglcfg = eglcfg;
       this.eglcfgid = eglcfgid;
@@ -74,6 +59,7 @@ public class EGLGLCapabilities extends GLCapabilities {
                                 " with EGL-RenderableType["+renderableTypeToString(null, renderableType)+"]");
       }
       this.renderableType = renderableType;
+      this.nativeVisualID = visualID;
   }
 
   public Object cloneMutable() {
@@ -87,13 +73,26 @@ public class EGLGLCapabilities extends GLCapabilities {
       throw new GLException(e);
     }
   }
-
+  
+  final protected void setEGLConfig(long v) { eglcfg=v; }
   final public long getEGLConfig() { return eglcfg; }
   final public int getEGLConfigID() { return eglcfgid; }
   final public int getRenderableType() { return renderableType; }
-  final public void setNativeVisualID(int vid) { nativeVisualID=vid; }
   final public int getNativeVisualID() { return nativeVisualID; }
   
+  @Override
+  final public int getVisualID(VIDType type) throws NativeWindowException {
+      switch(type) {
+          case INTRINSIC:
+          case EGL_CONFIG:
+              return getEGLConfigID();
+          case NATIVE:
+              return getNativeVisualID();
+          default:
+              throw new NativeWindowException("Invalid type <"+type+">");
+      }      
+  }
+  
   public static boolean isCompatible(GLProfile glp, int renderableType) {
     if(null == glp) {
         return true;
@@ -123,9 +122,9 @@ public class EGLGLCapabilities extends GLCapabilities {
     return null;
   }
   
-  public static StringBuffer renderableTypeToString(StringBuffer sink, int renderableType) {
+  public static StringBuilder renderableTypeToString(StringBuilder sink, int renderableType) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
     boolean first=true;
     if(0 != (renderableType & EGL.EGL_OPENGL_BIT)) {
@@ -143,12 +142,12 @@ public class EGLGLCapabilities extends GLCapabilities {
     return sink;      
   }
   
-  public StringBuffer toString(StringBuffer sink) {
+  public StringBuilder toString(StringBuilder sink) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
-    sink.append("0x").append(Long.toHexString(eglcfgid)).append(": ");
-    sink.append("vid 0x").append(Integer.toHexString(nativeVisualID)).append(", ");
+    sink.append("egl cfg 0x").append(Integer.toHexString(eglcfgid));
+    sink.append(", vid 0x").append(Integer.toHexString(nativeVisualID)).append(": ");
     super.toString(sink);
     sink.append(", [");
     renderableTypeToString(sink, renderableType);
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java
index ea625fb..875bcb9 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfiguration.java
@@ -42,23 +42,22 @@ import java.util.ArrayList;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.egl.EGLGraphicsDevice;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.opengl.DefaultGLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
-import jogamp.opengl.Debug;
 import jogamp.opengl.GLGraphicsConfigurationUtil;
 
 import com.jogamp.common.nio.Buffers;
 import com.jogamp.common.nio.PointerBuffer;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.egl.EGLGraphicsDevice;
 
 public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable {
-    protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration");
-
+    
     public final long getNativeConfig() {
         return ((EGLGLCapabilities)capabilitiesChosen).getEGLConfig();
     }
@@ -74,19 +73,20 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
     }
 
     public static EGLGraphicsConfiguration create(GLCapabilitiesImmutable capsRequested, AbstractGraphicsScreen absScreen, int cfgID) {
-        AbstractGraphicsDevice absDevice = absScreen.getDevice();
+        final AbstractGraphicsDevice absDevice = absScreen.getDevice();
         if(null==absDevice || !(absDevice instanceof EGLGraphicsDevice)) {
             throw new GLException("GraphicsDevice must be a valid EGLGraphicsDevice");
         }
-        long dpy = absDevice.getHandle();
+        final long dpy = absDevice.getHandle();
         if (dpy == EGL.EGL_NO_DISPLAY) {
             throw new GLException("Invalid EGL display: "+absDevice);
         }
-        GLProfile glp = capsRequested.getGLProfile();
-        long cfg = EGLConfigId2EGLConfig(glp, dpy, cfgID);
-        EGLGLCapabilities caps = EGLConfig2Capabilities(glp, dpy, cfg, false, capsRequested.isOnscreen(), capsRequested.isPBuffer());
-        caps = (EGLGLCapabilities) GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(caps, capsRequested.isBackgroundOpaque()); // FIXME: valid to override EGL transparency ?
-        return new EGLGraphicsConfiguration(absScreen, caps, capsRequested, new DefaultGLCapabilitiesChooser());
+        final long cfg = EGLConfigId2EGLConfig(dpy, cfgID);
+        if(0 < cfg) {
+            final EGLGLCapabilities caps = EGLConfig2Capabilities(capsRequested.getGLProfile(), dpy, cfg, false, capsRequested.isOnscreen(), capsRequested.isPBuffer(), false);
+            return new EGLGraphicsConfiguration(absScreen, caps, capsRequested, new DefaultGLCapabilitiesChooser());
+        }
+        return null;
     }
 
     @Override
@@ -102,12 +102,12 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
             // FIXME: setScreen( ... );
             setChosenCapabilities(newConfig.getChosenCapabilities());
             if(DEBUG) {
-                System.err.println("!!! updateGraphicsConfiguration(1): "+this);
+                System.err.println("updateGraphicsConfiguration(1): "+this);
             }
         }
     }
 
-    public static long EGLConfigId2EGLConfig(GLProfile glp, long display, int configID) {
+    public static long EGLConfigId2EGLConfig(long display, int configID) {
         int[] attrs = new int[] {
                 EGL.EGL_CONFIG_ID, configID,
                 EGL.EGL_NONE
@@ -131,7 +131,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
 
         int[] stype = new int[1];
         if(! EGL.eglGetConfigAttrib(display, config, EGL.EGL_SURFACE_TYPE, stype, 0)) {
-            throw new GLException("Could not determine EGL_SURFACE_TYPE !!!");
+            throw new GLException("Could not determine EGL_SURFACE_TYPE");
         }
 
         if ( 0 != ( stype[0] & EGL.EGL_WINDOW_BIT ) ) {
@@ -148,12 +148,12 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
     }
 
     public static EGLGLCapabilities EGLConfig2Capabilities(GLProfile glp, long display, long config,
-                                                           boolean relaxed, boolean onscreen, boolean usePBuffer) {
+                                                           boolean relaxed, boolean onscreen, boolean usePBuffer, boolean forceTransparentFlag) {
         ArrayList bucket = new ArrayList();
         final int winattrmask = GLGraphicsConfigurationUtil.getWinAttributeBits(onscreen, usePBuffer);
-        if( EGLConfig2Capabilities(bucket, glp, display, config, winattrmask) ) {
+        if( EGLConfig2Capabilities(bucket, glp, display, config, winattrmask, forceTransparentFlag) ) {
             return (EGLGLCapabilities) bucket.get(0);
-        } else if ( relaxed && EGLConfig2Capabilities(bucket, glp, display, config, GLGraphicsConfigurationUtil.ALL_BITS) ) {
+        } else if ( relaxed && EGLConfig2Capabilities(bucket, glp, display, config, GLGraphicsConfigurationUtil.ALL_BITS, forceTransparentFlag) ) {
             return (EGLGLCapabilities) bucket.get(0);
         }
         return null;
@@ -161,7 +161,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
 
     public static boolean EGLConfig2Capabilities(ArrayList capsBucket,
                                                  GLProfile glp, long display, long config,
-                                                 int winattrmask) {
+                                                 int winattrmask, boolean forceTransparentFlag) {
         final int allDrawableTypeBits = EGLConfigDrawableTypeBits(display, config);
         final int drawableTypeBits = winattrmask & allDrawableTypeBits;
 
@@ -172,6 +172,7 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
         final IntBuffer val = Buffers.newDirectIntBuffer(1);
         final int cfgID;
         final int rType;
+        final int visualID;
         
         // get the configID
         if(!EGL.eglGetConfigAttrib(display, config, EGL.EGL_CONFIG_ID, val)) {
@@ -190,10 +191,16 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
             return false;
         }
         rType = val.get(0);
+                       
+        if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_NATIVE_VISUAL_ID, val)) {
+            visualID = val.get(0);
+        } else {
+            visualID = VisualIDHolder.VID_UNDEFINED;
+        }
         
         EGLGLCapabilities caps = null;        
         try {
-            caps = new EGLGLCapabilities(config, cfgID, glp, rType);
+            caps = new EGLGLCapabilities(config, cfgID, visualID, glp, rType);
         } catch (GLException gle) {
             if(DEBUG) {
                 System.err.println("config "+toHexString(config)+": "+gle);
@@ -201,10 +208,6 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
             return false;
         }        
                 
-        // Read the actual configuration into the chosen caps
-        if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_NATIVE_VISUAL_ID, val)) {
-            caps.setNativeVisualID(val.get(0));
-        }                
         if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_RED_SIZE, val)) {
             caps.setRedBits(val.get(0));
         }
@@ -238,7 +241,9 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
                 }
             }
         }
-        if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_TRANSPARENT_TYPE, val)) {
+        if(forceTransparentFlag) {
+            caps.setBackgroundOpaque(false);
+        } else if(EGL.eglGetConfigAttrib(display, config, EGL.EGL_TRANSPARENT_TYPE, val)) {
             caps.setBackgroundOpaque(val.get(0) != EGL.EGL_TRANSPARENT_RGB);
         }
         if(!caps.isBackgroundOpaque()) {
@@ -275,11 +280,15 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
         attrs[idx++] = EGL.EGL_BLUE_SIZE;
         attrs[idx++] = caps.getBlueBits();
 
-        attrs[idx++] = EGL.EGL_ALPHA_SIZE;
-        attrs[idx++] = caps.getAlphaBits() > 0 ? caps.getAlphaBits() : EGL.EGL_DONT_CARE;
-
-        attrs[idx++] = EGL.EGL_STENCIL_SIZE;
-        attrs[idx++] = caps.getStencilBits() > 0 ? caps.getStencilBits() : EGL.EGL_DONT_CARE;
+        if(caps.getAlphaBits()>0) {
+            attrs[idx++] = EGL.EGL_ALPHA_SIZE;
+            attrs[idx++] = caps.getAlphaBits();
+        }
+        
+        if(caps.getStencilBits()>0) {
+            attrs[idx++] = EGL.EGL_STENCIL_SIZE;
+            attrs[idx++] = caps.getStencilBits();
+        }
 
         attrs[idx++] = EGL.EGL_DEPTH_SIZE;
         attrs[idx++] = caps.getDepthBits();
@@ -359,7 +368,8 @@ public class EGLGraphicsConfiguration extends MutableGraphicsConfiguration imple
 
     @Override
     public String toString() {
-        return getClass().getSimpleName()+"["+getScreen()+", eglConfigID "+toHexString(getNativeConfigID())+
+        return getClass().getSimpleName()+"["+getScreen()+
+                                     ",\n\teglConfigHandle "+toHexString(getNativeConfig())+", eglConfigID "+toHexString(getNativeConfigID())+
                                      ",\n\trequested " + getRequestedCapabilities()+
                                      ",\n\tchosen    " + getChosenCapabilities()+
                                      "]";
diff --git a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java
index ceeebe6..904110e 100644
--- a/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/egl/EGLGraphicsConfigurationFactory.java
@@ -40,7 +40,9 @@ import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.DefaultGraphicsScreen;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.egl.EGLGraphicsDevice;
+import javax.media.nativewindow.VisualIDHolder;
+import javax.media.nativewindow.VisualIDHolder.VIDType;
+import javax.media.nativewindow.NativeWindowFactory;
 
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLCapabilitiesChooser;
@@ -51,9 +53,11 @@ import javax.media.opengl.GLDrawableFactory;
 
 import com.jogamp.common.nio.Buffers;
 import com.jogamp.common.nio.PointerBuffer;
+import com.jogamp.nativewindow.egl.EGLGraphicsDevice;
 
 import jogamp.opengl.GLGraphicsConfigurationFactory;
 import jogamp.opengl.GLGraphicsConfigurationUtil;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
@@ -67,12 +71,40 @@ import java.nio.IntBuffer;
     GraphicsDevice and GraphicsConfiguration abstractions. */
 
 public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    static EGLGLCapabilities.EglCfgIDComparator EglCfgIDComparator = new EGLGLCapabilities.EglCfgIDComparator();
-
+    static VisualIDHolder.VIDComparator EglCfgIDComparator = new VisualIDHolder.VIDComparator(VisualIDHolder.VIDType.EGL_CONFIG);
+    static GraphicsConfigurationFactory nativeGraphicsConfigurationFactory = null;
+    static GraphicsConfigurationFactory kdeglGraphicsConfigurationFactory = null;
+    
     static void registerFactory() {
+        GraphicsConfigurationFactory eglFactory = new EGLGraphicsConfigurationFactory();
+        
+        // become the pre-selector for X11/.. to match the native visual id w/ EGL, if native ES is selected
+        final String nwType = NativeWindowFactory.getNativeWindowType(false);
+        if(NativeWindowFactory.TYPE_X11 == nwType) {
+            nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, eglFactory);
+        } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) {
+            nativeGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, eglFactory);
+        } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) {            
+        } */
+        
         // become the selector for KD/EGL ..
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.egl.EGLGraphicsDevice.class, new EGLGraphicsConfigurationFactory());
+        kdeglGraphicsConfigurationFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, eglFactory);
+    }
+    
+    static void unregisterFactory() {
+        final String nwType = NativeWindowFactory.getNativeWindowType(false);
+        if(NativeWindowFactory.TYPE_X11 == nwType) {
+            GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, nativeGraphicsConfigurationFactory);                    
+        } /* else if(NativeWindowFactory.TYPE_WINDOWS == NativeWindowFactory.getNativeWindowType(false)) {
+            GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, nativeGraphicsConfigurationFactory);
+        } else if(NativeWindowFactory.TYPE_MACOSX == NativeWindowFactory.getNativeWindowType(false)) {            
+        } */
+        nativeGraphicsConfigurationFactory = null;
+        
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.egl.EGLGraphicsDevice.class, kdeglGraphicsConfigurationFactory);
+        kdeglGraphicsConfigurationFactory = null;
     }
+    
     private EGLGraphicsConfigurationFactory() {
     }
 
@@ -86,6 +118,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
         if (! (capsChosen instanceof GLCapabilitiesImmutable) ) {
             throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilities objects - chosen");
         }
+        final GLCapabilitiesImmutable glCapsChosen = (GLCapabilitiesImmutable) capsChosen;
 
         if (! (capsRequested instanceof GLCapabilitiesImmutable) ) {
             throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilities objects - requested");
@@ -96,10 +129,48 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
             throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects");
         }
 
-        return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen,
-                                                 (GLCapabilitiesImmutable) capsRequested,
-                                                 (GLCapabilitiesChooser) chooser,
-                                                 absScreen, -1);
+        AbstractGraphicsDevice absDevice = absScreen.getDevice();
+        if(null==absDevice) {
+            throw new GLException("Null AbstractGraphicsDevice");
+        }        
+        
+        AbstractGraphicsConfiguration cfg = null;
+        
+        if( absDevice instanceof EGLGraphicsDevice ) {
+            cfg = chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen,
+                                                    (GLCapabilitiesImmutable) capsRequested,
+                                                    (GLCapabilitiesChooser) chooser,
+                                                    absScreen, VisualIDHolder.VID_UNDEFINED, false);            
+        } else {
+            // handle non native cases (X11, ..) 
+            if(null == nativeGraphicsConfigurationFactory) {
+                throw new InternalError("Native GraphicsConfigurationFactory is null, but call issued for device: "+absDevice+" of type "+absDevice.getClass().getSimpleName());
+            }
+            
+            if(glCapsChosen.getGLProfile().usesNativeGLES()) {
+                if(DEBUG) {
+                    System.err.println("EGLGraphicsConfigurationFactory.choose..: Handle native device "+absDevice.getClass().getSimpleName());
+                }
+                cfg = chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable) capsChosen,
+                                                        (GLCapabilitiesImmutable) capsRequested,
+                                                        (GLCapabilitiesChooser) chooser,
+                                                        absScreen, VisualIDHolder.VID_UNDEFINED, false);
+                if(null == cfg || VisualIDHolder.VID_UNDEFINED == cfg.getVisualID(VIDType.NATIVE)) {
+                    cfg = null;
+                    if(DEBUG) {
+                        System.err.println("EGLGraphicsConfigurationFactory.choose..: No native visual ID, fallback ..");
+                    }
+                }
+            }
+            if(null == cfg) {
+                // fwd to native config factory (only X11 for now)
+                if(DEBUG) {
+                    System.err.println("EGLGraphicsConfigurationFactory.choose..: Delegate to "+nativeGraphicsConfigurationFactory.getClass().getSimpleName());
+                }
+                cfg = nativeGraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen);
+            }            
+        }
+        return cfg;
     }
 
     protected static List<GLCapabilitiesImmutable> getAvailableCapabilities(EGLDrawableFactory factory, AbstractGraphicsDevice device) {
@@ -126,7 +197,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
             throw new GLException("Graphics configuration get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError()));
         }
         if (numConfigs.get(0) > 0) {
-            availableCaps = eglConfigs2GLCaps(null, eglDisplay, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS);
+            availableCaps = eglConfigs2GLCaps(null, eglDisplay, configs, numConfigs.get(0), GLGraphicsConfigurationUtil.ALL_BITS, false);
             if( null != availableCaps && availableCaps.size() > 1) {
                 Collections.sort(availableCaps, EglCfgIDComparator);
             }
@@ -138,7 +209,8 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
     public static EGLGraphicsConfiguration chooseGraphicsConfigurationStatic(GLCapabilitiesImmutable capsChosen,
                                                                              GLCapabilitiesImmutable capsReq,
                                                                              GLCapabilitiesChooser chooser,
-                                                                             AbstractGraphicsScreen absScreen, int nativeVisualID) {
+                                                                             AbstractGraphicsScreen absScreen, int nativeVisualID, 
+                                                                             boolean forceTransparentFlag) {
         if (capsChosen == null) {
             capsChosen = new GLCapabilities(null);
         }
@@ -147,86 +219,99 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
             throw new GLException("Null AbstractGraphicsScreen");
         }
         AbstractGraphicsDevice absDevice = absScreen.getDevice();
-
-        if(null==absDevice || !(absDevice instanceof EGLGraphicsDevice)) {
-            throw new GLException("GraphicsDevice must be a valid EGLGraphicsDevice");
+        if(null==absDevice) {
+            throw new GLException("Null AbstractGraphicsDevice");
         }
-        long eglDisplay = absDevice.getHandle();
-
-        if (eglDisplay == EGL.EGL_NO_DISPLAY) {
-            throw new GLException("Invalid EGL display: "+absDevice);
+        
+        final long eglDisplay;
+        final boolean ownEGLDisplay;
+        if( !(absDevice instanceof EGLGraphicsDevice) ) {
+            eglDisplay = EGLDisplayUtil.eglGetDisplay(absDevice.getHandle());
+            if (eglDisplay == EGL.EGL_NO_DISPLAY) {
+                throw new GLException("Could not get EGL display from: "+absDevice);
+            }
+            if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) {
+                throw new GLException("eglInitialize failed eglDisplay 0x"+Long.toHexString(eglDisplay)+", "+absDevice+", error 0x"+Integer.toHexString(EGL.eglGetError()));
+            }
+            ownEGLDisplay = true;
+        } else {
+            eglDisplay = absDevice.getHandle();
+            if (eglDisplay == EGL.EGL_NO_DISPLAY) {
+                throw new GLException("Invalid EGL display: "+absDevice);
+            }
+            ownEGLDisplay = false;
         }
 
         EGLDrawableFactory factory = (EGLDrawableFactory) GLDrawableFactory.getEGLFactory();
         capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory.canCreateGLPbuffer(absDevice) );
 
         GLProfile glp = capsChosen.getGLProfile();
+        GLCapabilities fixedCaps;
 
-        EGLGraphicsConfiguration res = eglChooseConfig(eglDisplay, capsChosen, capsReq, chooser, absScreen, nativeVisualID);
-        if(null!=res) {
-            return res;
-        }
-        if(DEBUG) {
-            System.err.println("eglChooseConfig failed with given capabilities "+capsChosen);
-        }
-
-        // Last try .. add a fixed embedded profile [ATI, Nokia, Intel, ..]
-        //
-        // rgb888 - d16, s4
-        GLCapabilities fixedCaps = new GLCapabilities(glp);
-        fixedCaps.setRedBits(8);
-        fixedCaps.setGreenBits(8);
-        fixedCaps.setBlueBits(8);
-        fixedCaps.setDepthBits(16);
-        fixedCaps.setSampleBuffers(true);
-        fixedCaps.setNumSamples(4);
-        if(DEBUG) {
-            System.err.println("trying fixed caps (1): "+fixedCaps);
-        }
-        res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID);
-        if(null!=res) {
-            return res;
+        EGLGraphicsConfiguration res = eglChooseConfig(eglDisplay, capsChosen, capsReq, chooser, absScreen, nativeVisualID, forceTransparentFlag);
+        if(null==res) {
+            if(DEBUG) {
+                System.err.println("eglChooseConfig failed with given capabilities "+capsChosen);
+            }
+    
+            // Last try .. add a fixed embedded profile [ATI, Nokia, Intel, ..]
+            //
+            // rgb888 - d16, s4
+            fixedCaps = new GLCapabilities(glp);
+            fixedCaps.setRedBits(8);
+            fixedCaps.setGreenBits(8);
+            fixedCaps.setBlueBits(8);
+            fixedCaps.setDepthBits(16);
+            fixedCaps.setSampleBuffers(true);
+            fixedCaps.setNumSamples(4);
+            if(DEBUG) {
+                System.err.println("trying fixed caps (1): "+fixedCaps);
+            }
+            res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false);
+        }
+        if(null==res) {
+            //
+            // rgb565 - d16, s0
+            fixedCaps = new GLCapabilities(glp);
+            fixedCaps.setRedBits(5);
+            fixedCaps.setGreenBits(6);
+            fixedCaps.setBlueBits(5);
+            fixedCaps.setDepthBits(16);
+            if(DEBUG) {
+                System.err.println("trying fixed caps (2): "+fixedCaps);
+            }
+            res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false);
+        }
+        if(null==res) {
+            //
+            // rgb565 - d16, s4
+            fixedCaps = new GLCapabilities(glp);
+            fixedCaps.setRedBits(5);
+            fixedCaps.setGreenBits(6);
+            fixedCaps.setBlueBits(5);
+            fixedCaps.setDepthBits(16);
+            fixedCaps.setSampleBuffers(true);
+            fixedCaps.setNumSamples(4);
+            if(DEBUG) {
+                System.err.println("trying fixed caps (3): "+fixedCaps);
+            }
+            res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID, false);
         }
-
-        //
-        // rgb565 - d16, s0
-        fixedCaps = new GLCapabilities(glp);
-        fixedCaps.setRedBits(5);
-        fixedCaps.setGreenBits(6);
-        fixedCaps.setBlueBits(5);
-        fixedCaps.setDepthBits(16);
-        if(DEBUG) {
-            System.err.println("trying fixed caps (2): "+fixedCaps);
-        }
-        res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID);
-        if(null!=res) {
-            return res;
-        }
-
-        //
-        // rgb565 - d16, s4
-        fixedCaps = new GLCapabilities(glp);
-        fixedCaps.setRedBits(5);
-        fixedCaps.setGreenBits(6);
-        fixedCaps.setBlueBits(5);
-        fixedCaps.setDepthBits(16);
-        fixedCaps.setSampleBuffers(true);
-        fixedCaps.setNumSamples(4);
-        if(DEBUG) {
-            System.err.println("trying fixed caps (3): "+fixedCaps);
+        if(null==res) {
+            throw new GLException("Graphics configuration failed [direct caps, eglGetConfig/chooser and fixed-caps(1-3)]");
         }
-        res = eglChooseConfig(eglDisplay, fixedCaps, capsReq, chooser, absScreen, nativeVisualID);
-        if(null!=res) {
-            return res;
+        if(ownEGLDisplay) {
+            ((EGLGLCapabilities) res.getChosenCapabilities()).setEGLConfig(0); // eglDisplay: EOL 
+            EGLDisplayUtil.eglTerminate(eglDisplay);
         }
-        throw new GLException("Graphics configuration failed [direct caps, eglGetConfig/chooser and fixed-caps(1-3)]");
+        return res;
     }
 
     static EGLGraphicsConfiguration eglChooseConfig(long eglDisplay, 
                                                     GLCapabilitiesImmutable capsChosen, GLCapabilitiesImmutable capsRequested,
                                                     GLCapabilitiesChooser chooser,
                                                     AbstractGraphicsScreen absScreen,
-                                                    int nativeVisualID) {
+                                                    int nativeVisualID, boolean forceTransparentFlag) {
         final GLProfile glp = capsChosen.getGLProfile();
         final boolean onscreen = capsChosen.isOnscreen();
         final boolean usePBuffer = capsChosen.isPBuffer();
@@ -244,7 +329,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
         }
         if (DEBUG) {
             System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglChooseConfig maxConfigs: "+numConfigs.get(0));
-            System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglDisplay "+toHexString(eglDisplay)+", "+capsChosen);
+            System.err.println("EGLGraphicsConfiguration.eglChooseConfig: eglDisplay "+toHexString(eglDisplay)+", "+capsChosen+", nativeVisualID "+toHexString(nativeVisualID));
         }
 
         final IntBuffer attrs = Buffers.newDirectIntBuffer(EGLGraphicsConfiguration.GLCapabilities2AttribList(capsChosen));
@@ -253,12 +338,12 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
         // 1st choice: get GLCapabilities based on users GLCapabilities 
         //             setting recommendedIndex as preferred choice
         // skipped if nativeVisualID is given
-        if( 0<=nativeVisualID || !EGL.eglChooseConfig(eglDisplay, attrs, configs, configs.capacity(), numConfigs) ) {
+        if( VisualIDHolder.VID_UNDEFINED != nativeVisualID || !EGL.eglChooseConfig(eglDisplay, attrs, configs, configs.capacity(), numConfigs) ) {
             if(DEBUG) {
                 System.err.println("EGLGraphicsConfiguration.eglChooseConfig: #1 eglChooseConfig: false");
             }
         } else  if (numConfigs.get(0) > 0) {
-            availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask);
+            availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag);
             if(availableCaps.size() > 0) {
                 recommendedEGLConfig =  configs.get(0);
                 recommendedIndex = 0;
@@ -283,7 +368,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
                 throw new GLException("EGLGraphicsConfiguration.eglChooseConfig: #2 Get all configs (eglGetConfigs) call failed, error "+toHexString(EGL.eglGetError()));
             }
             if (numConfigs.get(0) > 0) {
-                availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask);
+                availableCaps = eglConfigs2GLCaps(glp, eglDisplay, configs, numConfigs.get(0), winattrmask, forceTransparentFlag);
             }
         }
 
@@ -302,11 +387,11 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
             }
         }
 
-        if(0<=nativeVisualID) {
+        if( VisualIDHolder.VID_UNDEFINED != nativeVisualID ) {
             List/*<EGLGLCapabilities>*/ removedCaps = new ArrayList();
             for(int i=0; i<availableCaps.size(); ) {
-                EGLGLCapabilities ecap = (EGLGLCapabilities) availableCaps.get(i);
-                if(ecap.getNativeVisualID()!=nativeVisualID) {
+                VisualIDHolder vidh = (VisualIDHolder) availableCaps.get(i);
+                if(vidh.getVisualID(VIDType.NATIVE) != nativeVisualID) {
                     removedCaps.add(availableCaps.remove(i));
                 } else {
                     i++;
@@ -315,10 +400,10 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
             if(0==availableCaps.size()) {
                 availableCaps = removedCaps;
                 if(DEBUG) {
-                    System.err.println("EGLGraphicsConfiguration.eglChooseConfig: post filter nativeVisualID ("+nativeVisualID+") no config found, revert to all");
+                    System.err.println("EGLGraphicsConfiguration.eglChooseConfig: post filter nativeVisualID "+toHexString(nativeVisualID)+" no config found, revert to all");
                 }
             } else if(DEBUG) {
-                System.err.println("EGLGraphicsConfiguration.eglChooseConfig: post filter nativeVisualID ("+nativeVisualID+") got configs: "+availableCaps.size());
+                System.err.println("EGLGraphicsConfiguration.eglChooseConfig: post filter nativeVisualID "+toHexString(nativeVisualID)+" got configs: "+availableCaps.size());
             }
         }
 
@@ -336,10 +421,10 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
         return new EGLGraphicsConfiguration(absScreen, chosenCaps, capsRequested, chooser);
     }
 
-    static List/*<GLCapabilitiesImmutable>*/ eglConfigs2GLCaps(GLProfile glp, long eglDisplay, PointerBuffer configs, int num, int winattrmask) {
+    static List/*<GLCapabilitiesImmutable>*/ eglConfigs2GLCaps(GLProfile glp, long eglDisplay, PointerBuffer configs, int num, int winattrmask, boolean forceTransparentFlag) {
         ArrayList caps = new ArrayList(num);
         for(int i=0; i<num; i++) {
-            EGLGraphicsConfiguration.EGLConfig2Capabilities(caps, glp, eglDisplay, configs.get(i), winattrmask);
+            EGLGraphicsConfiguration.EGLConfig2Capabilities(caps, glp, eglDisplay, configs.get(i), winattrmask, forceTransparentFlag);
         }
         return caps;
     }
@@ -363,7 +448,7 @@ public class EGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFact
         }
 
         DefaultGraphicsScreen screen = new DefaultGraphicsScreen(device, 0);
-        EGLGraphicsConfiguration eglConfig = chooseGraphicsConfigurationStatic(capsChosen, capsReq, chooser, screen, -1);
+        EGLGraphicsConfiguration eglConfig = chooseGraphicsConfigurationStatic(capsChosen, capsReq, chooser, screen, VisualIDHolder.VID_UNDEFINED, false);
         if (null == eglConfig) {
             throw new GLException("Couldn't create EGLGraphicsConfiguration from "+screen);
         } else if(DEBUG) {
diff --git a/src/jogl/classes/jogamp/opengl/gl2/Util.java b/src/jogl/classes/jogamp/opengl/gl2/Util.java
deleted file mode 100644
index 83f98a6..0000000
--- a/src/jogl/classes/jogamp/opengl/gl2/Util.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/* 
- * Copyright (c) 2002-2004 LWJGL Project
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are 
- * met:
- * 
- * * Redistributions of source code must retain the above copyright 
- *   notice, this list of conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- *
- * * Neither the name of 'LWJGL' nor the names of 
- *   its contributors may be used to endorse or promote products derived 
- *   from this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- * 
- * - Redistribution of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- * 
- * - Redistribution in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * 
- * Neither the name of Sun Microsystems, Inc. or the names of
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 
- * This software is provided "AS IS," without a warranty of any kind. ALL
- * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
- * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
- * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
- * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
- * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
- * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
- * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
- * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
- * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
- * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
- * 
- * You acknowledge that this software is not designed or intended for use
- * in the design, construction, operation or maintenance of any nuclear
- * facility.
- */
-
-package jogamp.opengl.gl2;
-
-import jogamp.opengl.*;
-
-import java.nio.IntBuffer;
-import javax.media.opengl.*;
-
-/**
- * Util.java
- * <p/>
- * <p/>
- * Created 7-jan-2004
- *
- * @author Erik Duijs
- */
-class Util {
-
-  /**
-   * temp int[] of one for getting an int from some GL functions
-   */
-  private int[] scratch = new int[1];
-
-  /**
-   * Return ceiling of integer division
-   *
-   * @param a
-   * @param b
-   *
-   * @return int
-   */
-  protected static int ceil(int a, int b) {
-    return (a % b == 0 ? a / b : a / b + 1);
-  }
-
-  /**
-   * Method compPerPix.
-   *
-   * @param format
-   *
-   * @return int
-   */
-  protected static int compPerPix(int format) {
-    /* Determine number of components per pixel */
-    switch ( format ) {
-    case GL2.GL_COLOR_INDEX:
-    case GL2.GL_STENCIL_INDEX:
-    case GL2.GL_DEPTH_COMPONENT:
-    case GL2.GL_RED:
-    case GL2.GL_GREEN:
-    case GL2.GL_BLUE:
-    case GL2.GL_ALPHA:
-    case GL2.GL_LUMINANCE:
-      return 1;
-    case GL2.GL_LUMINANCE_ALPHA:
-      return 2;
-    case GL2.GL_RGB:
-    case GL2.GL_BGR:
-      return 3;
-    case GL2.GL_RGBA:
-    case GL2.GL_BGRA:
-      return 4;
-    default :
-      return -1;
-    }
-  }
-
-  /**
-   * Method nearestPower.
-   * <p/>
-   * Compute the nearest power of 2 number.  This algorithm is a little strange, but it works quite well.
-   *
-   * @param value
-   *
-   * @return int
-   */
-  protected static int nearestPower(int value) {
-    int i;
-
-    i = 1;
-
-    /* Error! */
-    if ( value == 0 )
-      return -1;
-
-    for ( ; ; ) {
-      if ( value == 1 ) {
-        return i;
-      } else if ( value == 3 ) {
-        return i << 2;
-      }
-      value >>= 1;
-      i <<= 1;
-    }
-  }
-
-  /**
-   * Method bytesPerPixel.
-   *
-   * @param format
-   * @param type
-   *
-   * @return int
-   */
-  protected static int bytesPerPixel(int format, int type) {
-    int n, m;
-
-    switch ( format ) {
-    case GL2.GL_COLOR_INDEX:
-    case GL2.GL_STENCIL_INDEX:
-    case GL2.GL_DEPTH_COMPONENT:
-    case GL2.GL_RED:
-    case GL2.GL_GREEN:
-    case GL2.GL_BLUE:
-    case GL2.GL_ALPHA:
-    case GL2.GL_LUMINANCE:
-      n = 1;
-      break;
-    case GL2.GL_LUMINANCE_ALPHA:
-      n = 2;
-      break;
-    case GL2.GL_RGB:
-    case GL2.GL_BGR:
-      n = 3;
-      break;
-    case GL2.GL_RGBA:
-    case GL2.GL_BGRA:
-      n = 4;
-      break;
-    default :
-      n = 0;
-    }
-
-    switch ( type ) {
-    case GL2.GL_UNSIGNED_BYTE:
-      m = 1;
-      break;
-    case GL2.GL_BYTE:
-      m = 1;
-      break;
-    case GL2.GL_BITMAP:
-      m = 1;
-      break;
-    case GL2.GL_UNSIGNED_SHORT:
-      m = 2;
-      break;
-    case GL2.GL_SHORT:
-      m = 2;
-      break;
-    case GL2.GL_UNSIGNED_INT:
-      m = 4;
-      break;
-    case GL2.GL_INT:
-      m = 4;
-      break;
-    case GL2.GL_FLOAT:
-      m = 4;
-      break;
-    default :
-      m = 0;
-    }
-
-    return n * m;
-  }
-
-  /**
-   * Convenience method for returning an int, rather than getting it out of a buffer yourself.
-   *
-   * @param what
-   *
-   * @return int
-   */
-  protected int glGetIntegerv(GL gl, int what) {
-    gl.glGetIntegerv(what, scratch, 0);
-    return scratch[0];
-  }
-}
diff --git a/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java b/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java
index f38b62e..b74d0a6 100644
--- a/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java
+++ b/src/jogl/classes/jogamp/opengl/glu/mipmap/Mipmap.java
@@ -149,7 +149,7 @@ public class Mipmap {
       case( GL2GL3.GL_LUMINANCE ):
       case( GL2GL3.GL_LUMINANCE_ALPHA ):
       case( GL2GL3.GL_BGR ):
-      case( GL2GL3.GL_BGRA ):
+      case( GL.GL_BGRA ):
         return( true );
       default:
         return( false );
@@ -227,7 +227,7 @@ public class Mipmap {
           type == GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV ||
           type == GL2GL3.GL_UNSIGNED_INT_10_10_10_2 ||
           type == GL2GL3.GL_UNSIGNED_INT_2_10_10_10_REV ) &&
-          (format != GL2GL3.GL_RGBA && format != GL2GL3.GL_BGRA) ) {
+          (format != GL.GL_RGBA && format != GL.GL_BGRA) ) {
             return( false );
     }
     return( true );
@@ -411,8 +411,8 @@ public class Mipmap {
         return( 3 );
       case( GL2GL3.GL_LUMINANCE_ALPHA ):
         return( 2 );
-      case( GL2GL3.GL_RGBA ):
-      case( GL2GL3.GL_BGRA ):
+      case( GL.GL_RGBA ):
+      case( GL.GL_BGRA ):
         return( 4 );
       default:
         return( 1 );
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java
index 77da265..3cd4b34 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLContext.java
@@ -142,6 +142,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
   @Override
   protected void resetStates() {
     // no inner state _cglExt = null;
+    cglExtProcAddressTable = null;
     super.resetStates();
   }
 
@@ -230,7 +231,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     }
     
     if (DEBUG) {
-      System.err.println("!!! Share context is " + toHexString(share) + " for " + this);
+      System.err.println("Share context is " + toHexString(share) + " for " + this);
     }
     return share;      
   }
@@ -278,14 +279,9 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     }
   }
 
-  protected void setSwapIntervalImpl(int interval) {
-    if( ! isCreated() ) {
-        throw new GLException("OpenGL context not created");
-    } 
-    if(!impl.setSwapInterval(interval)) {
-        throw new GLException("Error set swap-interval: "+this);        
-    }
-    currentSwapInterval = interval ;
+  @Override
+  protected boolean setSwapIntervalImpl(int interval) {
+    return impl.setSwapInterval(interval);
   }
 
   public ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3) {
@@ -298,7 +294,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
     final String key = "MacOSX-"+adevice.getUniqueID();
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! Initializing CGL extension address table: "+key);
+      System.err.println(getThreadName() + ": Initializing CGL extension address table: "+key);
     }
     ProcAddressTable table = null;
     synchronized(mappedContextTypeObjectLock) {
@@ -307,24 +303,22 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     if(null != table) {
         cglExtProcAddressTable = (CGLExtProcAddressTable) table;
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! GLContext CGL ProcAddressTable reusing key("+key+") -> "+table.hashCode());
+            System.err.println(getThreadName() + ": GLContext CGL ProcAddressTable reusing key("+key+") -> "+toHexString(table.hashCode()));
         }
     } else {
-        if (cglExtProcAddressTable == null) {
-          cglExtProcAddressTable = new CGLExtProcAddressTable(new GLProcAddressResolver());
-        }
+        cglExtProcAddressTable = new CGLExtProcAddressTable(new GLProcAddressResolver());
         resetProcAddressTable(getCGLExtProcAddressTable());
         synchronized(mappedContextTypeObjectLock) {
             mappedGLXProcAddress.put(key, getCGLExtProcAddressTable());
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext CGL ProcAddressTable mapping key("+key+") -> "+getCGLExtProcAddressTable().hashCode());
+                System.err.println(getThreadName() + ": GLContext CGL ProcAddressTable mapping key("+key+") -> "+toHexString(getCGLExtProcAddressTable().hashCode()));
             }
         }
     }
   }
     
-  protected final StringBuffer getPlatformExtensionsStringImpl() {
-    return new StringBuffer();
+  protected final StringBuilder getPlatformExtensionsStringImpl() {
+    return new StringBuilder();
   }
     
   public boolean isExtensionAvailable(String glExtensionName) {
@@ -366,7 +360,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
       destroyImpl();
       ((MacOSXCGLDrawable)drawable).setOpenGLMode(mode);
       if (DEBUG) {
-        System.err.println("Switching context mode " + openGLMode + " -> " + mode);
+        System.err.println("MacOSXCGLContext: Switching context mode " + openGLMode + " -> " + mode);
       }
       initOpenGLImpl(mode);
       openGLMode = mode;
@@ -388,7 +382,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
   }  
   
   public String toString() {
-    StringBuffer sb = new StringBuffer();
+    StringBuilder sb = new StringBuilder();
     sb.append(getClass().getSimpleName());
     sb.append(" [");
     super.append(sb);
@@ -402,10 +396,12 @@ public abstract class MacOSXCGLContext extends GLContextImpl
   class NSOpenGLImpl implements GLBackendImpl {
     long nsOpenGLLayer = 0;
     long nsOpenGLLayerPFmt = 0;
+    float screenVSyncTimeout; // microSec
+    int vsyncTimeout;    // microSec - for nsOpenGLLayer mode
     
     public boolean isNSContext() { return true; }
 
-    public long create(long share, int ctp, int major, int minor) {
+    public long create(long share, int ctp, int major, int minor) {        
         long ctx = 0;
         final MacOSXCGLDrawable drawable = (MacOSXCGLDrawable) MacOSXCGLContext.this.drawable;
         final NativeSurface surface = drawable.getNativeSurface();
@@ -414,17 +410,24 @@ public abstract class MacOSXCGLContext extends GLContextImpl
         final GLCapabilitiesImmutable chosenCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities();
         long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(chosenCaps, ctp, major, minor);
         if (pixelFormat == 0) {
-          throw new GLException("Unable to allocate pixel format with requested GLCapabilities");
+          if(DEBUG) {
+                System.err.println("Unable to allocate pixel format with requested GLCapabilities: "+chosenCaps);
+          }
+          return 0;
         }
         config.setChosenPixelFormat(pixelFormat);
+        int sRefreshRate = CGL.getScreenRefreshRate(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getIndex());
+        screenVSyncTimeout = 1000000f / (float)sRefreshRate;
         if(DEBUG) {
             System.err.println("NS create OSX>=lion "+isLionOrLater);
+            System.err.println("NS create backendType: "+drawable.getOpenGLMode());
             System.err.println("NS create backingLayerHost: "+backingLayerHost);
             System.err.println("NS create share: "+share);
             System.err.println("NS create chosenCaps: "+chosenCaps);
             System.err.println("NS create pixelFormat: "+toHexString(pixelFormat));
             System.err.println("NS create drawable native-handle: "+toHexString(drawable.getHandle()));
             System.err.println("NS create drawable NSView-handle: "+toHexString(drawable.getNSViewHandle()));
+            System.err.println("NS create screen refresh-rate: "+sRefreshRate+" hz, "+screenVSyncTimeout+" micros");
             // Thread.dumpStack();
         }
         try {
@@ -484,6 +487,7 @@ public abstract class MacOSXCGLContext extends GLContextImpl
                   System.err.println("NS create nsOpenGLLayer "+toHexString(nsOpenGLLayer)+", texSize "+texWidth+"x"+texHeight+", "+drawable);
               }
               backingLayerHost.attachSurfaceLayer(nsOpenGLLayer);
+              setSwapInterval(1); // enabled per default in layered surface
           }
         } finally {
           if(0!=pixelFormat) {
@@ -532,6 +536,14 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     }
 
     public boolean release(long ctx) {
+      try {
+          gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze
+      } catch (GLException gle) {
+          if(DEBUG) {
+            System.err.println("MacOSXCGLContext.NSOpenGLImpl.release: INFO: glFlush() catched exception:");
+            gle.printStackTrace();              
+          }
+      }
       final boolean res = CGL.clearCurrentContext(ctx);
       final long cglCtx = CGL.getCGLContext(ctx);
       if(0 == cglCtx) {
@@ -547,15 +559,18 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     public boolean setSwapInterval(int interval) {
       if(0 != nsOpenGLLayer) {
         CGL.setNSOpenGLLayerSwapInterval(nsOpenGLLayer, interval);
+        vsyncTimeout = interval * (int)screenVSyncTimeout;
+        if(DEBUG) { System.err.println("NS setSwapInterval: "+vsyncTimeout+" micros"); }
       }
       CGL.setSwapInterval(contextHandle, interval);
       return true;
     }
     
     public boolean swapBuffers() {
-      if(0 != nsOpenGLLayer) {
-        // sync w/ CALayer renderer - wait until next frame is required (v-sync)
-        CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, 16); // timeout 16ms -> 60Hz
+      if( 0 != nsOpenGLLayer ) {
+        // If v-sync is disabled, frames will be drawn as quickly as possible 
+        // w/o delay but in sync w/ CALayer. Otherwise wait until next swap interval (v-sync).        
+        CGL.waitUntilNSOpenGLLayerIsReady(nsOpenGLLayer, vsyncTimeout);
       }
       if(CGL.flushBuffer(contextHandle)) {
           if(0 != nsOpenGLLayer) {
@@ -635,6 +650,14 @@ public abstract class MacOSXCGLContext extends GLContextImpl
     }
 
     public boolean release(long ctx) {
+      try {
+          gl.glFlush(); // w/o glFlush()/glFinish() OSX < 10.7 (NVidia driver) may freeze
+      } catch (GLException gle) {
+          if(DEBUG) {
+            System.err.println("MacOSXCGLContext.CGLImpl.release: INFO: glFlush() catched exception:");
+            gle.printStackTrace();              
+          }
+      }
       int err = CGL.CGLSetCurrentContext(0);
       if(DEBUG && CGL.kCGLNoError != err) {
           System.err.println("CGL: Could not release current context: err 0x"+Integer.toHexString(err)+": "+this);
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java
index 12d480f..7b5efc3 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawable.java
@@ -106,7 +106,7 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl {
   }
 
   protected long getNSViewHandle() {
-      return GLBackendType.NSOPENGL == openGLMode ? getHandle() : null;
+      return GLBackendType.NSOPENGL == openGLMode ? getHandle() : 0;
   }
   
   protected void registerContext(MacOSXCGLContext ctx) {
@@ -151,7 +151,7 @@ public abstract class MacOSXCGLDrawable extends GLDrawableImpl {
     
       destroyImpl();
       if (DEBUG) {
-        System.err.println("Switching context mode " + openGLMode + " -> " + mode);
+        System.err.println("MacOSXCGLDrawable: Switching context mode " + openGLMode + " -> " + mode);
       }
       initOpenGLImpl(mode);
       openGLMode = mode;
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java
index 1e55879..b696e1b 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDrawableFactory.java
@@ -52,7 +52,6 @@ import javax.media.nativewindow.DefaultGraphicsScreen;
 import javax.media.nativewindow.NativeSurface;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.nativewindow.ProxySurface;
-import javax.media.nativewindow.macosx.MacOSXGraphicsDevice;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLCapabilitiesChooser;
@@ -63,7 +62,6 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 import javax.media.opengl.GLProfile.ShutdownType;
 
-import jogamp.nativewindow.WrappedSurface;
 import jogamp.opengl.DesktopGLDynamicLookupHelper;
 import jogamp.opengl.GLDrawableFactoryImpl;
 import jogamp.opengl.GLDrawableImpl;
@@ -71,6 +69,8 @@ import jogamp.opengl.GLDynamicLookupHelper;
 
 import com.jogamp.common.JogampRuntimeException;
 import com.jogamp.common.util.ReflectionUtil;
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice;
 
 public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
   private static DesktopGLDynamicLookupHelper macOSXCGLDynamicLookupHelper = null;
@@ -88,14 +88,17 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
                     gle.printStackTrace();
                 }
             }
-            macOSXCGLDynamicLookupHelper = tmp;
-            /** FIXME ?? 
-            if(null!=macOSXCGLDynamicLookupHelper) {
+            if(null!=tmp && tmp.isLibComplete()) {
+                macOSXCGLDynamicLookupHelper = tmp;
+                /** FIXME ?? 
                 CGL.getCGLProcAddressTable().reset(macOSXCGLDynamicLookupHelper);
-            } */
+                */
+            }
         }
     }
     
+    defaultDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT);
+    
     if(null!=macOSXCGLDynamicLookupHelper) {
         // Register our GraphicsConfigurationFactory implementations
         // The act of constructing them causes them to be registered
@@ -107,7 +110,6 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
             } catch (JogampRuntimeException jre) { /* n/a .. */ }
         }
     
-        defaultDevice = new MacOSXGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT);
         sharedMap = new HashMap<String, SharedResource>();
     }     
   }
@@ -141,7 +143,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
       boolean wasContextCreated;
       boolean hasNPOTTextures;
       boolean hasRECTTextures;
-      boolean hasAppletFloatPixels;
+      boolean hasAppleFloatPixels;
 
       SharedResource(MacOSXGraphicsDevice device, boolean wasContextCreated, 
                      boolean hasNPOTTextures, boolean hasRECTTextures, boolean hasAppletFloatPixels
@@ -152,13 +154,13 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
           this.wasContextCreated = wasContextCreated;
           this.hasNPOTTextures = hasNPOTTextures;
           this.hasRECTTextures = hasRECTTextures;
-          this.hasAppletFloatPixels = hasAppletFloatPixels;
+          this.hasAppleFloatPixels = hasAppletFloatPixels;
       }
       final MacOSXGraphicsDevice getDevice() { return device; }
       final boolean wasContextAvailable() { return wasContextCreated; }
       final boolean isNPOTTextureAvailable() { return hasNPOTTextures; }
       final boolean isRECTTextureAvailable() { return hasRECTTextures; }
-      final boolean isAppletFloatPixelsAvailable() { return hasAppletFloatPixels; }
+      final boolean isAppleFloatPixelsAvailable() { return hasAppleFloatPixels; }
   }
 
   public final AbstractGraphicsDevice getDefaultDevice() {
@@ -166,7 +168,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
   }
 
   public final boolean getIsDeviceCompatible(AbstractGraphicsDevice device) {
-      if(device instanceof MacOSXGraphicsDevice) {
+      if(null!=macOSXCGLDynamicLookupHelper && device instanceof MacOSXGraphicsDevice) {
           return true;
       }
       return false;
@@ -202,14 +204,15 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
         boolean madeCurrent = false;
         boolean hasNPOTTextures = false;
         boolean hasRECTTextures = false;
-        boolean hasAppletFloatPixels = false;
+        boolean hasAppleFloatPixels = false;
         {
-            GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP);
+            GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false);
             if (null == glp) {
                 throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice);
             }    
             final GLCapabilities caps = new GLCapabilities(glp);
             caps.setRedBits(5); caps.setGreenBits(5); caps.setBlueBits(5); caps.setAlphaBits(0);
+            caps.setDepthBits(5);
             caps.setDoubleBuffered(false);
             caps.setOnscreen(false);
             caps.setPBuffer(true);
@@ -226,29 +229,36 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
                             GL gl = context.getGL();
                             hasNPOTTextures = gl.isNPOTTextureAvailable();
                             hasRECTTextures = gl.isExtensionAvailable("GL_EXT_texture_rectangle");
-                            hasAppletFloatPixels = gl.isExtensionAvailable("GL_APPLE_float_pixels");
+                            hasAppleFloatPixels = gl.isExtensionAvailable("GL_APPLE_float_pixels");
                         }
                     } catch (GLException gle) {
                         if (DEBUG) {
-                            System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: makeCurrent failed");
+                            System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: makeCurrent catched exception:");
                             gle.printStackTrace();
                         }
                     } finally {
-                        context.release();
-                        context.destroy();
+                        try {
+                            context.destroy();
+                        } catch (GLException gle) {
+                            if (DEBUG) {
+                                System.err.println("MacOSXCGLDrawableFactory.createShared: INFO: destroy catched exception:");
+                                gle.printStackTrace();
+                            }                            
+                        }
                     }
                 }
                 drawable.destroy();
             }
         }
-        sr = new SharedResource(sharedDevice, madeCurrent, hasNPOTTextures, hasRECTTextures, hasAppletFloatPixels);
+        sr = new SharedResource(sharedDevice, madeCurrent, hasNPOTTextures, hasRECTTextures, hasAppleFloatPixels);
         synchronized(sharedMap) {
             sharedMap.put(connection, sr);
         }
         removeDeviceTried(connection);
         if (DEBUG) {
             System.err.println("MacOSXCGLDrawableFactory.createShared: device:  " + sharedDevice);
-            System.err.println("MacOSXCGLDrawableFactory.createShared: context: " + madeCurrent);
+            System.err.println("MacOSXCGLDrawableFactory.createShared: context: madeCurrent " + madeCurrent + ", NPOT "+hasNPOTTextures+
+                               ", RECT "+hasRECTTextures+", FloatPixels "+hasAppleFloatPixels);
         }                        
     }
     return sr;
@@ -266,7 +276,7 @@ public class MacOSXCGLDrawableFactory extends GLDrawableFactoryImpl {
         }
     } catch (GLException gle) {
         if(DEBUG) {
-            System.err.println("Catched Exception while MaxOSXCGL Shared Resource initialization");
+            System.err.println("Catched Exception while MaxOSXCGL Shared Resource initialization:");
             gle.printStackTrace();
         }
     }
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDynamicLibraryBundleInfo.java
index a5d3579..03ec94d 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLDynamicLibraryBundleInfo.java
@@ -36,6 +36,7 @@ public class MacOSXCGLDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBu
         super();
     }
 
+    @Override
     public List<List<String>> getToolLibNames() {
         final List<List<String>> libsList = new ArrayList<List<String>>();
         final List<String> libsGL = new ArrayList<String>();
@@ -45,6 +46,7 @@ public class MacOSXCGLDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBu
         return libsList;
     }
     
+    @Override
     public final List<String> getToolGetProcAddressFuncNameList() {
         return null; 
         /** OSX manual says: NSImage use is discouraged
@@ -53,6 +55,7 @@ public class MacOSXCGLDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBu
         return res; */
     }
 
+    @Override
     public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
         return 0;
         /** OSX manual says: NSImage use is discouraged
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java
index f552ab3..8393a68 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfiguration.java
@@ -46,9 +46,9 @@ import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
 
 import com.jogamp.common.nio.PointerBuffer;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
 
 public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable {
     long pixelformat;
@@ -78,10 +78,10 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration
     }
     
     static final int[] cglInternalAttributeToken = new int[] {
-        CGL.kCGLPFAOpenGLProfile,
-        CGL.kCGLPFAColorFloat,
+        CGL.kCGLPFAOpenGLProfile,    // >= lion
+        CGL.NSOpenGLPFAAccelerated,  // query only (prefer accelerated, but allow non accelerated), ignored for createPixelformat 
         CGL.NSOpenGLPFANoRecovery,
-        CGL.NSOpenGLPFAAccelerated,
+        CGL.kCGLPFAColorFloat,
         CGL.NSOpenGLPFAPixelBuffer,
         CGL.NSOpenGLPFADoubleBuffer,
         CGL.NSOpenGLPFAStereo,
@@ -109,17 +109,14 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration
               case CGL.kCGLPFAOpenGLProfile: 
                 ivalues[idx] = MacOSXCGLContext.GLProfile2CGLOGLProfileValue(ctp, major, minor);
                 break;
-              case CGL.kCGLPFAColorFloat:
-                ivalues[idx] = caps.getPbufferFloatingPointBuffers() ? 1 : 0;
-                break;
-
               case CGL.NSOpenGLPFANoRecovery:
                 ivalues[idx] = caps.getHardwareAccelerated() ? 1 : 0;
                 break;
-              case CGL.NSOpenGLPFAAccelerated:
-                ivalues[idx] = caps.getHardwareAccelerated() ? 1 : 0;
-                break;
                   
+              case CGL.kCGLPFAColorFloat:
+                ivalues[idx] = caps.getPbufferFloatingPointBuffers() ? 1 : 0;
+                break;
+
               case CGL.NSOpenGLPFAPixelBuffer:
                 ivalues[idx] = caps.isPBuffer() ? 1 : 0;
                 break;
@@ -287,14 +284,14 @@ public class MacOSXCGLGraphicsConfiguration extends MutableGraphicsConfiguration
         for (int i = 0; i < len; i++) {
           int attr = cglInternalAttributeToken[i+off];
           switch (attr) {
-              case CGL.kCGLPFAColorFloat:
-                caps.setPbufferFloatingPointBuffers(ivalues[i] != 0);
-                break;
-
               case CGL.NSOpenGLPFAAccelerated:
                 caps.setHardwareAccelerated(ivalues[i] != 0);
                 break;
                 
+              case CGL.kCGLPFAColorFloat:
+                caps.setPbufferFloatingPointBuffers(ivalues[i] != 0);
+                break;
+
               case CGL.NSOpenGLPFAPixelBuffer:
                 caps.setPBuffer(ivalues[i] != 0);
                 break;
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java
index 0de290c..1a9070a 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXCGLGraphicsConfigurationFactory.java
@@ -49,10 +49,8 @@ import javax.media.opengl.GLCapabilitiesImmutable;
     GraphicsDevice and GraphicsConfiguration abstractions. */
 
 public class MacOSXCGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    protected static final boolean DEBUG = jogamp.opengl.Debug.debug("GraphicsConfiguration");
-
     static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.macosx.MacOSXGraphicsDevice.class, new MacOSXCGLGraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice.class, new MacOSXCGLGraphicsConfigurationFactory());
     }
     private MacOSXCGLGraphicsConfigurationFactory() {        
     }
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java
index 6ce2d7b..58cea4a 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXExternalCGLContext.java
@@ -49,7 +49,8 @@ import javax.media.opengl.GLContext;
 import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLException;
 
-import jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.WrappedSurface;
+
 import jogamp.opengl.GLContextImpl;
 import jogamp.opengl.GLContextShareSet;
 import jogamp.opengl.macosx.cgl.MacOSXCGLDrawable.GLBackendType;
@@ -64,7 +65,7 @@ public class MacOSXExternalCGLContext extends MacOSXCGLContext {
     drawable.registerContext(this);
     this.contextHandle = handle;
     GLContextShareSet.contextCreated(this);
-    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY);
+    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT);
     getGLStateTracker().setEnabled(false); // external context usage can't track state in Java
   }
 
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java
index e02c3ef..1e49d1f 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/MacOSXPbufferCGLDrawable.java
@@ -129,6 +129,12 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable {
     
     if (DEBUG) {
         System.out.println("Pbuffer config: " + config);
+        if(null != sr) {
+            System.out.println("Pbuffer NPOT Texure  avail: "+sr.isNPOTTextureAvailable());
+            System.out.println("Pbuffer RECT Texture avail: "+sr.isRECTTextureAvailable());
+        } else {
+            System.out.println("Pbuffer no sr, no RECT/NPOT Texture avail");
+        }
     }
 
     if ( capabilities.getPbufferRenderToTextureRectangle() && null!=sr && sr.isRECTTextureAvailable() ) {
@@ -146,7 +152,7 @@ public class MacOSXPbufferCGLDrawable extends MacOSXCGLDrawable {
 
     int internalFormat = GL.GL_RGBA;
     if (capabilities.getPbufferFloatingPointBuffers()) {
-      if(!glProfile.isGL2GL3() || null==sr || sr.isAppletFloatPixelsAvailable()) {
+      if(!glProfile.isGL2GL3() || null==sr || sr.isAppleFloatPixelsAvailable()) {
           throw new GLException("Floating-point support (GL_APPLE_float_pixels) not available");
       }
       switch (capabilities.getRedBits()) {
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java
index a8c04ee..a6fa01b 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXAWTCGLGraphicsConfigurationFactory.java
@@ -44,22 +44,21 @@ import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.DefaultGraphicsScreen;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
-import javax.media.nativewindow.macosx.MacOSXGraphicsDevice;
 
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLException;
 
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
+import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice;
+
 import jogamp.opengl.macosx.cgl.MacOSXCGLGraphicsConfiguration;
 
 public class MacOSXAWTCGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    protected static final boolean DEBUG = jogamp.opengl.Debug.debug("GraphicsConfiguration");
-
     public static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.awt.AWTGraphicsDevice.class, new MacOSXAWTCGLGraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new MacOSXAWTCGLGraphicsConfigurationFactory());
     }    
     private MacOSXAWTCGLGraphicsConfigurationFactory() {
     }
diff --git a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXJava2DCGLContext.java b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXJava2DCGLContext.java
index 70416d1..f41400d 100644
--- a/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXJava2DCGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/macosx/cgl/awt/MacOSXJava2DCGLContext.java
@@ -97,7 +97,7 @@ public class MacOSXJava2DCGLContext extends MacOSXCGLContext implements Java2DGL
       }
       return false;
     }
-    setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); // use GL_VERSION
+    setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT); // use GL_VERSION
     contextHandle = ctx;
     return true;
   }
diff --git a/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java b/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java
new file mode 100644
index 0000000..31f1329
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/EGLMediaPlayerImpl.java
@@ -0,0 +1,169 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package jogamp.opengl.util.av;
+
+import java.nio.Buffer;
+import java.nio.IntBuffer;
+
+import javax.media.opengl.GL;
+
+import com.jogamp.common.nio.Buffers;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+import jogamp.opengl.egl.EGL;
+import jogamp.opengl.egl.EGLContext;
+import jogamp.opengl.egl.EGLDrawable;
+import jogamp.opengl.egl.EGLExt;
+
+public abstract class EGLMediaPlayerImpl extends GLMediaPlayerImpl {
+    final protected TextureType texType;
+    final protected boolean useKHRSync;
+    
+    public enum TextureType {
+        GL(0), KHRImage(1); 
+        
+        public final int id;
+
+        TextureType(int id){
+            this.id = id;
+        }
+    }    
+    
+    public static class EGLTextureFrame extends TextureSequence.TextureFrame {
+        
+        public EGLTextureFrame(Buffer clientBuffer, Texture t, long khrImage, long khrSync) {
+            super(t);
+            this.clientBuffer = clientBuffer;
+            this.image = khrImage;
+            this.sync = khrSync;
+        }
+        
+        public final Buffer getClientBuffer() { return clientBuffer; }
+        public final long getImage() { return image; }        
+        public final long getSync() { return sync; }
+        
+        public String toString() {
+            return "EGLTextureFrame[" + texture + ", img "+ image + ", sync "+ sync+", clientBuffer "+clientBuffer+"]";
+        }
+        protected final Buffer clientBuffer;
+        protected final long image;
+        protected final long sync;
+    }
+
+    
+    protected EGLMediaPlayerImpl() {
+        this(TextureType.GL, false);
+    }
+    
+    protected EGLMediaPlayerImpl(TextureType texType, boolean useKHRSync) {
+        super();
+        this.texType = texType;
+        this.useKHRSync = useKHRSync;
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        final Texture texture = super.createTexImageImpl(gl, idx, tex, width, height, false);
+        final Buffer clientBuffer;
+        final long image;
+        final long sync;
+        final boolean eglUsage = TextureType.KHRImage == texType || useKHRSync ; 
+        final EGLContext eglCtx;
+        final EGLExt eglExt;
+        final EGLDrawable eglDrawable;
+        
+        if(eglUsage) {
+            eglCtx = (EGLContext) gl.getContext();
+            eglExt = eglCtx.getEGLExt();
+            eglDrawable = (EGLDrawable) eglCtx.getGLDrawable();            
+        } else {
+            eglCtx = null;
+            eglExt = null;
+            eglDrawable = null;
+        }
+        
+        if(TextureType.KHRImage == texType) {
+            IntBuffer nioTmp = Buffers.newDirectIntBuffer(1);
+            // create EGLImage from texture
+            clientBuffer = null; // FIXME
+            nioTmp.put(0, EGL.EGL_NONE);
+            image =  eglExt.eglCreateImageKHR( eglDrawable.getDisplay(), eglCtx.getHandle(),
+                                               EGLExt.EGL_GL_TEXTURE_2D_KHR,
+                                               clientBuffer, nioTmp);
+            if (0==image) {
+                throw new RuntimeException("EGLImage creation failed: "+EGL.eglGetError()+", ctx "+eglCtx+", tex "+tex[idx]+", err "+toHexString(EGL.eglGetError()));
+            }
+        } else {
+            clientBuffer = null;
+            image = 0;
+        }
+
+        if(useKHRSync) {
+            int[] tmp = new int[1];
+            // Create sync object so that we can be sure that gl has finished
+            // rendering the EGLImage texture before we tell OpenMAX to fill
+            // it with a new frame.
+            tmp[0] = EGL.EGL_NONE;
+            sync = eglExt.eglCreateSyncKHR(eglDrawable.getDisplay(), EGLExt.EGL_SYNC_FENCE_KHR, tmp, 0);
+            if (0==sync) {
+                throw new RuntimeException("EGLSync creation failed: "+EGL.eglGetError()+", ctx "+eglCtx+", err "+toHexString(EGL.eglGetError()));
+            }
+        } else {
+            sync = 0;
+        }
+        return new EGLTextureFrame(clientBuffer, texture, image, sync);
+    }
+    
+    @Override
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        final boolean eglUsage = TextureType.KHRImage == texType || useKHRSync ; 
+        final EGLContext eglCtx;
+        final EGLExt eglExt;
+        final EGLDrawable eglDrawable;
+        
+        if(eglUsage) {
+            eglCtx = (EGLContext) gl.getContext();
+            eglExt = eglCtx.getEGLExt();
+            eglDrawable = (EGLDrawable) eglCtx.getGLDrawable();            
+        } else {
+            eglCtx = null;
+            eglExt = null;
+            eglDrawable = null;
+        }
+        final EGLTextureFrame eglTex = (EGLTextureFrame) imgTex;
+        
+        if(0!=eglTex.getImage()) {
+            eglExt.eglDestroyImageKHR(eglDrawable.getDisplay(), eglTex.getImage());
+        }
+        if(0!=eglTex.getSync()) {
+            eglExt.eglDestroySyncKHR(eglDrawable.getDisplay(), eglTex.getSync());
+        }
+        super.destroyTexImage(gl, imgTex);
+    }
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/av/GLMediaPlayerImpl.java b/src/jogl/classes/jogamp/opengl/util/av/GLMediaPlayerImpl.java
new file mode 100644
index 0000000..d3d45e6
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/GLMediaPlayerImpl.java
@@ -0,0 +1,575 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package jogamp.opengl.util.av;
+
+import java.io.IOException;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2;
+import javax.media.opengl.GLES2;
+import javax.media.opengl.GLException;
+
+import com.jogamp.opengl.util.av.GLMediaPlayer;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+/**
+ * After object creation an implementation may customize the behavior:
+ * <ul>
+ *   <li>{@link #setTextureCount(int)}</li>
+ *   <li>{@link #setTextureTarget(int)}</li>
+ *   <li>{@link EGLMediaPlayerImpl#setEGLTexImageAttribs(boolean, boolean)}.</li>
+ * </ul>
+ * 
+ * <p>
+ * See {@link GLMediaPlayer}.
+ * </p>
+ */
+public abstract class GLMediaPlayerImpl implements GLMediaPlayer {
+
+    protected static final String unknown = "unknown";
+
+    protected State state;
+    protected int textureCount;
+    protected int textureTarget;
+    protected int textureFormat;
+    protected int textureType;
+    protected int texUnit;
+    
+    
+    protected int[] texMinMagFilter = { GL.GL_NEAREST, GL.GL_NEAREST };
+    protected int[] texWrapST = { GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE };
+    
+    protected URLConnection urlConn = null;
+    
+    protected float playSpeed = 1.0f;
+    
+    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int width = 0;
+    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int height = 0;
+    /** Video fps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected float fps = 0;
+    /** Stream bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int bps_stream = 0;
+    /** Video bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int bps_video = 0;
+    /** Audio bps. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int bps_audio = 0;
+    /** In frames. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int totalFrames = 0;
+    /** In ms. Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected int duration = 0;
+    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected String acodec = unknown;
+    /** Shall be set by the {@link #initGLStreamImpl(GL, int[])} method implementation. */
+    protected String vcodec = unknown;
+    
+    protected int frameNumber = 0;
+    
+    protected TextureSequence.TextureFrame[] texFrames = null;
+    protected HashMap<Integer, TextureSequence.TextureFrame> texFrameMap = new HashMap<Integer, TextureSequence.TextureFrame>();
+    private ArrayList<GLMediaEventListener> eventListeners = new ArrayList<GLMediaEventListener>();
+
+    protected GLMediaPlayerImpl() {
+        this.textureCount=3;
+        this.textureTarget=GL.GL_TEXTURE_2D;
+        this.textureFormat = GL.GL_RGBA;
+        this.textureType = GL.GL_UNSIGNED_BYTE;        
+        this.texUnit = 0;
+        this.state = State.Uninitialized;
+    }
+
+    @Override
+    public void setTextureUnit(int u) { texUnit = u; }
+    
+    @Override
+    public int getTextureUnit() { return texUnit; }
+    
+    protected final void setTextureCount(int textureCount) {
+        this.textureCount=textureCount;
+    }
+    @Override
+    public final int getTextureCount() { return textureCount; }
+    
+    protected final void setTextureTarget(int target) { textureTarget=target; }
+    protected final void setTextureFormat(int f) { textureFormat=f; }    
+    protected final void setTextureType(int t) { textureType=t; }
+
+    public final void setTextureMinMagFilter(int[] minMagFilter) { texMinMagFilter[0] = minMagFilter[0]; texMinMagFilter[1] = minMagFilter[1];}
+    public final int[] getTextureMinMagFilter() { return texMinMagFilter; }
+    
+    public final void setTextureWrapST(int[] wrapST) { texWrapST[0] = wrapST[0]; texWrapST[1] = wrapST[1];}
+    public final int[] getTextureWrapST() { return texWrapST; }
+
+    @Override
+    public final TextureSequence.TextureFrame getLastTexture() throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        return getLastTextureImpl();
+    }
+    protected abstract TextureSequence.TextureFrame getLastTextureImpl();
+    
+    @Override
+    public final synchronized TextureSequence.TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        if(State.Playing == state) {
+            final TextureSequence.TextureFrame f = getNextTextureImpl(gl, blocking);
+            return f;
+        }
+        return getLastTextureImpl();        
+    }
+    protected abstract TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking);
+    
+    @Override
+    public String getRequiredExtensionsShaderStub() throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        if(GLES2.GL_TEXTURE_EXTERNAL_OES == textureTarget) {
+            return TextureSequence.GL_OES_EGL_image_external_Required_Prelude;
+        }
+        return "";
+    }
+        
+    @Override
+    public String getTextureSampler2DType() throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        switch(textureTarget) {
+            case GL.GL_TEXTURE_2D:
+            case GL2.GL_TEXTURE_RECTANGLE: 
+                return TextureSequence.sampler2D;
+            case GLES2.GL_TEXTURE_EXTERNAL_OES:
+                return TextureSequence.samplerExternalOES;
+            default:
+                throw new GLException("Unsuported texture target: "+toHexString(textureTarget));            
+        }
+    }
+    
+    /**
+     * {@inheritDoc}
+     * 
+     * This implementation simply returns the build-in function name of <code>texture2D</code>,
+     * if not overridden by specialization.
+     */
+    @Override
+    public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        return "texture2D";
+    }
+    
+    /**
+     * {@inheritDoc}
+     * 
+     * This implementation simply returns an empty string since it's using 
+     * the build-in function <code>texture2D</code>,
+     * if not overridden by specialization.
+     */
+    @Override
+    public String getTextureLookupFragmentShaderImpl() throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        return ""; 
+    }
+    
+    @Override
+    public final synchronized float getPlaySpeed() {
+        return playSpeed;
+    }
+    
+    @Override
+    public final synchronized void setPlaySpeed(float rate) {
+        if(State.Uninitialized != state && setPlaySpeedImpl(rate)) {
+            playSpeed = rate;
+        }
+        if(DEBUG) { System.err.println("SetPlaySpeed: "+toString()); }
+    }
+    protected abstract boolean setPlaySpeedImpl(float rate);
+
+    public final State start() {
+        switch(state) {
+            case Stopped:
+            case Paused:
+                if(startImpl()) {
+                    state = State.Playing;
+                }
+        }
+        if(DEBUG) { System.err.println("Start: "+toString()); }
+        return state;
+    }
+    protected abstract boolean startImpl();
+    
+    public final State pause() {
+        if(State.Playing == state && pauseImpl()) {
+            state = State.Paused;
+        }
+        if(DEBUG) { System.err.println("Pause: "+toString()); }            
+        return state;
+    }
+    protected abstract boolean pauseImpl();
+    
+    public final State stop() {
+        switch(state) {
+            case Playing:
+            case Paused:
+                if(stopImpl()) {
+                    state = State.Stopped;
+                }
+        }
+        if(DEBUG) { System.err.println("Stop: "+toString()); }
+        return state;
+    }
+    protected abstract boolean stopImpl();
+    
+    @Override
+    public final int getCurrentPosition() {
+        if(State.Uninitialized != state) {
+            return getCurrentPositionImpl();
+        }
+        return 0;
+    }
+    protected abstract int getCurrentPositionImpl();
+    
+    public final int seek(int msec) {
+        final int cp;
+        switch(state) {
+            case Stopped:
+            case Playing:
+            case Paused:
+                cp = seekImpl(msec);
+                break;
+            default:
+                cp = 0;
+        }
+        if(DEBUG) { System.err.println("Seek("+msec+"): "+toString()); }
+        return cp;        
+    }
+    protected abstract int seekImpl(int msec);
+    
+    public final State getState() { return state; }
+    
+    @Override
+    public final State initGLStream(GL gl, URLConnection urlConn) throws IllegalStateException, GLException, IOException {
+        if(State.Uninitialized != state) {
+            throw new IllegalStateException("Instance not in state "+State.Uninitialized+", but "+state+", "+this);
+        }
+        this.urlConn = urlConn;
+        if (this.urlConn != null) {
+            try {                
+                if(null != gl) {
+                    if(null!=texFrames) {
+                        // re-init ..
+                        removeAllImageTextures(gl);
+                    } else {
+                        texFrames = new TextureSequence.TextureFrame[textureCount];
+                    }
+                    final int[] tex = new int[textureCount];
+                    {
+                        gl.glGenTextures(textureCount, tex, 0);
+                        final int err = gl.glGetError();
+                        if( GL.GL_NO_ERROR != err ) {
+                            throw new RuntimeException("TextureNames creation failed (num: "+textureCount+"): err "+toHexString(err));
+                        }
+                    }
+                    initGLStreamImpl(gl, tex);
+                    
+                    for(int i=0; i<textureCount; i++) {
+                        final TextureSequence.TextureFrame tf = createTexImage(gl, i, tex); 
+                        texFrames[i] = tf;
+                        texFrameMap.put(tex[i], tf);
+                    }
+                }
+                state = State.Stopped;
+                return state;
+            } catch (Throwable t) {
+                throw new GLException("Error initializing GL resources", t);
+            }
+        }
+        return state;        
+    }
+    
+    /**
+     * Implementation shall set the following set of data here 
+     * @param gl TODO
+     * @param texNames TODO
+     * @see #width
+     * @see #height
+     * @see #fps
+     * @see #bps_stream
+     * @see #totalFrames
+     * @see #acodec
+     * @see #vcodec
+    */
+    protected abstract void initGLStreamImpl(GL gl, int[] texNames) throws IOException;
+    
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        return new TextureSequence.TextureFrame( createTexImageImpl(gl, idx, tex, width, height, false) );
+    }
+    
+    protected Texture createTexImageImpl(GL gl, int idx, int[] tex, int tWidth, int tHeight, boolean mustFlipVertically) {
+        if( 0 > tex[idx] ) {
+            throw new RuntimeException("TextureName "+toHexString(tex[idx])+" invalid.");
+        }
+        gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit());
+        gl.glBindTexture(textureTarget, tex[idx]);
+        {
+            final int err = gl.glGetError();
+            if( GL.GL_NO_ERROR != err ) {
+                throw new RuntimeException("Couldn't bind textureName "+toHexString(tex[idx])+" to 2D target, err "+toHexString(err));
+            }
+        }
+
+        if(GLES2.GL_TEXTURE_EXTERNAL_OES != textureTarget) {
+            // create space for buffer with a texture
+            gl.glTexImage2D(
+                    textureTarget,    // target
+                    0,                // level
+                    GL.GL_RGBA,       // internal format
+                    tWidth,            // width
+                    tHeight,           // height
+                    0,                // border
+                    textureFormat,
+                    textureType,
+                    null);            // pixels -- will be provided later
+            {
+                final int err = gl.glGetError();
+                if( GL.GL_NO_ERROR != err ) {
+                    throw new RuntimeException("Couldn't create TexImage2D RGBA "+tWidth+"x"+tHeight+", err "+toHexString(err));
+                }
+            }
+            if(DEBUG) {
+                System.err.println("Created TexImage2D RGBA "+tWidth+"x"+tHeight+", target "+toHexString(textureTarget)+
+                                   ", ifmt "+toHexString(GL.GL_RGBA)+", fmt "+toHexString(textureFormat)+", type "+toHexString(textureType));
+            }
+        }
+        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MIN_FILTER, texMinMagFilter[0]);
+        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MAG_FILTER, texMinMagFilter[1]);        
+        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_S, texWrapST[0]);
+        gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_T, texWrapST[1]);
+        
+        return com.jogamp.opengl.util.texture.TextureIO.newTexture(tex[idx],
+                     textureTarget,
+                     tWidth, tHeight,
+                     width,  height,
+                     mustFlipVertically);        
+    }
+    
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        imgTex.getTexture().destroy(gl);        
+    }
+    
+    protected void removeAllImageTextures(GL gl) {
+        if(null != texFrames) {
+            for(int i=0; i<textureCount; i++) {
+                final TextureSequence.TextureFrame imgTex = texFrames[i];
+                if(null != imgTex) {
+                    destroyTexImage(gl, imgTex);
+                    texFrames[i] = null;
+                }
+            }
+        }
+        texFrameMap.clear();
+    }
+
+    protected final void updateAttributes(int width, int height, int bps_stream, int bps_video, int bps_audio, 
+                                          float fps, int totalFrames, int duration, 
+                                          String vcodec, String acodec) {
+        int event_mask = 0;
+        if( this.width != width || this.height != height ) {
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_SIZE;
+            this.width = width;
+            this.height = height;
+        }   
+        if( this.fps != fps ) {
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_FPS;
+            this.fps = fps;
+        }
+        if( this.bps_stream != bps_stream || this.bps_video != bps_video || this.bps_audio != bps_audio ) {
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_BPS;
+            this.bps_stream = bps_stream;
+            this.bps_video = bps_video;
+            this.bps_audio = bps_audio;
+        }
+        if( this.totalFrames != totalFrames || this.duration != duration ) {
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_LENGTH;
+            this.totalFrames = totalFrames;
+            this.duration = duration;
+        }
+        if( (null!=acodec && acodec.length()>0 && !this.acodec.equals(acodec)) ) { 
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_CODEC;
+            this.acodec = acodec;
+        }
+        if( (null!=vcodec && vcodec.length()>0 && !this.vcodec.equals(vcodec)) ) {
+            event_mask |= GLMediaEventListener.EVENT_CHANGE_CODEC;
+            this.vcodec = vcodec;
+        }
+        if(0==event_mask) {
+            return;
+        }
+        attributesUpdated(event_mask);    
+    }
+
+    protected final void attributesUpdated(int event_mask) {
+        synchronized(eventListenersLock) {
+            for(Iterator<GLMediaEventListener> i = eventListeners.iterator(); i.hasNext(); ) {
+                i.next().attributesChanges(this, event_mask, System.currentTimeMillis());
+            }
+        }
+    }
+    protected final void newFrameAvailable() {
+        frameNumber++;        
+        synchronized(eventListenersLock) {
+            for(Iterator<GLMediaEventListener> i = eventListeners.iterator(); i.hasNext(); ) {
+                i.next().newFrameAvailable(this, System.currentTimeMillis());
+            }
+        }
+    }
+    
+    @Override
+    public final synchronized State destroy(GL gl) {
+        destroyImpl(gl);
+        removeAllImageTextures(gl);
+        state = State.Uninitialized;
+        return state;
+    }
+    protected abstract void destroyImpl(GL gl);
+
+    @Override
+    public final synchronized URLConnection getURLConnection() {
+        return urlConn;
+    }
+
+    @Override
+    public final synchronized String getVideoCodec() {
+        return vcodec;
+    }
+
+    @Override
+    public final synchronized String getAudioCodec() {
+        return acodec;
+    }
+
+    @Override
+    public final synchronized long getTotalFrames() {
+        return totalFrames;
+    }
+
+    @Override
+    public final synchronized int getDuration() {
+        return duration;
+    }
+    
+    @Override
+    public final synchronized long getStreamBitrate() {
+        return bps_stream;
+    }
+
+    @Override
+    public final synchronized int getVideoBitrate() {
+        return bps_video;
+    }
+    
+    @Override
+    public final synchronized int getAudioBitrate() {
+        return bps_audio;
+    }
+    
+    @Override
+    public final synchronized float getFramerate() {
+        return fps;
+    }
+
+    @Override
+    public final synchronized int getWidth() {
+        return width;
+    }
+
+    @Override
+    public final synchronized int getHeight() {
+        return height;
+    }
+
+    @Override
+    public final synchronized String toString() {
+        final float ct = getCurrentPosition() / 1000.0f, tt = getDuration() / 1000.0f;
+        final String loc = ( null != urlConn ) ? urlConn.getURL().toExternalForm() : "<undefined stream>" ;
+        return "GLMediaPlayer["+state+", "+frameNumber+"/"+totalFrames+" frames, "+ct+"/"+tt+"s, speed "+playSpeed+", "+bps_stream+" bps, "+
+                "Texture[count "+textureCount+", target "+toHexString(textureTarget)+", format "+toHexString(textureFormat)+", type "+toHexString(textureType)+"], "+               
+               "Stream[Video[<"+vcodec+">, "+width+"x"+height+", "+fps+" fps, "+bps_video+" bsp], "+
+               "Audio[<"+acodec+">, "+bps_audio+" bsp]], "+loc+"]";
+    }
+
+    @Override
+    public final void addEventListener(GLMediaEventListener l) {
+        if(l == null) {
+            return;
+        }
+        synchronized(eventListenersLock) {
+            eventListeners.add(l);
+        }
+    }
+
+    @Override
+    public final void removeEventListener(GLMediaEventListener l) {
+        if (l == null) {
+            return;
+        }
+        synchronized(eventListenersLock) {
+            eventListeners.remove(l);
+        }
+    }
+
+    @Override
+    public final synchronized GLMediaEventListener[] getEventListeners() {
+        synchronized(eventListenersLock) {
+            return eventListeners.toArray(new GLMediaEventListener[eventListeners.size()]);
+        }
+    }
+
+    private Object eventListenersLock = new Object();
+
+    protected static final String toHexString(long v) {
+        return "0x"+Long.toHexString(v);
+    }
+    protected static final String toHexString(int v) {
+        return "0x"+Integer.toHexString(v);
+    }
+        
+}
\ No newline at end of file
diff --git a/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java
new file mode 100644
index 0000000..3d740d6
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/NullGLMediaPlayer.java
@@ -0,0 +1,173 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package jogamp.opengl.util.av;
+
+import java.io.IOException;
+import java.net.URLConnection;
+import java.nio.ByteBuffer;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GLProfile;
+
+import jogamp.opengl.util.av.GLMediaPlayerImpl;
+
+import com.jogamp.common.nio.Buffers;
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureData;
+import com.jogamp.opengl.util.texture.TextureIO;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+/***
+ * A dummy null media player implementation using a static test frame
+ * available on all platforms.
+ */
+public class NullGLMediaPlayer extends GLMediaPlayerImpl {
+    private TextureData texData = null;
+    private TextureSequence.TextureFrame frame = null;
+    private int pos_ms = 0;
+    private int pos_start = 0;
+    
+    public NullGLMediaPlayer() {
+        super();
+        this.setTextureCount(1);
+    }
+
+    @Override
+    protected boolean setPlaySpeedImpl(float rate) {
+        return false;
+    }
+
+    @Override
+    protected boolean startImpl() {
+        pos_start = (int)System.currentTimeMillis();
+        return true;
+    }
+
+    @Override
+    protected boolean pauseImpl() {
+        return true;
+    }
+
+    @Override
+    protected boolean stopImpl() {
+        return true;
+    }
+    
+    @Override
+    protected int seekImpl(int msec) {
+        pos_ms = msec;
+        validatePos();
+        return pos_ms;
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame getLastTextureImpl() {
+        return frame;
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) {
+        return frame;
+    }
+    
+    @Override
+    protected int getCurrentPositionImpl() {
+        pos_ms = (int)System.currentTimeMillis() - pos_start;
+        validatePos();
+        return pos_ms;
+    }
+
+    @Override
+    protected void destroyImpl(GL gl) {
+    }
+    
+    @Override
+    protected void initGLStreamImpl(GL gl, int[] texNames) throws IOException {
+        try {
+            URLConnection urlConn = IOUtil.getResource("jogl/util/data/av/test-ntsc01-160x90.png", NullGLMediaPlayer.class.getClassLoader());
+            if(null != urlConn) {
+                texData = TextureIO.newTextureData(GLProfile.getGL2ES2(), urlConn.getInputStream(), false, TextureIO.PNG);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if(null != texData) {
+            width = texData.getWidth();
+            height = texData.getHeight();            
+        } else {
+            width = 640;
+            height = 480;
+            ByteBuffer buffer = Buffers.newDirectByteBuffer(width*height*4);
+            while(buffer.hasRemaining()) {
+                buffer.put((byte) 0xEA); buffer.put((byte) 0xEA); buffer.put((byte) 0xEA); buffer.put((byte) 0xEA);
+            }
+            buffer.rewind();
+            texData = new TextureData(GLProfile.getGL2ES2(),
+                   GL.GL_RGBA, width, height, 0,
+                   GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, false, 
+                   false, false, buffer, null);
+        }
+        fps = 24f;
+        duration = 10*60*1000; // msec
+        totalFrames = (int) ( (duration/1000)*fps );
+        vcodec = "png-static";
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        Texture texture = super.createTexImageImpl(gl, idx, tex, width, height, false);
+        if(null != texData) {
+            texture.updateImage(gl, texData);
+            texData.destroy();
+            texData = null;
+        }                      
+        frame = new TextureSequence.TextureFrame( texture );
+        return frame;
+    }
+    
+    @Override
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        frame = null;
+        super.destroyTexImage(gl, imgTex);
+    }
+    
+    private void validatePos() {
+        boolean considerPausing = false;
+        if( 0 > pos_ms) {
+            pos_ms = 0;
+            considerPausing = true;
+        } else if ( pos_ms > getDuration() ) {
+            pos_ms = getDuration();
+            considerPausing = true;
+        }
+        if(considerPausing && state == State.Playing) {
+            state = State.Paused;
+        }
+    }
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java
new file mode 100644
index 0000000..ce9df21
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGDynamicLibraryBundleInfo.java
@@ -0,0 +1,270 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+ 
+package jogamp.opengl.util.av.impl;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.media.opengl.GLProfile;
+
+import com.jogamp.common.os.DynamicLibraryBundle;
+import com.jogamp.common.os.DynamicLibraryBundleInfo;
+import com.jogamp.common.util.RunnableExecutor;
+
+/**
+ * FIXME: We need native structure access methods to deal with API changes
+ *        in the libav headers, which break binary compatibility!
+ *        Currently we are binary compatible w/ [0.6 ?, ] 0.7 and 0.8 but not w/ trunk.
+ *        
+ *        ChangeList for trunk:
+ *          Thu Jan 12 11:21:02 2012 a17479dfce67fbea2d0a1bf303010dce1e79059f major 53 -> 54
+ *          Mon Feb 27 22:40:11 2012 ee42df8a35c2b795f524c856834d0823dbd4e75d reorder AVStream and AVFormatContext
+ *          Tue Feb 28 12:07:53 2012 322537478b63c6bc01e640643550ff539864d790 minor  1 ->  2
+ */
+class FFMPEGDynamicLibraryBundleInfo implements DynamicLibraryBundleInfo  {
+    private static List<String> glueLibNames = new ArrayList<String>(); // none
+    
+    private static final int symbolCount = 31;
+    private static String[] symbolNames = {
+         "avcodec_version",
+         "avformat_version",
+/* 3 */  "avutil_version",
+        
+         // libavcodec
+         "avcodec_close", 
+         "avcodec_string", 
+         "avcodec_find_decoder", 
+         "avcodec_open2",             // 53.6.0    (opt) 
+         "avcodec_open", 
+         "avcodec_alloc_frame", 
+         "avcodec_default_get_buffer", 
+         "avcodec_default_release_buffer", 
+         "av_free_packet", 
+         "avcodec_decode_audio4",     // 53.25.0   (opt)
+         "avcodec_decode_audio3",     // 52.23.0
+/* 15 */ "avcodec_decode_video2",     // 52.23.0
+        
+         // libavutil
+         "av_pix_fmt_descriptors", 
+         "av_free", 
+/* 18 */ "av_get_bits_per_pixel",
+        
+         // libavformat
+         "avformat_alloc_context",
+         "avformat_free_context",     // 52.96.0   (opt)
+         "avformat_close_input",      // 53.17.0   (opt)
+         "av_close_input_file",
+         "av_register_all", 
+         "avformat_open_input", 
+         "av_dump_format", 
+         "av_read_frame",
+         "av_seek_frame",
+         "avformat_network_init",     // 53.13.0   (opt)
+         "avformat_network_deinit",   // 53.13.0   (opt)
+         "avformat_find_stream_info", // 53.3.0    (opt)
+/* 29 */ "av_find_stream_info",
+    };
+    
+    // alternate symbol names
+    private static String[][] altSymbolNames = {
+        { "avcodec_open",          "avcodec_open2" },              // old, 53.6.0
+        { "avcodec_decode_audio3", "avcodec_decode_audio4" },      // old, 53.25.0
+        { "av_close_input_file",   "avformat_close_input" },       // old, 53.17.0
+        { "av_find_stream_info",   "avformat_find_stream_info" },  // old, 53.3.0       
+    };
+    
+    // optional symbol names
+    private static String[] optionalSymbolNames = {
+         "avformat_free_context",     // 52.96.0   (opt)
+         "avformat_network_init",     // 53.13.0   (opt)
+         "avformat_network_deinit",   // 53.13.0   (opt)
+    };
+    
+    private static long[] symbolAddr;
+    private static final boolean ready;
+    
+    static {
+        // native ffmpeg media player implementation is included in jogl_desktop and jogl_mobile     
+        GLProfile.initSingleton();
+        boolean _ready = false;
+        try {
+            _ready = initSymbols();
+        } catch (Throwable t) {
+            t.printStackTrace();
+        }
+        ready = _ready;
+        if(!ready) {
+            System.err.println("FFMPEG: Not Available");
+        }
+    }
+    
+    static boolean initSingleton() { return ready; }
+    
+    private static boolean initSymbols() {
+        final DynamicLibraryBundle dl = new DynamicLibraryBundle(new FFMPEGDynamicLibraryBundleInfo());
+        final boolean avutilLoaded = dl.isToolLibLoaded(0); 
+        final boolean avformatLoaded = dl.isToolLibLoaded(1);
+        final boolean avcodecLoaded = dl.isToolLibLoaded(2);
+        if(!avutilLoaded || !avformatLoaded || !avcodecLoaded) {
+            throw new RuntimeException("FFMPEG Tool library incomplete: [ avutil "+avutilLoaded+", avformat "+avformatLoaded+", avcodec "+avcodecLoaded+"]");
+        }        
+        if(!dl.isToolLibComplete()) {
+            throw new RuntimeException("FFMPEG Tool libraries incomplete");
+        }
+        if(symbolNames.length != symbolCount) {
+            throw new InternalError("XXX0 "+symbolNames.length+" != "+symbolCount);
+        }
+        symbolAddr = new long[symbolCount];        
+        
+        // optional symbol name set
+        final Set<String> optionalSymbolNameSet = new HashSet<String>();
+        optionalSymbolNameSet.addAll(Arrays.asList(optionalSymbolNames));
+        
+        // alternate symbol name mapping to indexed array
+        final Map<String, Integer> mAltSymbolNames = new HashMap<String, Integer>();
+        final int[][] iAltSymbolNames = new int[altSymbolNames.length][];
+        {
+            final List<String> symbolNameList = Arrays.asList(symbolNames);
+            for(int i=0; i<altSymbolNames.length; i++) {
+                iAltSymbolNames[i] = new int[altSymbolNames[i].length];        
+                for(int j=0; j<altSymbolNames[i].length; j++) {
+                    mAltSymbolNames.put(altSymbolNames[i][j], new Integer(i));
+                    iAltSymbolNames[i][j] = symbolNameList.indexOf(altSymbolNames[i][j]); 
+                }            
+            }
+        }
+        
+        // lookup
+        for(int i = 0; i<symbolCount; i++) {
+            symbolAddr[i] = dl.dynamicLookupFunction(symbolNames[i]);
+        }        
+        
+        // validate results
+        for(int i = 0; i<symbolCount; i++) {
+            if( 0 == symbolAddr[i] ) {
+                // no symbol, check optional and alternative symbols
+                final String symbol = symbolNames[i];
+                if ( !optionalSymbolNameSet.contains(symbol) ) {
+                    // check for API changed symbols
+                    boolean ok = false;                    
+                    final Integer cI = mAltSymbolNames.get(symbol);
+                    if ( null != cI ) {
+                        // check whether alternative symbol is available
+                        final int ci = cI.intValue();
+                        for(int j=0; !ok && j<iAltSymbolNames[ci].length; j++) {
+                            final int si = iAltSymbolNames[ci][j];
+                            ok = 0 != symbolAddr[si];
+                            if(ok && (true || DEBUG )) { // keep it verbose per default for now ..
+                                System.err.println("OK: Unresolved symbol <"+symbol+">, but has alternative <"+symbolNames[si]+">");
+                            }
+                        }
+                    }
+                    if(!ok) {
+                        System.err.println("Fail: Could not resolve symbol <"+symbolNames[i]+">: not optional, no alternatives.");
+                        return false;
+                    }
+                } else if(true || DEBUG ) { // keep it verbose per default for now ..
+                    System.err.println("OK: Unresolved optional symbol <"+symbolNames[i]+">");
+                }
+            }
+        }
+        return initSymbols0(symbolAddr, symbolCount);
+    }
+    
+    protected FFMPEGDynamicLibraryBundleInfo() {
+    }
+
+    @Override
+    public boolean shallLinkGlobal() { return true; }
+
+    @Override
+    public boolean shallLookupGlobal() { return true; }
+    
+    @Override
+    public final List<String> getGlueLibNames() {
+        return glueLibNames;
+    }
+
+    @Override
+    public List<List<String>> getToolLibNames() {
+        List<List<String>> libsList = new ArrayList<List<String>>();
+
+        final List<String> avutil = new ArrayList<String>();
+        avutil.add("avutil");        // default
+        avutil.add("avutil-52");     // dummy future proof
+        avutil.add("avutil-51");     // 0.8
+        avutil.add("avutil-50");     // 0.7
+        libsList.add(avutil);
+        
+        final List<String> avformat = new ArrayList<String>();
+        avformat.add("avformat");    // default
+        avformat.add("avformat-55"); // dummy future proof
+        avformat.add("avformat-54"); // 0.?
+        avformat.add("avformat-53"); // 0.8
+        avformat.add("avformat-52"); // 0.7
+        libsList.add(avformat);
+        
+        final List<String> avcodec = new ArrayList<String>();
+        avcodec.add("avcodec");      // default
+        avcodec.add("avcodec-55");   // dummy future proof
+        avcodec.add("avcodec-54");   // 0.?
+        avcodec.add("avcodec-53");   // 0.8
+        avcodec.add("avcodec-52");   // 0.7
+        libsList.add(avcodec);
+                
+        return libsList;
+    }
+
+    @Override
+    public final List<String> getToolGetProcAddressFuncNameList() {
+        return null;
+    }
+
+    @Override
+    public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
+        return 0;
+    }
+
+    @Override
+    public boolean useToolGetProcAdressFirst(String funcName) {
+        return false;
+    }
+
+    @Override
+    public RunnableExecutor getLibLoaderExecutor() {
+        return DynamicLibraryBundle.getDefaultRunnableExecutor();
+    }    
+    
+    private static native boolean initSymbols0(long[] symbols, int count);
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java
new file mode 100644
index 0000000..7d10cff
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java
@@ -0,0 +1,544 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package jogamp.opengl.util.av.impl;
+
+import java.io.IOException;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLException;
+
+import com.jogamp.common.util.VersionNumber;
+import com.jogamp.gluegen.runtime.ProcAddressTable;
+import com.jogamp.opengl.util.GLPixelStorageModes;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+import jogamp.opengl.GLContextImpl;
+import jogamp.opengl.es1.GLES1ProcAddressTable;
+import jogamp.opengl.es2.GLES2ProcAddressTable;
+import jogamp.opengl.gl4.GL4bcProcAddressTable;
+import jogamp.opengl.util.av.EGLMediaPlayerImpl;
+
+/***
+ * Implementation utilizes <a href="http://libav.org/">Libav</a>
+ * or  <a href="http://ffmpeg.org/">FFmpeg</a> which is ubiquitous
+ * available and usually pre-installed on Unix platforms. Due to legal 
+ * reasons we cannot deploy binaries of it, which contains patented codecs.
+ * Besides the default BSD/Linux/.. repositories and installations,
+ * precompiled binaries can be found at the listed location below. 
+ * <p>
+ * Implements YUV420P to RGB fragment shader conversion 
+ * and the usual packed RGB formats.
+ * The decoded video frame is written directly into an OpenGL texture 
+ * on the GPU in it's native format. A custom fragment shader converts 
+ * the native pixelformat to a usable RGB format if required. 
+ * Hence only 1 copy is required before bloating the picture 
+ * from YUV to RGB, for example.
+ * </p> 
+ * <p>
+ * Utilizes a slim dynamic and native binding to the Lib_av 
+ * libraries:
+ * <ul>
+ *   <li>libavutil</li>
+ *   <li>libavformat</li>
+ *   <li>libavcodec</li>
+ * </ul> 
+ * </p>
+ * <p>
+ * http://libav.org/
+ * </p>
+ * <p> 
+ * Check tag 'FIXME: Add more planar formats !' 
+ * here and in the corresponding native code
+ * <code>jogl/src/jogl/native/ffmpeg/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c</code>
+ * </p>
+ * <p>
+ * TODO:
+ * <ul>
+ *   <li>Audio Output</li>
+ *   <li>Off thread <i>next frame</i> processing using multiple target textures</li>
+ *   <li>better pts sync handling</li>
+ *   <li>fix seek</li>   
+ * </ul> 
+ * </p>
+ * Pre-compiled Libav / FFmpeg packages:
+ * <ul>
+ *   <li>Windows: http://ffmpeg.zeranoe.com/builds/</li>
+ *   <li>MacOSX: http://www.ffmpegx.com/</li>
+ *   <li>OpenIndiana/Solaris:<pre>
+ *       pkg set-publisher -p http://pkg.openindiana.org/sfe-encumbered.
+ *       pkt install pkg:/video/ffmpeg
+ *       </pre></li>
+ * </ul> 
+ */
+public class FFMPEGMediaPlayer extends EGLMediaPlayerImpl {
+    public static final VersionNumber avUtilVersion;
+    public static final VersionNumber avFormatVersion;
+    public static final VersionNumber avCodecVersion;    
+    static final boolean available;
+    
+    static {
+        if(FFMPEGDynamicLibraryBundleInfo.initSingleton()) {
+            avUtilVersion = getAVVersion(getAvUtilVersion0());
+            avFormatVersion = getAVVersion(getAvFormatVersion0());
+            avCodecVersion = getAVVersion(getAvCodecVersion0());        
+            System.err.println("LIB_AV Util  : "+avUtilVersion);
+            System.err.println("LIB_AV Format: "+avFormatVersion);
+            System.err.println("LIB_AV Codec : "+avCodecVersion);
+            available = initIDs0();
+        } else {
+            avUtilVersion = null;
+            avFormatVersion = null;
+            avCodecVersion = null;
+            available = false;
+        }
+    }
+    
+    public static final boolean isAvailable() { return available; }
+
+    private static VersionNumber getAVVersion(int vers) {
+        return new VersionNumber( ( vers >> 16 ) & 0xFF,
+                                  ( vers >>  8 ) & 0xFF,
+                                  ( vers >>  0 ) & 0xFF );
+    }
+    
+    protected long moviePtr = 0;    
+    protected long procAddrGLTexSubImage2D = 0;
+    protected EGLMediaPlayerImpl.EGLTextureFrame lastTex = null;
+    protected GLPixelStorageModes psm;
+    protected PixelFormat vPixelFmt = null;
+    protected int vPlanes = 0;
+    protected int vBitsPerPixel = 0;
+    protected int vBytesPerPixelPerPlane = 0;    
+    protected int[] vLinesize = { 0, 0, 0 }; // per plane
+    protected int[] vTexWidth = { 0, 0, 0 }; // per plane
+    protected int texWidth, texHeight; // overall (stuffing planes in one texture)
+    protected ByteBuffer texCopy;
+
+    public FFMPEGMediaPlayer() {
+        super(TextureType.GL, false);
+        if(!available) {
+            throw new RuntimeException("FFMPEGMediaPlayer not available");
+        }
+        setTextureCount(1);
+        moviePtr = createInstance0(true);
+        if(0==moviePtr) {
+            throw new GLException("Couldn't create FFMPEGInstance");
+        }
+        psm = new GLPixelStorageModes();
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        if(TextureType.GL == texType) {
+            final Texture texture = super.createTexImageImpl(gl, idx, tex, texWidth, texHeight, true);
+            lastTex = new EGLTextureFrame(null, texture, 0, 0);
+        } else {
+            throw new InternalError("n/a");
+        }
+        return lastTex;
+    }
+    
+    @Override
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        lastTex = null;
+        super.destroyTexImage(gl, imgTex);        
+    }
+    
+    @Override
+    protected void destroyImpl(GL gl) {
+        if (moviePtr != 0) {
+            destroyInstance0(moviePtr);
+            moviePtr = 0;
+        }
+    }
+    
+    @Override
+    protected void initGLStreamImpl(GL gl, int[] texNames) throws IOException {
+        if(0==moviePtr) {
+            throw new GLException("FFMPEG native instance null");
+        }
+        final String urlS=urlConn.getURL().toExternalForm();
+    
+        System.out.println("setURL: p1 "+this);
+        setStream0(moviePtr, urlS, -1, -1);
+        System.out.println("setURL: p2 "+this);
+        int tf;
+        switch(vBytesPerPixelPerPlane) {
+            case 1: tf = GL2ES2.GL_RED; break;
+            case 3: tf = GL2ES2.GL_RGB; break;
+            case 4: tf = GL2ES2.GL_RGBA; break;
+            default: throw new RuntimeException("Unsupported bytes-per-pixel / plane "+vBytesPerPixelPerPlane);
+        }        
+        setTextureFormat(tf);
+        setTextureType(GL.GL_UNSIGNED_BYTE);
+        GLContextImpl ctx = (GLContextImpl)gl.getContext();
+        ProcAddressTable pt = ctx.getGLProcAddressTable();
+        if(pt instanceof GLES2ProcAddressTable) {
+            procAddrGLTexSubImage2D = ((GLES2ProcAddressTable)pt)._addressof_glTexSubImage2D;
+        } else if(pt instanceof GLES1ProcAddressTable) {
+            procAddrGLTexSubImage2D = ((GLES1ProcAddressTable)pt)._addressof_glTexSubImage2D;
+        } else if(pt instanceof GL4bcProcAddressTable) {
+            procAddrGLTexSubImage2D = ((GL4bcProcAddressTable)pt)._addressof_glTexSubImage2D;
+        } else {
+            throw new InternalError("Unknown ProcAddressTable: "+pt.getClass().getName()+" of "+ctx.getClass().getName());
+        }
+    }
+    private void updateAttributes2(int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane,
+                                   int lSz0, int lSz1, int lSz2,
+                                   int tWd0, int tWd1, int tWd2) {
+        vPixelFmt = PixelFormat.valueOf(pixFmt);
+        vPlanes = planes;
+        vBitsPerPixel = bitsPerPixel;
+        vBytesPerPixelPerPlane = bytesPerPixelPerPlane;
+        vLinesize[0] = lSz0; vLinesize[1] = lSz1; vLinesize[2] = lSz2;
+        vTexWidth[0] = tWd0; vTexWidth[1] = tWd1; vTexWidth[2] = tWd2;
+        
+        switch(vPixelFmt) {
+            case YUV420P:
+                // YUV420P: Adding U+V on right side of fixed height texture,
+                //          since width is already aligned by decoder.
+                // Y=w*h, Y=w/2*h/2, U=w/2*h/2
+                // w*h + 2 ( w/2 * h/2 ) 
+                // w*h + w*h/2
+                // 2*w/2 * h 
+                texWidth = vTexWidth[0] + vTexWidth[1]; texHeight = height; 
+                break;
+            // case PIX_FMT_YUYV422:
+            case RGB24:
+            case BGR24:
+            case ARGB:
+            case RGBA:
+            case ABGR:
+            case BGRA:
+                texWidth = vTexWidth[0]; texHeight = height; 
+                break;
+            default: // FIXME: Add more planar formats !
+                throw new RuntimeException("Unsupported pixelformat: "+vPixelFmt);
+        }
+        if(DEBUG) {
+            System.err.println("XXX0: fmt "+vPixelFmt+", planes "+vPlanes+", bpp "+vBitsPerPixel+"/"+vBytesPerPixelPerPlane);
+            for(int i=0; i<3; i++) {
+                System.err.println("XXX0 "+i+": "+vTexWidth[i]+"/"+vLinesize[i]);
+            }
+            System.err.println("XXX0 total tex "+texWidth+"x"+texHeight);
+        }
+    }
+    
+    /**
+     * {@inheritDoc}
+     * 
+     * If this implementation generates a specialized shader,
+     * it allows the user to override the default function name <code>ffmpegTexture2D</code>.
+     * Otherwise the call is delegated to it's super class.
+     */
+    @Override
+    public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException {
+        if(State.Uninitialized == state) {
+            throw new IllegalStateException("Instance not initialized: "+this);
+        }
+        if(PixelFormat.YUV420P == vPixelFmt) {
+            if(null != desiredFuncName && desiredFuncName.length()>0) {
+                textureLookupFunctionName = desiredFuncName;
+            }
+            return textureLookupFunctionName;
+        }
+        return super.getTextureLookupFunctionName(desiredFuncName);        
+    }
+    private String textureLookupFunctionName = "ffmpegTexture2D";
+    
+    /**
+     * {@inheritDoc}
+     * 
+     * Depending on the pixelformat, a specific conversion shader is being created,
+     * e.g. YUV420P to RGB. Otherwise the call is delegated to it's super class.  
+     */ 
+    @Override
+    public String getTextureLookupFragmentShaderImpl() throws IllegalStateException {
+      if(State.Uninitialized == state) {
+          throw new IllegalStateException("Instance not initialized: "+this);
+      }
+      final float tc_w_1 = (float)getWidth() / (float)texWidth;
+      switch(vPixelFmt) {
+        case YUV420P:
+          return 
+              "vec4 "+textureLookupFunctionName+"(in "+getTextureSampler2DType()+" image, in vec2 texCoord) {\n"+
+              "  vec2 u_off = vec2("+tc_w_1+", 0.0);\n"+
+              "  vec2 v_off = vec2("+tc_w_1+", 0.5);\n"+
+              "  vec2 tc_half = texCoord*0.5;\n"+
+              "  float y,u,v,r,g,b;\n"+
+              "  y = texture2D(image, texCoord).r;\n"+
+              "  u = texture2D(image, u_off+tc_half).r;\n"+
+              "  v = texture2D(image, v_off+tc_half).r;\n"+              
+              "  y = 1.1643*(y-0.0625);\n"+
+              "  u = u-0.5;\n"+
+              "  v = v-0.5;\n"+
+              "  r = y+1.5958*v;\n"+
+              "  g = y-0.39173*u-0.81290*v;\n"+
+              "  b = y+2.017*u;\n"+              
+              "  return vec4(r, g, b, 1);\n"+
+              "}\n"
+          ;            
+        default: // FIXME: Add more planar formats !
+          return super.getTextureLookupFragmentShaderImpl();
+      }        
+    }
+    
+    @Override
+    protected synchronized int getCurrentPositionImpl() {
+        return 0!=moviePtr ? getVideoPTS0(moviePtr) : 0;
+    }
+
+    @Override
+    protected synchronized boolean setPlaySpeedImpl(float rate) {
+        return true;
+    }
+
+    @Override
+    public synchronized boolean startImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    public synchronized boolean pauseImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    public synchronized boolean stopImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    protected synchronized int seekImpl(int msec) {
+        if(0==moviePtr) {
+            throw new GLException("FFMPEG native instance null");
+        }
+        int pts0 = getVideoPTS0(moviePtr);
+        int pts1 = seek0(moviePtr, msec);
+        System.err.println("Seek: "+pts0+" -> "+msec+" : "+pts1);
+        return pts1;
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame getLastTextureImpl() {
+        return lastTex;
+    }
+    
+    private long lastVideoTime = 0;
+    private int lastVideoPTS = 0;
+    private static final int dt_d = 9;
+    
+    @Override
+    protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) {
+        if(0==moviePtr) {
+            throw new GLException("FFMPEG native instance null");
+        }                
+        if(null != lastTex) {
+            psm.setUnpackAlignment(gl, 1); // RGBA ? 4 : 1
+            try {
+                final Texture tex = lastTex.getTexture();
+                gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit());
+                tex.enable(gl);
+                tex.bind(gl);
+                readNextPacket0(moviePtr, procAddrGLTexSubImage2D, textureTarget, textureFormat, textureType);
+            } finally {
+                psm.restore(gl);
+            }
+            final int pts = getVideoPTS0(moviePtr); // this frame
+            if(blocking) {
+                // poor mans video sync .. TODO: off thread 'readNextPackage0(..)' on shared GLContext and multi textures/unit!
+                final long now = System.currentTimeMillis();
+                final long now_d = now - lastVideoTime;
+                final long pts_d = pts - lastVideoPTS;                
+                final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ;
+                lastVideoTime = now;
+                // System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt);
+                if(dt>dt_d) {
+                    try {
+                        Thread.sleep(dt-dt_d);
+                    } catch (InterruptedException e) { }
+                } /* else if(0>pts_d) {
+                    System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt);
+                } */
+            }
+            lastVideoPTS = pts;
+        }
+        return lastTex;
+    }
+    
+    private void consumeAudio(int len) {
+        
+    }
+    
+    private static native int getAvUtilVersion0();
+    private static native int getAvFormatVersion0();
+    private static native int getAvCodecVersion0();
+    private static native boolean initIDs0();
+    private native long createInstance0(boolean verbose);    
+    private native void destroyInstance0(long moviePtr);
+    
+    private native void setStream0(long moviePtr, String url, int vid, int aid);
+
+    private native int getVideoPTS0(long moviePtr);    
+    
+    private native int getAudioPTS0(long moviePtr);
+    private native Buffer getAudioBuffer0(long moviePtr, int plane);
+    
+    private native int readNextPacket0(long moviePtr, long procAddrGLTexSubImage2D, int texTarget, int texFmt, int texType);
+    
+    private native int seek0(long moviePtr, int position);
+
+    public static enum PixelFormat {
+        // NONE= -1,
+        YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+        YUYV422,   ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+        RGB24,     ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+        BGR24,     ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+        YUV422P,   ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+        YUV444P,   ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+        YUV410P,   ///< planar YUV 4:1:0,  9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+        YUV411P,   ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+        GRAY8,     ///<        Y        ,  8bpp
+        MONOWHITE, ///<        Y        ,  1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+        MONOBLACK, ///<        Y        ,  1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+        PAL8,      ///< 8 bit with RGB32 palette
+        YUVJ420P,  ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of YUV420P and setting color_range
+        YUVJ422P,  ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of YUV422P and setting color_range
+        YUVJ444P,  ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of YUV444P and setting color_range
+        XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing
+        XVMC_MPEG2_IDCT,
+        UYVY422,   ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+        UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+        BGR8,      ///< packed RGB 3:3:2,  8bpp, (msb)2B 3G 3R(lsb)
+        BGR4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+        BGR4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1B 2G 1R(lsb)
+        RGB8,      ///< packed RGB 3:3:2,  8bpp, (msb)2R 3G 3B(lsb)
+        RGB4,      ///< packed RGB 1:2:1 bitstream,  4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+        RGB4_BYTE, ///< packed RGB 1:2:1,  8bpp, (msb)1R 2G 1B(lsb)
+        NV12,      ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+        NV21,      ///< as above, but U and V bytes are swapped
+
+        ARGB,      ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+        RGBA,      ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+        ABGR,      ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+        BGRA,      ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+        GRAY16BE,  ///<        Y        , 16bpp, big-endian
+        GRAY16LE,  ///<        Y        , 16bpp, little-endian
+        YUV440P,   ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+        YUVJ440P,  ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of YUV440P and setting color_range
+        YUVA420P,  ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+        VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        RGB48BE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+        RGB48LE,   ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+        RGB565BE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), big-endian
+        RGB565LE,  ///< packed RGB 5:6:5, 16bpp, (msb)   5R 6G 5B(lsb), little-endian
+        RGB555BE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0
+        RGB555LE,  ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0
+
+        BGR565BE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), big-endian
+        BGR565LE,  ///< packed BGR 5:6:5, 16bpp, (msb)   5B 6G 5R(lsb), little-endian
+        BGR555BE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1
+        BGR555LE,  ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1
+
+        VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+        VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+        VAAPI_VLD,  ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+
+        YUV420P16LE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+        YUV420P16BE,  ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+        YUV422P16LE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+        YUV422P16BE,  ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+        YUV444P16LE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+        YUV444P16BE,  ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+        VDPAU_MPEG4,  ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers
+        DXVA2_VLD,    ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+        RGB444LE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0
+        RGB444BE,  ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0
+        BGR444LE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1
+        BGR444BE,  ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1
+        Y400A,     ///< 8bit gray, 8bit alpha
+        BGR48BE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+        BGR48LE,   ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
+        YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+        YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+        YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+        YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+        YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+        YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+        YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+        YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+        YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+        YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+        YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+        YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+        VDA_VLD,    ///< hardware decoding through VDA
+        GBRP,      ///< planar GBR 4:4:4 24bpp
+        GBRP9BE,   ///< planar GBR 4:4:4 27bpp, big endian
+        GBRP9LE,   ///< planar GBR 4:4:4 27bpp, little endian
+        GBRP10BE,  ///< planar GBR 4:4:4 30bpp, big endian
+        GBRP10LE,  ///< planar GBR 4:4:4 30bpp, little endian
+        GBRP16BE,  ///< planar GBR 4:4:4 48bpp, big endian
+        GBRP16LE,  ///< planar GBR 4:4:4 48bpp, little endian
+        COUNT      ///< number of pixel formats in this list
+        ;
+        public static PixelFormat valueOf(int i) {
+            for (PixelFormat fmt : PixelFormat.values()) {
+                if(fmt.ordinal() == i) {
+                    return fmt;
+                }
+            }
+            return null;            
+        }
+    }
+
+}
+
diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java
new file mode 100644
index 0000000..aef98fc
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/av/impl/OMXGLMediaPlayer.java
@@ -0,0 +1,228 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package jogamp.opengl.util.av.impl;
+
+import java.io.IOException;
+import java.net.URL;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+import jogamp.opengl.egl.EGL;
+import jogamp.opengl.util.av.EGLMediaPlayerImpl;
+
+/**
+ * OpenMAX IL implementation. This implementation is currently not tested
+ * due to lack of an available device or working <i>software</i> implementation.
+ * It is kept alive through all changes in the hope of a later availability though.
+ */
+public class OMXGLMediaPlayer extends EGLMediaPlayerImpl {
+    static final boolean available;
+    
+    static {
+        // OMX binding is included in jogl_desktop and jogl_mobile     
+        GLProfile.initSingleton();
+        available = initIDs0();
+    }
+    
+    public static final boolean isAvailable() { return available; }
+    
+    protected long moviePtr = 0;
+    
+    protected TextureSequence.TextureFrame lastTex = null;
+
+    public OMXGLMediaPlayer() {
+        super(TextureType.KHRImage, true);
+        if(!available) {
+            throw new RuntimeException("OMXGLMediaPlayer not available");
+        }
+        initOMX();
+    }
+
+    protected void initOMX() {
+        moviePtr = _createInstance();
+        if(0==moviePtr) {
+            throw new GLException("Couldn't create OMXInstance");
+        }        
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) {
+        final EGLTextureFrame eglTex = (EGLTextureFrame) super.createTexImage(gl, idx, tex);
+        _setStreamEGLImageTexture2D(moviePtr, idx, tex[idx], eglTex.getImage(), eglTex.getSync());
+        lastTex = eglTex;
+        return eglTex;
+    }
+    
+    @Override
+    protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) {
+        lastTex = null;
+        super.destroyTexImage(gl, imgTex);        
+    }
+    
+    @Override
+    protected void destroyImpl(GL gl) {
+        _detachVideoRenderer(moviePtr);
+        if (moviePtr != 0) {
+            _destroyInstance(moviePtr);
+            moviePtr = 0;
+        }
+    }
+    
+    @Override
+    protected void initGLStreamImpl(GL gl, int[] texNames) throws IOException {
+        if(0==moviePtr) {
+            throw new GLException("OMX native instance null");
+        }
+        final URL url = urlConn.getURL();
+        if(!url.getProtocol().equals("file")) {
+            throw new IOException("Only file URLs are allowed: "+url);            
+        }
+        final String path=url.getPath();
+        System.out.println("setURL: clean path "+path);
+    
+        System.out.println("setURL: p1 "+this);
+        _setStream(moviePtr, textureCount, path);
+        System.out.println("setURL: p2 "+this);        
+    }
+    
+    @Override
+    protected int getCurrentPositionImpl() {
+        return 0!=moviePtr ? _getCurrentPosition(moviePtr) : 0;
+    }
+
+    @Override
+    protected boolean setPlaySpeedImpl(float rate) {
+        if(0==moviePtr) {
+            throw new GLException("OMX native instance null");
+        }
+        _setPlaySpeed(moviePtr, rate);
+        return true;
+    }
+
+    @Override
+    public synchronized boolean startImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        _play(moviePtr);
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    public synchronized boolean pauseImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        _pause(moviePtr);
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    public synchronized boolean stopImpl() {
+        if(0==moviePtr) {
+            return false;
+        }
+        _stop(moviePtr);
+        return true;
+    }
+
+    /** @return time position after issuing the command */
+    @Override
+    protected int seekImpl(int msec) {
+        if(0==moviePtr) {
+            throw new GLException("OMX native instance null");
+        }
+        return _seek(moviePtr, msec);
+    }
+
+    @Override
+    protected TextureSequence.TextureFrame getLastTextureImpl() {
+        return lastTex;
+    }
+    
+    @Override
+    protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) {
+        if(0==moviePtr) {
+            throw new GLException("OMX native instance null");
+        }
+        final int nextTex = _getNextTextureID(moviePtr, blocking);
+        if(0 < nextTex) {
+            final TextureSequence.TextureFrame eglImgTex = texFrameMap.get(new Integer(_getNextTextureID(moviePtr, blocking)));
+            if(null!=eglImgTex) {
+                lastTex = eglImgTex;
+            }
+        }
+        return lastTex;
+    }
+    
+    private String replaceAll(String orig, String search, String repl) {
+        String dest=null;
+        // In case replaceAll / java.util.regex.* is not supported (-> CVM)
+        int i=0,j;
+        dest = new String();
+        while((j=orig.indexOf(search, i))>=0) {
+            dest=dest.concat(orig.substring(i, j));
+            dest=dest.concat(repl);
+            i=j+1;
+        }
+        return dest.concat(orig.substring(i, orig.length()));
+    }
+
+    private void errorCheckEGL(String s) {
+        int e;
+        if( (e=EGL.eglGetError()) != EGL.EGL_SUCCESS ) {
+            System.out.println("EGL Error: ("+s+"): 0x"+Integer.toHexString(e));
+        }
+    }
+
+    private static native boolean initIDs0();
+    private native long _createInstance();    
+    private native void _destroyInstance(long moviePtr);
+    
+    private native void _detachVideoRenderer(long moviePtr); // stop before
+    private native void _attachVideoRenderer(long moviePtr); // detach before
+    private native void _setStream(long moviePtr, int textureNum, String path);
+    private native void _activateStream(long moviePtr);
+    
+    private native void _setStreamEGLImageTexture2D(long moviePtr, int i, int tex, long image, long sync);
+    private native int  _seek(long moviePtr, int position);
+    private native void _setPlaySpeed(long moviePtr, float rate);
+    private native void _play(long moviePtr);
+    private native void _pause(long moviePtr);
+    private native void _stop(long moviePtr);
+    private native int  _getNextTextureID(long moviePtr, boolean blocking);
+    private native int  _getCurrentPosition(long moviePtr);
+}
+
diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncHook.java b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncHook.java
index fe4db89..897967f 100644
--- a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncHook.java
+++ b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncHook.java
@@ -31,10 +31,9 @@ package jogamp.opengl.util.glsl.fixedfunc;
 
 import javax.media.opengl.*;
 import javax.media.opengl.fixedfunc.*;
-import javax.media.opengl.glu.*;
 import com.jogamp.common.nio.Buffers;
 import com.jogamp.opengl.util.*;
-import com.jogamp.opengl.util.glsl.*;
+
 import java.nio.*;
 
 public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFunc {
@@ -56,7 +55,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
     }
 
     public FixedFuncHook(GL2ES2 gl, PMVMatrix matrix, 
-                       Class shaderRootClass, String shaderSrcRoot, String shaderBinRoot, 
+                       Class<?> shaderRootClass, String shaderSrcRoot, String shaderBinRoot, 
                        String vertexColorFile,
                        String vertexColorLightFile,
                        String fragmentColorFile,
@@ -112,28 +111,28 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
     }
 
     public void glGetFloatv(int pname, java.nio.FloatBuffer params) {
-        if(pmvMatrix.isMatrixGetName(pname)) {
+        if(PMVMatrix.isMatrixGetName(pname)) {
             pmvMatrix.glGetFloatv(pname, params);
             return;
         }
         gl.glGetFloatv(pname, params);
     }
     public void glGetFloatv(int pname, float[] params, int params_offset) {
-        if(pmvMatrix.isMatrixGetName(pname)) {
+        if(PMVMatrix.isMatrixGetName(pname)) {
             pmvMatrix.glGetFloatv(pname, params, params_offset);
             return;
         }
         gl.glGetFloatv(pname, params, params_offset);
     }
     public void glGetIntegerv(int pname, IntBuffer params) {
-        if(pmvMatrix.isMatrixGetName(pname)) {
+        if(PMVMatrix.isMatrixGetName(pname)) {
             pmvMatrix.glGetIntegerv(pname, params);
             return;
         }
         gl.glGetIntegerv(pname, params);
     }
     public void glGetIntegerv(int pname, int[] params, int params_offset) {
-        if(pmvMatrix.isMatrixGetName(pname)) {
+        if(PMVMatrix.isMatrixGetName(pname)) {
             pmvMatrix.glGetIntegerv(pname, params, params_offset);
             return;
         }
@@ -339,7 +338,7 @@ public class FixedFuncHook implements GLLightingFunc, GLMatrixFunc, GLPointerFun
     }
 
     public final String toString() {
-          StringBuffer buf = new StringBuffer();
+          StringBuilder buf = new StringBuilder();
           buf.append(getClass().getName()+" (");
           if(null!=pmvMatrix) {
               buf.append(", matrixDirty: "+pmvMatrix.isDirty());
diff --git a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
index 7bc0c54..bfe2e13 100644
--- a/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
+++ b/src/jogl/classes/jogamp/opengl/util/glsl/fixedfunc/FixedFuncPipeline.java
@@ -365,15 +365,15 @@ public class FixedFuncPipeline {
 
         if(textureEnabled) {
             if(lightingEnabled) {
-                shaderState.attachShaderProgram(gl, shaderProgramColorTextureLight);
+                shaderState.attachShaderProgram(gl, shaderProgramColorTextureLight, true);
             } else {
-                shaderState.attachShaderProgram(gl, shaderProgramColorTexture);
+                shaderState.attachShaderProgram(gl, shaderProgramColorTexture, true);
             }
         } else {
             if(lightingEnabled) {
-                shaderState.attachShaderProgram(gl, shaderProgramColorLight);
+                shaderState.attachShaderProgram(gl, shaderProgramColorLight, true);
             } else {
-                shaderState.attachShaderProgram(gl, shaderProgramColor);
+                shaderState.attachShaderProgram(gl, shaderProgramColor, true);
             }
         }
         if(DEBUG) {
@@ -409,17 +409,17 @@ public class FixedFuncPipeline {
         this.shaderState.setVerbose(verbose);
         ShaderCode vertexColor, vertexColorLight, fragmentColor, fragmentColorTexture;
 
-        vertexColor = ShaderCode.create( gl, gl.GL_VERTEX_SHADER, 1, shaderRootClass,
-                                         shaderSrcRoot, shaderBinRoot, vertexColorFile);
+        vertexColor = ShaderCode.create( gl, gl.GL_VERTEX_SHADER, shaderRootClass, shaderSrcRoot,
+                                         shaderBinRoot, vertexColorFile, false);
 
-        vertexColorLight = ShaderCode.create( gl, gl.GL_VERTEX_SHADER, 1, shaderRootClass,
-                                           shaderSrcRoot, shaderBinRoot, vertexColorLightFile);
+        vertexColorLight = ShaderCode.create( gl, gl.GL_VERTEX_SHADER, shaderRootClass, shaderSrcRoot,
+                                           shaderBinRoot, vertexColorLightFile, false);
 
-        fragmentColor = ShaderCode.create( gl, gl.GL_FRAGMENT_SHADER, 1, shaderRootClass,
-                                           shaderSrcRoot, shaderBinRoot, fragmentColorFile);
+        fragmentColor = ShaderCode.create( gl, gl.GL_FRAGMENT_SHADER, shaderRootClass, shaderSrcRoot,
+                                           shaderBinRoot, fragmentColorFile, false);
 
-        fragmentColorTexture = ShaderCode.create( gl, gl.GL_FRAGMENT_SHADER, 1, shaderRootClass,
-                                                  shaderSrcRoot, shaderBinRoot, fragmentColorTextureFile);
+        fragmentColorTexture = ShaderCode.create( gl, gl.GL_FRAGMENT_SHADER, shaderRootClass, shaderSrcRoot,
+                                                  shaderBinRoot, fragmentColorTextureFile, false);
 
         shaderProgramColor = new ShaderProgram();
         shaderProgramColor.add(vertexColor);
@@ -449,8 +449,7 @@ public class FixedFuncPipeline {
             throw new GLException("Couldn't link VertexColorLight program: "+shaderProgramColorTextureLight);
         }
 
-        shaderState.attachShaderProgram(gl, shaderProgramColor);
-        shaderState.useProgram(gl, true);
+        shaderState.attachShaderProgram(gl, shaderProgramColor, true);
 
         // mandatory ..
         if(!shaderState.uniform(gl, new GLUniformData(mgl_PMVMatrix, 4, 4, pmvMatrix.glGetPMvMvitMatrixf()))) {
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java b/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java
new file mode 100644
index 0000000..a34f73a
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/FilterType.java
@@ -0,0 +1,94 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Internal PNG predictor filter, or strategy to select it.
+ * 
+ */
+public enum FilterType {
+	/**
+	 * No filter.
+	 */
+	FILTER_NONE(0),
+	/**
+	 * SUB filter (uses same row)
+	 */
+	FILTER_SUB(1),
+	/**
+	 * UP filter (uses previous row)
+	 */
+	FILTER_UP(2),
+	/**
+	 * AVERAGE filter
+	 */
+	FILTER_AVERAGE(3),
+	/**
+	 * PAETH predictor
+	 */
+	FILTER_PAETH(4),
+	/**
+	 * Default strategy: select one of the above filters depending on global image parameters
+	 */
+	FILTER_DEFAULT(-1),
+	/**
+	 * Aggresive strategy: select one of the above filters trying each of the filters (this is done every 8 rows)
+	 */
+	FILTER_AGGRESSIVE(-2),
+	/**
+	 * Uses all fiters, one for lines, cyciclally. Only for tests.
+	 */
+	FILTER_ALTERNATE(-3),
+	/**
+	 * Aggresive strategy: select one of the above filters trying each of the filters (this is done for every row!)
+	 */
+	FILTER_VERYAGGRESSIVE(-4), ;
+	public final int val;
+
+	private FilterType(int val) {
+		this.val = val;
+	}
+
+	public static FilterType getByVal(int i) {
+		for (FilterType ft : values()) {
+			if (ft.val == i)
+				return ft;
+		}
+		return null;
+	}
+
+	public static int unfilterRowNone(int r) {
+		return (int) (r & 0xFF);
+	}
+
+	public static int unfilterRowSub(int r, int left) {
+		return ((int) (r + left) & 0xFF);
+	}
+
+	public static int unfilterRowUp(int r, int up) {
+		return ((int) (r + up) & 0xFF);
+	}
+
+	public static int unfilterRowAverage(int r, int left, int up) {
+		return (r + (left + up) / 2) & 0xFF;
+	}
+
+	public static int unfilterRowPaeth(int r, int a, int b, int c) { // a = left, b = above, c = upper left
+		return (r + filterPaethPredictor(a, b, c)) & 0xFF;
+	}
+
+	public static int filterPaethPredictor(int a, int b, int c) {
+		// from http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
+		// a = left, b = above, c = upper left
+		final int p = a + b - c;// ; initial estimate
+		final int pa = p >= a ? p - a : a - p;
+		final int pb = p >= b ? p - b : b - p;
+		final int pc = p >= c ? p - c : c - p;
+		// ; return nearest of a,b,c,
+		// ; breaking ties in order a,b,c.
+		if (pa <= pb && pa <= pc)
+			return a;
+		else if (pb <= pc)
+			return b;
+		else
+			return c;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/FilterWriteStrategy.java b/src/jogl/classes/jogamp/opengl/util/pngj/FilterWriteStrategy.java
new file mode 100644
index 0000000..27586b2
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/FilterWriteStrategy.java
@@ -0,0 +1,97 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Manages the writer strategy for selecting the internal png "filter"
+ */
+class FilterWriteStrategy {
+	private static final int COMPUTE_STATS_EVERY_N_LINES = 8;
+
+	final ImageInfo imgInfo;
+	public final FilterType configuredType; // can be negative (fin dout)
+	private FilterType currentType; // 0-4
+	private int lastRowTested = -1000000;
+	// performance of each filter (less is better) (can be negative)
+	private double[] lastSums = new double[5];
+	// performance of each filter (less is better) (can be negative)
+	private double[] lastEntropies = new double[5];
+	// a priori preference (NONE SUB UP AVERAGE PAETH)
+	private double[] preference = new double[] { 1.1, 1.1, 1.1, 1.1, 1.2 };
+	private int discoverEachLines = -1;
+	private double[] histogram1 = new double[256];
+
+	FilterWriteStrategy(ImageInfo imgInfo, FilterType configuredType) {
+		this.imgInfo = imgInfo;
+		this.configuredType = configuredType;
+		if (configuredType.val < 0) { // first guess
+			if ((imgInfo.rows < 8 && imgInfo.cols < 8) || imgInfo.indexed || imgInfo.bitDepth < 8)
+				currentType = FilterType.FILTER_NONE;
+			else
+				currentType = FilterType.FILTER_PAETH;
+		} else {
+			currentType = configuredType;
+		}
+		if (configuredType == FilterType.FILTER_AGGRESSIVE)
+			discoverEachLines = COMPUTE_STATS_EVERY_N_LINES;
+		if (configuredType == FilterType.FILTER_VERYAGGRESSIVE)
+			discoverEachLines = 1;
+	}
+
+	boolean shouldTestAll(int rown) {
+		if (discoverEachLines > 0 && lastRowTested + discoverEachLines <= rown) {
+			currentType = null;
+			return true;
+		} else
+			return false;
+	}
+
+	public void setPreference(double none, double sub, double up, double ave, double paeth) {
+		preference = new double[] { none, sub, up, ave, paeth };
+	}
+
+	public boolean computesStatistics() {
+		return (discoverEachLines > 0);
+	}
+
+	void fillResultsForFilter(int rown, FilterType type, double sum, int[] histo, boolean tentative) {
+		lastRowTested = rown;
+		lastSums[type.val] = sum;
+		if (histo != null) {
+			double v, alfa, beta, e;
+			alfa = rown == 0 ? 0.0 : 0.3;
+			beta = 1 - alfa;
+			e = 0.0;
+			for (int i = 0; i < 256; i++) {
+				v = ((double) histo[i]) / imgInfo.cols;
+				v = histogram1[i] * alfa + v * beta;
+				if (tentative)
+					e += v > 0.00000001 ? v * Math.log(v) : 0.0;
+				else
+					histogram1[i] = v;
+			}
+			lastEntropies[type.val] = (-e);
+		}
+	}
+
+	FilterType gimmeFilterType(int rown, boolean useEntropy) {
+		if (currentType == null) { // get better
+			if (rown == 0)
+				currentType = FilterType.FILTER_SUB;
+			else {
+				double bestval = Double.MAX_VALUE;
+				double val;
+				for (int i = 0; i < 5; i++) {
+					val = useEntropy ? lastEntropies[i] : lastSums[i];
+					val /= preference[i];
+					if (val <= bestval) {
+						bestval = val;
+						currentType = FilterType.getByVal(i);
+					}
+				}
+			}
+		}
+		if (configuredType == FilterType.FILTER_ALTERNATE) {
+			currentType = FilterType.getByVal((currentType.val + 1) % 5);
+		}
+		return currentType;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java
new file mode 100644
index 0000000..2f6b89e
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageInfo.java
@@ -0,0 +1,208 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Simple immutable wrapper for basic image info.
+ * <p>
+ * Some parameters are redundant, but the constructor receives an 'orthogonal' subset.
+ * <p>
+ * ref: http://www.w3.org/TR/PNG/#11IHDR
+ */
+public class ImageInfo {
+
+	// very big value ; actually we are ok with 2**22=4M, perhaps even more
+	private static final int MAX_COLS_ROWS_VAL = 1000000;
+
+	/**
+	 * Image width, in pixels.
+	 */
+	public final int cols;
+
+	/**
+	 * Image height, in pixels
+	 */
+	public final int rows;
+
+	/**
+	 * Bits per sample (per channel) in the buffer (1-2-4-8-16). This is 8-16 for RGB/ARGB images, 1-2-4-8 for
+	 * grayscale. For indexed images, number of bits per palette index (1-2-4-8)
+	 */
+	public final int bitDepth;
+
+	/**
+	 * Number of channels, as used internally. This is 3 for RGB, 4 for RGBA, 2 for GA (gray with alpha), 1 for
+	 * grayscales or indexed.
+	 */
+	public final int channels;
+
+	/**
+	 * Flag: true if has alpha channel (RGBA/GA)
+	 */
+	public final boolean alpha;
+
+	/**
+	 * Flag: true if is grayscale (G/GA)
+	 */
+	public final boolean greyscale;
+
+	/**
+	 * Flag: true if image is indexed, i.e., it has a palette
+	 */
+	public final boolean indexed;
+
+	/**
+	 * Flag: true if image internally uses less than one byte per sample (bit depth 1-2-4)
+	 */
+	public final boolean packed;
+
+	/**
+	 * Bits used for each pixel in the buffer: channel * bitDepth
+	 */
+	public final int bitspPixel;
+
+	/**
+	 * rounded up value: this is only used internally for filter
+	 */
+	public final int bytesPixel;
+
+	/**
+	 * ceil(bitspp*cols/8)
+	 */
+	public final int bytesPerRow;
+
+	/**
+	 * Equals cols * channels
+	 */
+	public final int samplesPerRow;
+
+	/**
+	 * For internal use only. Samples available for our packed scanline. Equals samplesPerRow if not packed. Elsewhere,
+	 * it's lower
+	 */
+	final int samplesPerRowP;
+
+	/**
+	 * Short constructor: assumes truecolor (RGB/RGBA)
+	 */
+	public ImageInfo(int cols, int rows, int bitdepth, boolean alpha) {
+		this(cols, rows, bitdepth, alpha, false, false);
+	}
+
+	/**
+	 * Full constructor
+	 * 
+	 * @param cols
+	 *            Width in pixels
+	 * @param rows
+	 *            Height in pixels
+	 * @param bitdepth
+	 *            Bits per sample, in the buffer : 8-16 for RGB true color and greyscale
+	 * @param alpha
+	 *            Flag: has an alpha channel (RGBA or GA)
+	 * @param grayscale
+	 *            Flag: is gray scale (any bitdepth, with or without alpha)
+	 * @param indexed
+	 *            Flag: has palette
+	 */
+	public ImageInfo(int cols, int rows, int bitdepth, boolean alpha, boolean grayscale, boolean indexed) {
+		this.cols = cols;
+		this.rows = rows;
+		this.alpha = alpha;
+		this.indexed = indexed;
+		this.greyscale = grayscale;
+		if (greyscale && indexed)
+			throw new PngjException("palette and greyscale are mutually exclusive");
+		this.channels = (grayscale || indexed) ? (alpha ? 2 : 1) : (alpha ? 4 : 3);
+		// http://www.w3.org/TR/PNG/#11IHDR
+		this.bitDepth = bitdepth;
+		this.packed = bitdepth < 8;
+		this.bitspPixel = (channels * this.bitDepth);
+		this.bytesPixel = (bitspPixel + 7) / 8;
+		this.bytesPerRow = (bitspPixel * cols + 7) / 8;
+		this.samplesPerRow = channels * this.cols;
+		this.samplesPerRowP = packed ? bytesPerRow : samplesPerRow;
+		// several checks
+		switch (this.bitDepth) {
+		case 1:
+		case 2:
+		case 4:
+			if (!(this.indexed || this.greyscale))
+				throw new PngjException("only indexed or grayscale can have bitdepth=" + this.bitDepth);
+			break;
+		case 8:
+			break;
+		case 16:
+			if (this.indexed)
+				throw new PngjException("indexed can't have bitdepth=" + this.bitDepth);
+			break;
+		default:
+			throw new PngjException("invalid bitdepth=" + this.bitDepth);
+		}
+		if (cols < 1 || cols > MAX_COLS_ROWS_VAL)
+			throw new PngjException("invalid cols=" + cols + " ???");
+		if (rows < 1 || rows > MAX_COLS_ROWS_VAL)
+			throw new PngjException("invalid rows=" + rows + " ???");
+	}
+
+	@Override
+	public String toString() {
+		return "ImageInfo [cols=" + cols + ", rows=" + rows + ", bitDepth=" + bitDepth + ", channels=" + channels
+				+ ", bitspPixel=" + bitspPixel + ", bytesPixel=" + bytesPixel + ", bytesPerRow=" + bytesPerRow
+				+ ", samplesPerRow=" + samplesPerRow + ", samplesPerRowP=" + samplesPerRowP + ", alpha=" + alpha
+				+ ", greyscale=" + greyscale + ", indexed=" + indexed + ", packed=" + packed + "]";
+	}
+
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + (alpha ? 1231 : 1237);
+		result = prime * result + bitDepth;
+		result = prime * result + bitspPixel;
+		result = prime * result + bytesPerRow;
+		result = prime * result + bytesPixel;
+		result = prime * result + channels;
+		result = prime * result + cols;
+		result = prime * result + (greyscale ? 1231 : 1237);
+		result = prime * result + (indexed ? 1231 : 1237);
+		result = prime * result + (packed ? 1231 : 1237);
+		result = prime * result + rows;
+		result = prime * result + samplesPerRow;
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (getClass() != obj.getClass())
+			return false;
+		ImageInfo other = (ImageInfo) obj;
+		if (alpha != other.alpha)
+			return false;
+		if (bitDepth != other.bitDepth)
+			return false;
+		if (bitspPixel != other.bitspPixel)
+			return false;
+		if (bytesPerRow != other.bytesPerRow)
+			return false;
+		if (bytesPixel != other.bytesPixel)
+			return false;
+		if (channels != other.channels)
+			return false;
+		if (cols != other.cols)
+			return false;
+		if (greyscale != other.greyscale)
+			return false;
+		if (indexed != other.indexed)
+			return false;
+		if (packed != other.packed)
+			return false;
+		if (rows != other.rows)
+			return false;
+		if (samplesPerRow != other.samplesPerRow)
+			return false;
+		return true;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java
new file mode 100644
index 0000000..bfbb35b
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/ImageLine.java
@@ -0,0 +1,175 @@
+package jogamp.opengl.util.pngj;
+
+import java.util.Arrays;
+
+/**
+ * Lightweight wrapper for an image scanline, used for read and write.
+ * <p>
+ * This object can be (usually it is) reused while iterating over the image lines.
+ * <p>
+ * See <code>scanline</code> field, to understand the format.
+ */
+public class ImageLine {
+	public final ImageInfo imgInfo;
+
+	/**
+	 * tracks the current row number (from 0 to rows-1)
+	 */
+	private int rown = 0;
+
+	/**
+	 * The 'scanline' is an array of integers, corresponds to an image line (row).
+	 * <p>
+	 * Except for 'packed' formats (gray/indexed with 1-2-4 bitdepth) each int is a "sample" (one for channel), (0-255
+	 * or 0-65535) in the respective PNG sequence sequence : (R G B R G B...) or (R G B A R G B A...) or (g g g ...) or
+	 * ( i i i) (palette index)
+	 * <p>
+	 * For bitdepth 1/2/4 , each element is a PACKED byte! To get an unpacked copy, see <code>tf_pack()</code> and its
+	 * inverse <code>tf_unpack()</code>
+	 * <p>
+	 * To convert a indexed line to RGB balues, see <code>ImageLineHelper.tf_palIdx2RGB()</code> (can't do the reverse)
+	 */
+	public final int[] scanline; // see explanation above!!
+
+	protected FilterType filterUsed; // informational ; only filled by the reader
+	public final int channels; // copied from imgInfo, more handy
+	public final int bitDepth; // copied from imgInfo, more handy
+
+	public ImageLine(ImageInfo imgInfo) {
+		this.imgInfo = imgInfo;
+		channels = imgInfo.channels;
+		scanline = new int[imgInfo.samplesPerRowP];
+		this.bitDepth = imgInfo.bitDepth;
+	}
+
+	/** This row number inside the image (0 is top) */
+	public int getRown() {
+		return rown;
+	}
+
+	/** Increments row number */
+	public void incRown() {
+		this.rown++;
+	}
+
+	/** Sets row number */
+	public void setRown(int n) {
+		this.rown = n;
+	}
+
+	/** Sets scanline, making copy from passed array */
+	public void setScanLine(int[] b) {
+		System.arraycopy(b, 0, scanline, 0, scanline.length);
+	}
+
+	/**
+	 * Returns a copy from scanline, in byte array.
+	 * 
+	 * You can (OPTIONALLY) pass an preallocated array to use.
+	 **/
+	public int[] getScanLineCopy(int[] b) {
+		if (b == null || b.length < scanline.length)
+			b = new int[scanline.length];
+		System.arraycopy(scanline, 0, b, 0, scanline.length);
+		return b;
+	}
+
+	/**
+	 * Unpacks scanline (for bitdepth 1-2-4) into buffer.
+	 * <p>
+	 * You can (OPTIONALLY) pass an preallocated array to use.
+	 * <p>
+	 * If scale==TRUE scales the value (just a bit shift).
+	 */
+	public int[] tf_unpack(int[] buf, boolean scale) {
+		int len = scanline.length;
+		if (bitDepth == 1)
+			len *= 8;
+		else if (bitDepth == 2)
+			len *= 4;
+		else if (bitDepth == 4)
+			len *= 2;
+		if (buf == null)
+			buf = new int[len];
+		if (bitDepth >= 8)
+			System.arraycopy(scanline, 0, buf, 0, scanline.length);
+		else {
+			int mask, offset, v;
+			int mask0 = getMaskForPackedFormats();
+			int offset0 = 8 - bitDepth;
+			mask = mask0;
+			offset = offset0;
+			for (int i = 0, j = 0; i < len; i++) {
+				v = (scanline[j] & mask) >> offset;
+				if (scale)
+					v <<= offset0;
+				buf[i] = v;
+				mask = mask >> bitDepth;
+				offset -= bitDepth;
+				if (mask == 0) { // new byte in source
+					mask = mask0;
+					offset = offset0;
+					j++;
+				}
+			}
+		}
+		return buf;
+	}
+
+	/**
+	 * Packs scanline (for bitdepth 1-2-4) from buffer.
+	 * <p>
+	 * If scale==TRUE scales the value (just a bit shift).
+	 */
+	public void tf_pack(int[] buf, boolean scale) { // writes scanline
+		int len = scanline.length;
+		if (bitDepth == 1)
+			len *= 8;
+		else if (bitDepth == 2)
+			len *= 4;
+		else if (bitDepth == 4)
+			len *= 2;
+		if (bitDepth >= 8)
+			System.arraycopy(buf, 0, scanline, 0, scanline.length);
+		else {
+			int offset0 = 8 - bitDepth;
+			int mask0 = getMaskForPackedFormats() >> offset0;
+			int offset, v;
+			offset = offset0;
+			Arrays.fill(scanline, 0);
+			for (int i = 0, j = 0; i < len; i++) {
+				v = buf[i];
+				if (scale)
+					v >>= offset0;
+				v = (v & mask0) << offset;
+				scanline[j] |= v;
+				offset -= bitDepth;
+				if (offset < 0) { // new byte in scanline
+					offset = offset0;
+					j++;
+				}
+			}
+		}
+	}
+
+	private int getMaskForPackedFormats() { // Utility function for pacj/unpack
+		if (bitDepth == 1)
+			return 0x80;
+		if (bitDepth == 2)
+			return 0xc0;
+		if (bitDepth == 4)
+			return 0xf0;
+		throw new RuntimeException("?");
+	}
+
+	public FilterType getFilterUsed() {
+		return filterUsed;
+	}
+
+	/**
+	 * Basic info
+	 */
+	public String toString() {
+		return "row=" + rown + " cols=" + imgInfo.cols + " bpc=" + imgInfo.bitDepth + " size=" + scanline.length;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelper.java
new file mode 100644
index 0000000..1016b1b
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngHelper.java
@@ -0,0 +1,213 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.CRC32;
+
+/**
+ * Some utility static methods.
+ * <p>
+ * See also <code>FileHelper</code> (if not sandboxed).
+ * <p>
+ * Client code should rarely need these methods.
+ */
+public class PngHelper {
+	/**
+	 * Default charset, used internally by PNG for several things
+	 */
+	public static Charset charsetLatin1 = Charset.forName("ISO-8859-1");
+	public static Charset charsetUTF8 = Charset.forName("UTF-8"); // only for some chunks
+
+	static boolean DEBUG = false;
+
+	public static int readByte(InputStream is) {
+		try {
+			return is.read();
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	/**
+	 * -1 if eof
+	 * 
+	 * PNG uses "network byte order"
+	 */
+	public static int readInt2(InputStream is) {
+		try {
+			int b1 = is.read();
+			int b2 = is.read();
+			if (b1 == -1 || b2 == -1)
+				return -1;
+			return (b1 << 8) + b2;
+		} catch (IOException e) {
+			throw new PngjInputException("error reading readInt2", e);
+		}
+	}
+
+	/**
+	 * -1 if eof
+	 */
+	public static int readInt4(InputStream is) {
+		try {
+			int b1 = is.read();
+			int b2 = is.read();
+			int b3 = is.read();
+			int b4 = is.read();
+			if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1)
+				return -1;
+			return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
+		} catch (IOException e) {
+			throw new PngjInputException("error reading readInt4", e);
+		}
+	}
+
+	public static int readInt1fromByte(byte[] b, int offset) {
+		return (b[offset] & 0xff);
+	}
+
+	public static int readInt2fromBytes(byte[] b, int offset) {
+		return ((b[offset] & 0xff) << 16) | ((b[offset + 1] & 0xff));
+	}
+
+	public static int readInt4fromBytes(byte[] b, int offset) {
+		return ((b[offset] & 0xff) << 24) | ((b[offset + 1] & 0xff) << 16) | ((b[offset + 2] & 0xff) << 8)
+				| (b[offset + 3] & 0xff);
+	}
+
+	public static void writeByte(OutputStream os, byte b) {
+		try {
+			os.write(b);
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	public static void writeInt2(OutputStream os, int n) {
+		byte[] temp = { (byte) ((n >> 8) & 0xff), (byte) (n & 0xff) };
+		writeBytes(os, temp);
+	}
+
+	public static void writeInt4(OutputStream os, int n) {
+		byte[] temp = new byte[4];
+		writeInt4tobytes(n, temp, 0);
+		writeBytes(os, temp);
+	}
+
+	public static void writeInt2tobytes(int n, byte[] b, int offset) {
+		b[offset] = (byte) ((n >> 8) & 0xff);
+		b[offset + 1] = (byte) (n & 0xff);
+	}
+
+	public static void writeInt4tobytes(int n, byte[] b, int offset) {
+		b[offset] = (byte) ((n >> 24) & 0xff);
+		b[offset + 1] = (byte) ((n >> 16) & 0xff);
+		b[offset + 2] = (byte) ((n >> 8) & 0xff);
+		b[offset + 3] = (byte) (n & 0xff);
+	}
+
+	/**
+	 * guaranteed to read exactly len bytes. throws error if it cant
+	 */
+	public static void readBytes(InputStream is, byte[] b, int offset, int len) {
+		if (len == 0)
+			return;
+		try {
+			int read = 0;
+			while (read < len) {
+				int n = is.read(b, offset + read, len - read);
+				if (n < 1)
+					throw new RuntimeException("error reading bytes, " + n + " !=" + len);
+				read += n;
+			}
+		} catch (IOException e) {
+			throw new PngjInputException("error reading", e);
+		}
+	}
+
+	public static void writeBytes(OutputStream os, byte[] b) {
+		try {
+			os.write(b);
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	public static void writeBytes(OutputStream os, byte[] b, int offset, int n) {
+		try {
+			os.write(b, offset, n);
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	public static void logdebug(String msg) {
+		if (DEBUG)
+			System.out.println(msg);
+	}
+
+	public static Set<String> asSet(String... values) {
+		return new HashSet<String>(java.util.Arrays.asList(values));
+	}
+
+	public static Set<String> unionSets(Set<String> set1, Set<String> set2) {
+		Set<String> s = new HashSet<String>();
+		s.addAll(set1);
+		s.addAll(set2);
+		return s;
+	}
+
+	public static Set<String> unionSets(Set<String> set1, Set<String> set2, Set<String> set3) {
+		Set<String> s = new HashSet<String>();
+		s.addAll(set1);
+		s.addAll(set2);
+		s.addAll(set3);
+		return s;
+	}
+
+	private static final ThreadLocal<CRC32> crcProvider = new ThreadLocal<CRC32>() {
+		protected CRC32 initialValue() {
+			return new CRC32();
+		}
+	};
+
+	/** thread-singleton crc engine */
+	public static CRC32 getCRC() {
+		return crcProvider.get();
+	}
+
+	static final byte[] pngIdBytes = { -119, 80, 78, 71, 13, 10, 26, 10 }; // png magic
+
+	public static double resMetersToDpi(long res) {
+		return (double) res * 0.0254;
+	}
+
+	public static long resDpiToMeters(double dpi) {
+		return (long) (dpi / 0.0254 + 0.5);
+	}
+
+	public static int doubleToInt100000(double d) {
+		return (int) (d * 100000.0 + 0.5);
+	}
+
+	public static double intToDouble100000(int i) {
+		return i / 100000.0;
+	}
+
+	public static int clampTo_0_255(int i) {
+		return i > 255 ? 255 : (i < 0 ? 0 : i);
+	}
+
+	public static int clampTo_0_65535(int i) {
+		return i > 65535 ? 65535 : (i < 0 ? 0 : i);
+	}
+
+	public static int clampTo_128_127(int x) {
+		return x > 127 ? 127 : (x < -128 ? -128 : x);
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkInputStream.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkInputStream.java
new file mode 100644
index 0000000..66c4b49
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkInputStream.java
@@ -0,0 +1,153 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.CRC32;
+
+import jogamp.opengl.util.pngj.chunks.ChunkHelper;
+
+
+/**
+ * Reads IDAT chunks
+ */
+class PngIDatChunkInputStream extends InputStream {
+	private final InputStream inputStream;
+	private final CRC32 crcEngine;
+	private int lenLastChunk;
+	private byte[] idLastChunk = new byte[4];
+	private int toReadThisChunk = 0;
+	private boolean ended = false;
+	private long offset; // offset inside inputstream
+
+	// just informational
+	static class IdatChunkInfo {
+		public final int len;
+		public final int offset;
+
+		private IdatChunkInfo(int len, int offset) {
+			this.len = len;
+			this.offset = offset;
+		}
+	}
+
+	List<IdatChunkInfo> foundChunksInfo = new ArrayList<IdatChunkInfo>();
+
+	/**
+	 * Constructor must be called just after reading length and id of first IDAT chunk
+	 **/
+	PngIDatChunkInputStream(InputStream iStream, int lenFirstChunk, int offset) {
+		this.offset = (long) offset;
+		inputStream = iStream;
+		crcEngine = new CRC32();
+		this.lenLastChunk = lenFirstChunk;
+		toReadThisChunk = lenFirstChunk;
+		// we know it's a IDAT
+		System.arraycopy(ChunkHelper.b_IDAT, 0, idLastChunk, 0, 4);
+		crcEngine.update(idLastChunk, 0, 4);
+		foundChunksInfo.add(new IdatChunkInfo(lenLastChunk, offset - 8));
+		// PngHelper.logdebug("IDAT Initial fragment: len=" + lenLastChunk);
+		if (this.lenLastChunk == 0)
+			endChunkGoForNext(); // rare, but...
+	}
+
+	/**
+	 * does NOT close the associated stream!
+	 */
+	@Override
+	public void close() throws IOException {
+		super.close(); // nothing
+	}
+
+	private void endChunkGoForNext() {
+		// Called after readging the last byte of chunk
+		// Checks CRC, and read ID from next CHUNK
+		// Those values are left in idLastChunk / lenLastChunk
+		// Skips empty IDATS
+		do {
+			int crc = PngHelper.readInt4(inputStream); //
+			offset += 4;
+			int crccalc = (int) crcEngine.getValue();
+			if (lenLastChunk > 0 && crc != crccalc)
+				throw new PngjBadCrcException("error reading idat; offset: " + offset);
+			crcEngine.reset();
+			lenLastChunk = PngHelper.readInt4(inputStream);
+			if (lenLastChunk < 0)
+				throw new PngjInputException("invalid len for chunk: " + lenLastChunk);
+			toReadThisChunk = lenLastChunk;
+			PngHelper.readBytes(inputStream, idLastChunk, 0, 4);
+			offset += 8;
+			ended = !Arrays.equals(idLastChunk, ChunkHelper.b_IDAT);
+			if (!ended) {
+				foundChunksInfo.add(new IdatChunkInfo(lenLastChunk, (int) (offset - 8)));
+				crcEngine.update(idLastChunk, 0, 4);
+			}
+			// PngHelper.logdebug("IDAT ended. next len= " + lenLastChunk + " idat?" +
+			// (!ended));
+		} while (lenLastChunk == 0 && !ended);
+		// rarely condition is true (empty IDAT ??)
+	}
+
+	/**
+	 * sometimes last row read does not fully consumes the chunk here we read the reamaing dummy bytes
+	 */
+	void forceChunkEnd() {
+		if (!ended) {
+			byte[] dummy = new byte[toReadThisChunk];
+			PngHelper.readBytes(inputStream, dummy, 0, toReadThisChunk);
+			crcEngine.update(dummy, 0, toReadThisChunk);
+			endChunkGoForNext();
+		}
+	}
+
+	/**
+	 * This can return less than len, but never 0 Returns -1 if "pseudo file" ended prematurely. That is our error.
+	 */
+	@Override
+	public int read(byte[] b, int off, int len) throws IOException {
+		if (toReadThisChunk == 0)
+			throw new RuntimeException("this should not happen");
+		int n = inputStream.read(b, off, len >= toReadThisChunk ? toReadThisChunk : len);
+		if (n > 0) {
+			crcEngine.update(b, off, n);
+			this.offset += n;
+			toReadThisChunk -= n;
+		}
+		if (toReadThisChunk == 0) { // end of chunk: prepare for next
+			endChunkGoForNext();
+		}
+		return n;
+	}
+
+	@Override
+	public int read(byte[] b) throws IOException {
+		return this.read(b, 0, b.length);
+	}
+
+	@Override
+	public int read() throws IOException {
+		// PngHelper.logdebug("read() should go here");
+		// inneficient - but this should be used rarely
+		byte[] b1 = new byte[1];
+		int r = this.read(b1, 0, 1);
+		return r < 0 ? -1 : (int) b1[0];
+	}
+
+	int getLenLastChunk() {
+		return lenLastChunk;
+	}
+
+	byte[] getIdLastChunk() {
+		return idLastChunk;
+	}
+
+	long getOffset() {
+		return offset;
+	}
+
+	boolean isEnded() {
+		return ended;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkOutputStream.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkOutputStream.java
new file mode 100644
index 0000000..8b9fa5d
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngIDatChunkOutputStream.java
@@ -0,0 +1,31 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.OutputStream;
+
+import jogamp.opengl.util.pngj.chunks.ChunkHelper;
+import jogamp.opengl.util.pngj.chunks.ChunkRaw;
+
+
+/**
+ * outputs the stream for IDAT chunk , fragmented at fixed size (16384 default).
+ */
+class PngIDatChunkOutputStream extends ProgressiveOutputStream {
+	private static final int SIZE_DEFAULT = 16384;
+	private final OutputStream outputStream;
+
+	PngIDatChunkOutputStream(OutputStream outputStream) {
+		this(outputStream, SIZE_DEFAULT);
+	}
+
+	PngIDatChunkOutputStream(OutputStream outputStream, int size) {
+		super(size);
+		this.outputStream = outputStream;
+	}
+
+	@Override
+	public final void flushBuffer(byte[] b, int len) {
+		ChunkRaw c = new ChunkRaw(len, ChunkHelper.b_IDAT, false);
+		c.data = b;
+		c.writeChunk(outputStream);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java
new file mode 100644
index 0000000..7343893
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngReader.java
@@ -0,0 +1,415 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.InflaterInputStream;
+
+import jogamp.opengl.util.pngj.PngIDatChunkInputStream.IdatChunkInfo;
+import jogamp.opengl.util.pngj.chunks.ChunkHelper;
+import jogamp.opengl.util.pngj.chunks.ChunkList;
+import jogamp.opengl.util.pngj.chunks.ChunkLoadBehaviour;
+import jogamp.opengl.util.pngj.chunks.ChunkRaw;
+import jogamp.opengl.util.pngj.chunks.PngChunk;
+import jogamp.opengl.util.pngj.chunks.PngChunkIHDR;
+import jogamp.opengl.util.pngj.chunks.PngMetadata;
+
+
+/**
+ * Reads a PNG image, line by line
+ */
+public class PngReader {
+	/**
+	 * Basic image info - final and inmutable.
+	 */
+	public final ImageInfo imgInfo;
+	protected final String filename; // not necesarily a file, can be a description - merely informative
+
+	private static int MAX_BYTES_CHUNKS_TO_LOAD = 640000;
+	private ChunkLoadBehaviour chunkLoadBehaviour = ChunkLoadBehaviour.LOAD_CHUNK_ALWAYS;
+
+	private final InputStream is;
+	private InflaterInputStream idatIstream;
+	private PngIDatChunkInputStream iIdatCstream;
+
+	protected int currentChunkGroup = -1;
+	protected int rowNum = -1; // current row number
+	private int offset = 0;
+	private int bytesChunksLoaded; // bytes loaded from anciallary chunks
+
+	protected ImageLine imgLine;
+
+	// line as bytes, counting from 1 (index 0 is reserved for filter type)
+	protected byte[] rowb = null;
+	protected byte[] rowbprev = null; // rowb previous
+	protected byte[] rowbfilter = null; // current line 'filtered': exactly as in uncompressed stream
+
+	/**
+	 * All chunks loaded. Criticals are included, except that all IDAT chunks appearance are replaced by a single
+	 * dummy-marker IDAT chunk. These might be copied to the PngWriter
+	 */
+	private final ChunkList chunksList;
+	private final PngMetadata metadata; // this a wrapper over chunks
+
+	/**
+	 * Constructs a PngReader from an InputStream.
+	 * <p>
+	 * See also <code>FileHelper.createPngReader(File f)</code> if available.
+	 * 
+	 * Reads only the signature and first chunk (IDHR)
+	 * 
+	 * @param filenameOrDescription
+	 *            : Optional, can be a filename or a description. Just for error/debug messages
+	 * 
+	 */
+	public PngReader(InputStream inputStream, String filenameOrDescription) {
+		this.filename = filenameOrDescription == null ? "" : filenameOrDescription;
+		this.is = inputStream;
+		this.chunksList = new ChunkList(null);
+		this.metadata = new PngMetadata(chunksList, true);
+		// reads header (magic bytes)
+		byte[] pngid = new byte[PngHelper.pngIdBytes.length];
+		PngHelper.readBytes(is, pngid, 0, pngid.length);
+		offset += pngid.length;
+		if (!Arrays.equals(pngid, PngHelper.pngIdBytes))
+			throw new PngjInputException("Bad PNG signature");
+		// reads first chunk
+		currentChunkGroup = ChunkList.CHUNK_GROUP_0_IDHR;
+		int clen = PngHelper.readInt4(is);
+		offset += 4;
+		if (clen != 13)
+			throw new RuntimeException("IDHR chunk len != 13 ?? " + clen);
+		byte[] chunkid = new byte[4];
+		PngHelper.readBytes(is, chunkid, 0, 4);
+		if (!Arrays.equals(chunkid, ChunkHelper.b_IHDR))
+			throw new PngjInputException("IHDR not found as first chunk??? [" + ChunkHelper.toString(chunkid) + "]");
+		offset += 4;
+		ChunkRaw chunk = new ChunkRaw(clen, chunkid, true);
+		String chunkids = ChunkHelper.toString(chunkid);
+		offset += chunk.readChunkData(is);
+		PngChunkIHDR ihdr = (PngChunkIHDR) addChunkToList(chunk);
+		boolean alpha = (ihdr.getColormodel() & 0x04) != 0;
+		boolean palette = (ihdr.getColormodel() & 0x01) != 0;
+		boolean grayscale = (ihdr.getColormodel() == 0 || ihdr.getColormodel() == 4);
+		imgInfo = new ImageInfo(ihdr.getCols(), ihdr.getRows(), ihdr.getBitspc(), alpha, grayscale, palette);
+		imgLine = new ImageLine(imgInfo);
+		if (ihdr.getInterlaced() != 0)
+			throw new PngjUnsupportedException("PNG interlaced not supported by this library");
+		if (ihdr.getFilmeth() != 0 || ihdr.getCompmeth() != 0)
+			throw new PngjInputException("compmethod o filtermethod unrecognized");
+		if (ihdr.getColormodel() < 0 || ihdr.getColormodel() > 6 || ihdr.getColormodel() == 1
+				|| ihdr.getColormodel() == 5)
+			throw new PngjInputException("Invalid colormodel " + ihdr.getColormodel());
+		if (ihdr.getBitspc() != 1 && ihdr.getBitspc() != 2 && ihdr.getBitspc() != 4 && ihdr.getBitspc() != 8
+				&& ihdr.getBitspc() != 16)
+			throw new PngjInputException("Invalid bit depth " + ihdr.getBitspc());
+		// allocation: one extra byte for filter type one pixel
+		rowbfilter = new byte[imgInfo.bytesPerRow + 1];
+		rowb = new byte[imgInfo.bytesPerRow + 1];
+		rowbprev = new byte[rowb.length];
+	}
+
+	private static class FoundChunkInfo {
+		public final String id;
+		public final int len;
+		public final int offset;
+		public final boolean loaded;
+
+		private FoundChunkInfo(String id, int len, int offset, boolean loaded) {
+			this.id = id;
+			this.len = len;
+			this.offset = offset;
+			this.loaded = loaded;
+		}
+
+		public String toString() {
+			return "chunk " + id + " len=" + len + " offset=" + offset + (this.loaded ? " " : " X ");
+		}
+	}
+
+	private PngChunk addChunkToList(ChunkRaw chunk) {
+		// this requires that the currentChunkGroup is ok
+		PngChunk chunkType = PngChunk.factory(chunk, imgInfo);
+		if (!chunkType.crit) {
+			bytesChunksLoaded += chunk.len;
+		}
+		if (bytesChunksLoaded > MAX_BYTES_CHUNKS_TO_LOAD) {
+			throw new PngjInputException("Chunk exceeded available space (" + MAX_BYTES_CHUNKS_TO_LOAD + ") chunk: "
+					+ chunk + " See PngReader.MAX_BYTES_CHUNKS_TO_LOAD\n");
+		}
+		chunksList.appendReadChunk(chunkType, currentChunkGroup);
+		return chunkType;
+	}
+
+	/**
+	 * Reads chunks before first IDAT. Position before: after IDHR (crc included) Position after: just after the first
+	 * IDAT chunk id
+	 * 
+	 * This can be called several times (tentatively), it does nothing if already run
+	 * 
+	 * (Note: when should this be called? in the constructor? hardly, because we loose the opportunity to call
+	 * setChunkLoadBehaviour() and perhaps other settings before reading the first row? but sometimes we want to access
+	 * some metadata (plte, phys) before. Because of this, this method can be called explicitly but is also called
+	 * implicititly in some methods (getMetatada(), getChunks())
+	 * 
+	 **/
+	public void readFirstChunks() {
+		if (!firstChunksNotYetRead())
+			return;
+		int clen = 0;
+		boolean found = false;
+		byte[] chunkid = new byte[4]; // it's important to reallocate in each iteration
+		currentChunkGroup = ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+		while (!found) {
+			clen = PngHelper.readInt4(is);
+			offset += 4;
+			if (clen < 0)
+				break;
+			PngHelper.readBytes(is, chunkid, 0, 4);
+			offset += 4;
+			if (Arrays.equals(chunkid, ChunkHelper.b_IDAT)) {
+				found = true;
+				currentChunkGroup = ChunkList.CHUNK_GROUP_4_IDAT;
+				// add dummy idat chunk to list
+				ChunkRaw chunk = new ChunkRaw(0, chunkid, false);
+				addChunkToList(chunk);
+				break;
+			} else if (Arrays.equals(chunkid, ChunkHelper.b_IEND)) {
+				throw new PngjInputException("END chunk found before image data (IDAT) at offset=" + offset);
+			}
+			ChunkRaw chunk = new ChunkRaw(clen, chunkid, true);
+			String chunkids = ChunkHelper.toString(chunkid);
+			boolean loadchunk = ChunkHelper.shouldLoad(chunkids, chunkLoadBehaviour);
+			offset += chunk.readChunkData(is);
+			if (chunkids.equals(ChunkHelper.PLTE))
+				currentChunkGroup = ChunkList.CHUNK_GROUP_2_PLTE;
+			if (loadchunk)
+				addChunkToList(chunk);
+			if (chunkids.equals(ChunkHelper.PLTE))
+				currentChunkGroup = ChunkList.CHUNK_GROUP_3_AFTERPLTE;
+		}
+		int idatLen = found ? clen : -1;
+		if (idatLen < 0)
+			throw new PngjInputException("first idat chunk not found!");
+		iIdatCstream = new PngIDatChunkInputStream(is, idatLen, offset);
+		idatIstream = new InflaterInputStream(iIdatCstream);
+	}
+
+	/**
+	 * Reads (and processes) chunks after last IDAT.
+	 **/
+	private void readLastChunks() {
+		// PngHelper.logdebug("idat ended? " + iIdatCstream.isEnded());
+		currentChunkGroup = ChunkList.CHUNK_GROUP_5_AFTERIDAT;
+		if (!iIdatCstream.isEnded())
+			iIdatCstream.forceChunkEnd();
+		int clen = iIdatCstream.getLenLastChunk();
+		byte[] chunkid = iIdatCstream.getIdLastChunk();
+		boolean endfound = false;
+		boolean first = true;
+		boolean ignore = false;
+		while (!endfound) {
+			ignore = false;
+			if (!first) {
+				clen = PngHelper.readInt4(is);
+				offset += 4;
+				if (clen < 0)
+					throw new PngjInputException("bad len " + clen);
+				PngHelper.readBytes(is, chunkid, 0, 4);
+				offset += 4;
+			}
+			first = false;
+			if (Arrays.equals(chunkid, ChunkHelper.b_IDAT)) {
+				// PngHelper.logdebug("extra IDAT chunk len - ignoring : ");
+				ignore = true;
+			} else if (Arrays.equals(chunkid, ChunkHelper.b_IEND)) {
+				currentChunkGroup = ChunkList.CHUNK_GROUP_6_END;
+				endfound = true;
+			}
+			ChunkRaw chunk = new ChunkRaw(clen, chunkid, true);
+			String chunkids = ChunkHelper.toString(chunkid);
+			boolean loadchunk = ChunkHelper.shouldLoad(chunkids, chunkLoadBehaviour);
+			offset += chunk.readChunkData(is);
+			if (loadchunk && !ignore) {
+				addChunkToList(chunk);
+			}
+		}
+		if (!endfound)
+			throw new PngjInputException("end chunk not found - offset=" + offset);
+		// PngHelper.logdebug("end chunk found ok offset=" + offset);
+	}
+
+	/**
+	 * Calls <code>readRow(int[] buffer, int nrow)</code> using internal ImageLine as buffer. This doesn't allocate or
+	 * copy anything.
+	 * 
+	 * @return The ImageLine that also is available inside this object.
+	 */
+	public ImageLine readRow(int nrow) {
+		readRow(imgLine.scanline, nrow);
+		imgLine.filterUsed = FilterType.getByVal(rowbfilter[0]);
+		imgLine.setRown(nrow);
+		return imgLine;
+	}
+
+	/**
+	 * Reads a line and returns it as a int[] array.
+	 * 
+	 * You can pass (optionally) a prealocatted buffer.
+	 * 
+	 * @param buffer
+	 *            Prealocated buffer, or null.
+	 * @param nrow
+	 *            Row number (0 is top). This is mostly for checking, because this library reads rows in sequence.
+	 * 
+	 * @return The scanline in the same passwd buffer if it was allocated, a newly allocated one otherwise
+	 */
+	public int[] readRow(int[] buffer, int nrow) {
+		if (nrow < 0 || nrow >= imgInfo.rows)
+			throw new PngjInputException("invalid line");
+		if (nrow != rowNum + 1)
+			throw new PngjInputException("invalid line (expected: " + (rowNum + 1));
+		if (nrow == 0 && firstChunksNotYetRead())
+			readFirstChunks();
+		rowNum++;
+		if (buffer == null || buffer.length < imgInfo.samplesPerRowP)
+			buffer = new int[imgInfo.samplesPerRowP];
+		// swap
+		byte[] tmp = rowb;
+		rowb = rowbprev;
+		rowbprev = tmp;
+		// loads in rowbfilter "raw" bytes, with filter
+		PngHelper.readBytes(idatIstream, rowbfilter, 0, rowbfilter.length);
+		rowb[0] = 0;
+		unfilterRow();
+		rowb[0] = rowbfilter[0];
+		convertRowFromBytes(buffer);
+		return buffer;
+	}
+
+	/**
+	 * This should be called after having read the last line. It reads extra chunks after IDAT, if present.
+	 */
+	public void end() {
+		offset = (int) iIdatCstream.getOffset();
+		try {
+			idatIstream.close();
+		} catch (Exception e) {
+		}
+		readLastChunks();
+		try {
+			is.close();
+		} catch (Exception e) {
+			throw new PngjInputException("error closing input stream!", e);
+		}
+	}
+
+	private void convertRowFromBytes(int[] buffer) {
+		// http://www.libpng.org/pub/png/spec/1.2/PNG-DataRep.html
+		int i, j;
+		if (imgInfo.bitDepth <= 8) {
+			for (i = 0, j = 1; i < imgInfo.samplesPerRowP; i++) {
+				buffer[i] = (rowb[j++] & 0xFF);
+			}
+		} else { // 16 bitspc
+			for (i = 0, j = 1; i < imgInfo.samplesPerRowP; i++) {
+				buffer[i] = ((rowb[j++] & 0xFF) << 8) + (rowb[j++] & 0xFF);
+			}
+		}
+	}
+
+	private void unfilterRow() {
+		int ftn = rowbfilter[0];
+		FilterType ft = FilterType.getByVal(ftn);
+		if (ft == null)
+			throw new PngjInputException("Filter type " + ftn + " invalid");
+		switch (ft) {
+		case FILTER_NONE:
+			unfilterRowNone();
+			break;
+		case FILTER_SUB:
+			unfilterRowSub();
+			break;
+		case FILTER_UP:
+			unfilterRowUp();
+			break;
+		case FILTER_AVERAGE:
+			unfilterRowAverage();
+			break;
+		case FILTER_PAETH:
+			unfilterRowPaeth();
+			break;
+		default:
+			throw new PngjInputException("Filter type " + ftn + " not implemented");
+		}
+	}
+
+	private void unfilterRowNone() {
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++) {
+			rowb[i] = (byte) (rowbfilter[i]);
+		}
+	}
+
+	private void unfilterRowSub() {
+		int i, j;
+		for (i = 1; i <= imgInfo.bytesPixel; i++) {
+			rowb[i] = (byte) (rowbfilter[i]);
+		}
+		for (j = 1, i = imgInfo.bytesPixel + 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			rowb[i] = (byte) (rowbfilter[i] + rowb[j]);
+		}
+	}
+
+	private void unfilterRowUp() {
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++) {
+			rowb[i] = (byte) (rowbfilter[i] + rowbprev[i]);
+		}
+	}
+
+	private void unfilterRowAverage() {
+		int i, j, x;
+		for (j = 1 - imgInfo.bytesPixel, i = 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			x = j > 0 ? (rowb[j] & 0xff) : 0;
+			rowb[i] = (byte) (rowbfilter[i] + (x + (rowbprev[i] & 0xFF)) / 2);
+		}
+	}
+
+	private void unfilterRowPaeth() {
+		int i, j, x, y;
+		for (j = 1 - imgInfo.bytesPixel, i = 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			x = j > 0 ? (rowb[j] & 0xFF) : 0;
+			y = j > 0 ? (rowbprev[j] & 0xFF) : 0;
+			rowb[i] = (byte) (rowbfilter[i] + FilterType.filterPaethPredictor(x, rowbprev[i] & 0xFF, y));
+		}
+	}
+
+	public ChunkLoadBehaviour getChunkLoadBehaviour() {
+		return chunkLoadBehaviour;
+	}
+
+	public void setChunkLoadBehaviour(ChunkLoadBehaviour chunkLoadBehaviour) {
+		this.chunkLoadBehaviour = chunkLoadBehaviour;
+	}
+
+	private boolean firstChunksNotYetRead() {
+		return currentChunkGroup < ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+	}
+
+	public ChunkList getChunksList() {
+		if (firstChunksNotYetRead())
+			readFirstChunks();
+		return chunksList;
+	}
+
+	public PngMetadata getMetadata() {
+		if (firstChunksNotYetRead())
+			readFirstChunks();
+		return metadata;
+	}
+
+	public String toString() { // basic info
+		return "filename=" + filename + " " + imgInfo.toString();
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java
new file mode 100644
index 0000000..ee8472b
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngWriter.java
@@ -0,0 +1,462 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+
+import jogamp.opengl.util.pngj.chunks.ChunkCopyBehaviour;
+import jogamp.opengl.util.pngj.chunks.ChunkHelper;
+import jogamp.opengl.util.pngj.chunks.ChunkList;
+import jogamp.opengl.util.pngj.chunks.PngChunk;
+import jogamp.opengl.util.pngj.chunks.PngChunkIEND;
+import jogamp.opengl.util.pngj.chunks.PngChunkIHDR;
+import jogamp.opengl.util.pngj.chunks.PngChunkTextVar;
+import jogamp.opengl.util.pngj.chunks.PngMetadata;
+
+
+/**
+ * Writes a PNG image, line by line.
+ */
+public class PngWriter {
+
+	public final ImageInfo imgInfo;
+
+	protected int compLevel = 6; // zip compression level 0 - 9
+	private int deflaterStrategy = Deflater.FILTERED;
+	protected FilterWriteStrategy filterStrat;
+
+	protected int currentChunkGroup = -1;
+	protected int rowNum = -1; // current line number
+
+	// current line, one (packed) sample per element (layout differnt from rowb!)
+	protected int[] scanline = null;
+	protected byte[] rowb = null; // element 0 is filter type!
+	protected byte[] rowbprev = null; // rowb prev
+	protected byte[] rowbfilter = null; // current line with filter
+
+	protected final OutputStream os;
+	protected final String filename; // optional, can be a description
+
+	private PngIDatChunkOutputStream datStream;
+	private DeflaterOutputStream datStreamDeflated;
+
+	private final ChunkList chunkList;
+	private final PngMetadata metadata; // high level wrapper over chunkList
+
+	public PngWriter(OutputStream outputStream, ImageInfo imgInfo) {
+		this(outputStream, imgInfo, "[NO FILENAME AVAILABLE]");
+	}
+
+	/**
+	 * Constructs a new PngWriter from a output stream.
+	 * <p>
+	 * See also <code>FileHelper.createPngWriter()</code> if available.
+	 * 
+	 * @param outputStream
+	 *            Opened stream for binary writing
+	 * @param imgInfo
+	 *            Basic image parameters
+	 * @param filenameOrDescription
+	 *            Optional, just for error/debug messages
+	 */
+	public PngWriter(OutputStream outputStream, ImageInfo imgInfo, String filenameOrDescription) {
+		this.filename = filenameOrDescription == null ? "" : filenameOrDescription;
+		this.os = outputStream;
+		this.imgInfo = imgInfo;
+		// prealloc
+		scanline = new int[imgInfo.samplesPerRowP];
+		rowb = new byte[imgInfo.bytesPerRow + 1];
+		rowbprev = new byte[rowb.length];
+		rowbfilter = new byte[rowb.length];
+		datStream = new PngIDatChunkOutputStream(this.os);
+		chunkList = new ChunkList(imgInfo);
+		metadata = new PngMetadata(chunkList, false);
+		filterStrat = new FilterWriteStrategy(imgInfo, FilterType.FILTER_DEFAULT);
+	}
+
+	/**
+	 * Write id signature and also "IHDR" chunk
+	 */
+	private void writeSignatureAndIHDR() {
+		currentChunkGroup = ChunkList.CHUNK_GROUP_0_IDHR;
+		if (datStreamDeflated == null) {
+			Deflater def = new Deflater(compLevel);
+			def.setStrategy(deflaterStrategy);
+			datStreamDeflated = new DeflaterOutputStream(datStream, def, 8192);
+		}
+		PngHelper.writeBytes(os, PngHelper.pngIdBytes); // signature
+		PngChunkIHDR ihdr = new PngChunkIHDR(imgInfo);
+		// http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
+		ihdr.setCols(imgInfo.cols);
+		ihdr.setRows(imgInfo.rows);
+		ihdr.setBitspc(imgInfo.bitDepth);
+		int colormodel = 0;
+		if (imgInfo.alpha)
+			colormodel += 0x04;
+		if (imgInfo.indexed)
+			colormodel += 0x01;
+		if (!imgInfo.greyscale)
+			colormodel += 0x02;
+		ihdr.setColormodel(colormodel);
+		ihdr.setCompmeth(0); // compression method 0=deflate
+		ihdr.setFilmeth(0); // filter method (0)
+		ihdr.setInterlaced(0); // we never interlace
+		ihdr.createChunk().writeChunk(os);
+
+	}
+
+	private void writeFirstChunks() {
+		int nw = 0;
+		currentChunkGroup = ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+		nw = chunkList.writeChunks(os, currentChunkGroup);
+		currentChunkGroup = ChunkList.CHUNK_GROUP_2_PLTE;
+		nw = chunkList.writeChunks(os, currentChunkGroup);
+		if (nw > 0 && imgInfo.greyscale)
+			throw new PngjOutputException("cannot write palette for this format");
+		if (nw == 0 && imgInfo.indexed)
+			throw new PngjOutputException("missing palette");
+		currentChunkGroup = ChunkList.CHUNK_GROUP_3_AFTERPLTE;
+		nw = chunkList.writeChunks(os, currentChunkGroup);
+		currentChunkGroup = ChunkList.CHUNK_GROUP_4_IDAT;
+	}
+
+	private void writeLastChunks() { // not including end
+		currentChunkGroup = ChunkList.CHUNK_GROUP_5_AFTERIDAT;
+		chunkList.writeChunks(os, currentChunkGroup);
+		// should not be unwriten chunks
+		List<PngChunk> pending = chunkList.getQueuedChunks();
+		if (!pending.isEmpty())
+			throw new PngjOutputException(pending.size() + " chunks were not written! Eg: " + pending.get(0).toString());
+		currentChunkGroup = ChunkList.CHUNK_GROUP_6_END;
+	}
+
+	private void writeEndChunk() {
+		PngChunkIEND c = new PngChunkIEND(imgInfo);
+		c.createChunk().writeChunk(os);
+	}
+
+	/**
+	 * Writes a full image row. This must be called sequentially from n=0 to n=rows-1 One integer per sample , in the
+	 * natural order: R G B R G B ... (or R G B A R G B A... if has alpha) The values should be between 0 and 255 for 8
+	 * bitspc images, and between 0- 65535 form 16 bitspc images (this applies also to the alpha channel if present) The
+	 * array can be reused.
+	 * 
+	 * @param newrow
+	 *            Array of pixel values
+	 * @param rown
+	 *            Row number, from 0 (top) to rows-1 (bottom). This is just used as a check. Pass -1 if you want to
+	 *            autocompute it
+	 */
+	public void writeRow(int[] newrow, int rown) {
+		if (rown == 0) {
+			writeSignatureAndIHDR();
+			writeFirstChunks();
+		}
+		if (rown < -1 || rown > imgInfo.rows)
+			throw new RuntimeException("invalid value for row " + rown);
+		rowNum++;
+		if (rown >= 0 && rowNum != rown)
+			throw new RuntimeException("rows must be written in strict consecutive order: tried to write row " + rown
+					+ ", expected=" + rowNum);
+		scanline = newrow;
+		// swap
+		byte[] tmp = rowb;
+		rowb = rowbprev;
+		rowbprev = tmp;
+		convertRowToBytes();
+		filterRow(rown);
+		try {
+			datStreamDeflated.write(rowbfilter, 0, imgInfo.bytesPerRow + 1);
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	/**
+	 * Same as writeRow(int[] newrow, int rown), but does not check row number
+	 * 
+	 * @param newrow
+	 */
+	public void writeRow(int[] newrow) {
+		writeRow(newrow, -1);
+	}
+
+	/**
+	 * Writes line. See writeRow(int[] newrow, int rown)
+	 */
+	public void writeRow(ImageLine imgline, int rownumber) {
+		writeRow(imgline.scanline, rownumber);
+	}
+
+	/**
+	 * Writes line, checks that the row number is consistent with that of the ImageLine See writeRow(int[] newrow, int
+	 * rown)
+	 * 
+	 * @deprecated Better use writeRow(ImageLine imgline, int rownumber)
+	 */
+	public void writeRow(ImageLine imgline) {
+		writeRow(imgline.scanline, imgline.getRown());
+	}
+
+	/**
+	 * Finalizes the image creation and closes the stream. This MUST be called after writing the lines.
+	 */
+	public void end() {
+		if (rowNum != imgInfo.rows - 1)
+			throw new PngjOutputException("all rows have not been written");
+		try {
+			datStreamDeflated.finish();
+			datStream.flush();
+			writeLastChunks();
+			writeEndChunk();
+			os.close();
+		} catch (IOException e) {
+			throw new PngjOutputException(e);
+		}
+	}
+
+	private int[] histox = new int[256]; // auxiliar buffer, only used by reportResultsForFilter
+
+	private void reportResultsForFilter(int rown, FilterType type, boolean tentative) {
+		Arrays.fill(histox, 0);
+		int s = 0, v;
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++) {
+			v = rowbfilter[i];
+			if (v < 0)
+				s -= (int) v;
+			else
+				s += (int) v;
+			histox[v & 0xFF]++;
+		}
+		filterStrat.fillResultsForFilter(rown, type, s, histox, tentative);
+	}
+
+	private void filterRow(int rown) {
+		// warning: filters operation rely on: "previos row" (rowbprev) is
+		// initialized to 0 the first time
+		if (filterStrat.shouldTestAll(rown)) {
+			filterRowNone();
+			reportResultsForFilter(rown, FilterType.FILTER_NONE, true);
+			filterRowSub();
+			reportResultsForFilter(rown, FilterType.FILTER_SUB, true);
+			filterRowUp();
+			reportResultsForFilter(rown, FilterType.FILTER_UP, true);
+			filterRowAverage();
+			reportResultsForFilter(rown, FilterType.FILTER_AVERAGE, true);
+			filterRowPaeth();
+			reportResultsForFilter(rown, FilterType.FILTER_PAETH, true);
+		}
+		FilterType filterType = filterStrat.gimmeFilterType(rown, true);
+		rowbfilter[0] = (byte) filterType.val;
+		switch (filterType) {
+		case FILTER_NONE:
+			filterRowNone();
+			break;
+		case FILTER_SUB:
+			filterRowSub();
+			break;
+		case FILTER_UP:
+			filterRowUp();
+			break;
+		case FILTER_AVERAGE:
+			filterRowAverage();
+			break;
+		case FILTER_PAETH:
+			filterRowPaeth();
+			break;
+		default:
+			throw new PngjOutputException("Filter type " + filterType + " not implemented");
+		}
+		reportResultsForFilter(rown, filterType, false);
+	}
+
+	protected int sumRowbfilter() { // sums absolute value
+		int s = 0;
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++)
+			if (rowbfilter[i] < 0)
+				s -= (int) rowbfilter[i];
+			else
+				s += (int) rowbfilter[i];
+		return s;
+	}
+
+	protected void filterRowNone() {
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++) {
+			rowbfilter[i] = (byte) rowb[i];
+		}
+	}
+
+	protected void filterRowSub() {
+		int i, j;
+		for (i = 1; i <= imgInfo.bytesPixel; i++)
+			rowbfilter[i] = (byte) rowb[i];
+		for (j = 1, i = imgInfo.bytesPixel + 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			rowbfilter[i] = (byte) (rowb[i] - rowb[j]);
+		}
+	}
+
+	protected void filterRowUp() {
+		for (int i = 1; i <= imgInfo.bytesPerRow; i++) {
+			rowbfilter[i] = (byte) (rowb[i] - rowbprev[i]);
+		}
+	}
+
+	protected void filterRowAverage() {
+		int i, j;
+		for (j = 1 - imgInfo.bytesPixel, i = 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			rowbfilter[i] = (byte) (rowb[i] - ((rowbprev[i] & 0xFF) + (j > 0 ? (rowb[j] & 0xFF) : 0)) / 2);
+		}
+	}
+
+	protected void filterRowPaeth() {
+		int i, j;
+		for (j = 1 - imgInfo.bytesPixel, i = 1; i <= imgInfo.bytesPerRow; i++, j++) {
+			rowbfilter[i] = (byte) (rowb[i] - FilterType.filterPaethPredictor(j > 0 ? (rowb[j] & 0xFF) : 0,
+					rowbprev[i] & 0xFF, j > 0 ? (rowbprev[j] & 0xFF) : 0));
+		}
+	}
+
+	protected void convertRowToBytes() {
+		// http://www.libpng.org/pub/png/spec/1.2/PNG-DataRep.html
+		int i, j;
+		if (imgInfo.bitDepth <= 8) {
+			for (i = 0, j = 1; i < imgInfo.samplesPerRowP; i++) {
+				rowb[j++] = (byte) (scanline[i]);
+			}
+		} else { // 16 bitspc
+			for (i = 0, j = 1; i < imgInfo.samplesPerRowP; i++) {
+				// x = (int) (scanline[i]) & 0xFFFF;
+				rowb[j++] = (byte) (scanline[i] >> 8);
+				rowb[j++] = (byte) (scanline[i]);
+			}
+		}
+	}
+
+	// /// several getters / setters - all this setters are optional
+
+	/**
+	 * Filename or description, from the optional constructor argument.
+	 */
+	public String getFilename() {
+		return filename;
+	}
+
+	/**
+	 * Sets internal prediction filter type, or strategy to choose it.
+	 * <p>
+	 * This must be called just after constructor, before starting writing.
+	 * <p>
+	 * See also setCompLevel()
+	 * 
+	 * @param filterType
+	 *            One of the five prediction types or strategy to choose it (see <code>PngFilterType</code>) Recommended
+	 *            values: DEFAULT (default) or AGGRESIVE
+	 */
+	public void setFilterType(FilterType filterType) {
+		filterStrat = new FilterWriteStrategy(imgInfo, filterType);
+	}
+
+	/**
+	 * Sets compression level of ZIP algorithm.
+	 * <p>
+	 * This must be called just after constructor, before starting writing.
+	 * <p>
+	 * See also setFilterType()
+	 * 
+	 * @param compLevel
+	 *            between 0 and 9 (default:6 , recommended: 6 or more)
+	 */
+	public void setCompLevel(int compLevel) {
+		if (compLevel < 0 || compLevel > 9)
+			throw new PngjException("Compression level invalid (" + compLevel + ") Must be 0..9");
+		this.compLevel = compLevel;
+	}
+
+	/**
+	 * copy chunks from reader - copy_mask : see ChunksToWrite.COPY_XXX
+	 * 
+	 * If we are after idat, only considers those chunks after IDAT in PngReader TODO: this should be more customizable
+	 */
+	private void copyChunks(PngReader reader, int copy_mask, boolean onlyAfterIdat) {
+		boolean idatDone = currentChunkGroup >= ChunkList.CHUNK_GROUP_4_IDAT;
+		for (PngChunk chunk : reader.getChunksList().getChunks()) {
+			int group = chunk.getChunkGroup();
+			if (group < ChunkList.CHUNK_GROUP_4_IDAT && idatDone)
+				continue;
+			boolean copy = false;
+			if (chunk.crit) {
+				if (chunk.id.equals(ChunkHelper.PLTE)) {
+					if (imgInfo.indexed && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_PALETTE))
+						copy = true;
+					if (!imgInfo.greyscale && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL))
+						copy = true;
+				}
+			} else { // ancillary
+				boolean text = (chunk instanceof PngChunkTextVar);
+				boolean safe = chunk.safe;
+				// notice that these if are not exclusive
+				if (ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL))
+					copy = true;
+				if (safe && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL_SAFE))
+					copy = true;
+				if (chunk.id.equals(ChunkHelper.tRNS)
+						&& ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_TRANSPARENCY))
+					copy = true;
+				if (chunk.id.equals(ChunkHelper.pHYs) && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_PHYS))
+					copy = true;
+				if (text && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_TEXTUAL))
+					copy = true;
+				if (ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALMOSTALL)
+						&& !(ChunkHelper.isUnknown(chunk) || text || chunk.id.equals(ChunkHelper.hIST) || chunk.id
+								.equals(ChunkHelper.tIME)))
+					copy = true;
+			}
+			if (copy) {
+				chunkList.queueChunk(PngChunk.cloneChunk(chunk, imgInfo), !chunk.allowsMultiple(), false);
+			}
+		}
+	}
+
+	/**
+	 * Copies first (pre IDAT) ancillary chunks from a PngReader.
+	 * <p>
+	 * Should be called when creating an image from another, before starting writing lines, to copy relevant chunks.
+	 * <p>
+	 * 
+	 * @param reader
+	 *            : PngReader object, already opened.
+	 * @param copy_mask
+	 *            : Mask bit (OR), see <code>ChunksToWrite.COPY_XXX</code> constants
+	 */
+	public void copyChunksFirst(PngReader reader, int copy_mask) {
+		copyChunks(reader, copy_mask, false);
+	}
+
+	/**
+	 * Copies last (post IDAT) ancillary chunks from a PngReader.
+	 * <p>
+	 * Should be called when creating an image from another, after writing all lines, before closing the writer, to copy
+	 * additional chunks.
+	 * <p>
+	 * 
+	 * @param reader
+	 *            : PngReader object, already opened and fully read.
+	 * @param copy_mask
+	 *            : Mask bit (OR), see <code>ChunksToWrite.COPY_XXX</code> constants
+	 */
+	public void copyChunksLast(PngReader reader, int copy_mask) {
+		copyChunks(reader, copy_mask, true);
+	}
+
+	public ChunkList getChunkList() {
+		return chunkList;
+	}
+
+	public PngMetadata getMetadata() {
+		return metadata;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjBadCrcException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjBadCrcException.java
new file mode 100644
index 0000000..3b74f86
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjBadCrcException.java
@@ -0,0 +1,20 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Exception thrown by bad CRC check
+ */
+public class PngjBadCrcException extends PngjInputException {
+	private static final long serialVersionUID = 1L;
+
+	public PngjBadCrcException(String message, Throwable cause) {
+		super(message, cause);
+	}
+
+	public PngjBadCrcException(String message) {
+		super(message);
+	}
+
+	public PngjBadCrcException(Throwable cause) {
+		super(cause);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java
new file mode 100644
index 0000000..4a45cb5
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjException.java
@@ -0,0 +1,23 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Generic exception
+ * 
+ * @author Hernan J Gonzalez
+ * 
+ */
+public class PngjException extends RuntimeException {
+	private static final long serialVersionUID = 1L;
+
+	public PngjException(String message, Throwable cause) {
+		super(message, cause);
+	}
+
+	public PngjException(String message) {
+		super(message);
+	}
+
+	public PngjException(Throwable cause) {
+		super(cause);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjInputException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjInputException.java
new file mode 100644
index 0000000..5cc36b9
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjInputException.java
@@ -0,0 +1,20 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Exception thrown by reading process
+ */
+public class PngjInputException extends PngjException {
+	private static final long serialVersionUID = 1L;
+
+	public PngjInputException(String message, Throwable cause) {
+		super(message, cause);
+	}
+
+	public PngjInputException(String message) {
+		super(message);
+	}
+
+	public PngjInputException(Throwable cause) {
+		super(cause);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjOutputException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjOutputException.java
new file mode 100644
index 0000000..c8cd36a
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjOutputException.java
@@ -0,0 +1,20 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Exception thrown by writing process
+ */
+public class PngjOutputException extends PngjException {
+	private static final long serialVersionUID = 1L;
+
+	public PngjOutputException(String message, Throwable cause) {
+		super(message, cause);
+	}
+
+	public PngjOutputException(String message) {
+		super(message);
+	}
+
+	public PngjOutputException(Throwable cause) {
+		super(cause);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/PngjUnsupportedException.java b/src/jogl/classes/jogamp/opengl/util/pngj/PngjUnsupportedException.java
new file mode 100644
index 0000000..0801e33
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/PngjUnsupportedException.java
@@ -0,0 +1,24 @@
+package jogamp.opengl.util.pngj;
+
+/**
+ * Exception thrown because of some valid feature of PNG standard that this library does not support
+ */
+public class PngjUnsupportedException extends RuntimeException {
+	private static final long serialVersionUID = 1L;
+
+	public PngjUnsupportedException() {
+		super();
+	}
+
+	public PngjUnsupportedException(String message, Throwable cause) {
+		super(message, cause);
+	}
+
+	public PngjUnsupportedException(String message) {
+		super(message);
+	}
+
+	public PngjUnsupportedException(Throwable cause) {
+		super(cause);
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/ProgressiveOutputStream.java b/src/jogl/classes/jogamp/opengl/util/pngj/ProgressiveOutputStream.java
new file mode 100644
index 0000000..bbec247
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/ProgressiveOutputStream.java
@@ -0,0 +1,71 @@
+package jogamp.opengl.util.pngj;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+/**
+ * stream that outputs to memory and allows to flush fragments every 'size' bytes to some other destination
+ */
+abstract class ProgressiveOutputStream extends ByteArrayOutputStream {
+	private final int size;
+
+	public ProgressiveOutputStream(int size) {
+		this.size = size;
+	}
+
+	@Override
+	public final void close() throws IOException {
+		flush();
+		super.close();
+	}
+
+	@Override
+	public final void flush() throws IOException {
+		super.flush();
+		checkFlushBuffer(true);
+	}
+
+	@Override
+	public final void write(byte[] b, int off, int len) {
+		super.write(b, off, len);
+		checkFlushBuffer(false);
+	}
+
+	@Override
+	public final void write(byte[] b) throws IOException {
+		super.write(b);
+		checkFlushBuffer(false);
+	}
+
+	@Override
+	public final void write(int arg0) {
+		super.write(arg0);
+		checkFlushBuffer(false);
+	}
+
+	@Override
+	public final synchronized void reset() {
+		super.reset();
+	}
+
+	/**
+	 * if it's time to flush data (or if forced==true) calls abstract method flushBuffer() and cleans those bytes from
+	 * own buffer
+	 */
+	private final void checkFlushBuffer(boolean forced) {
+		while (forced || count >= size) {
+			int nb = size;
+			if (nb > count)
+				nb = count;
+			if (nb == 0)
+				return;
+			flushBuffer(buf, nb);
+			int bytesleft = count - nb;
+			count = bytesleft;
+			if (bytesleft > 0)
+				System.arraycopy(buf, nb, buf, 0, bytesleft);
+		}
+	}
+
+	public abstract void flushBuffer(byte[] b, int n);
+}
\ No newline at end of file
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkCopyBehaviour.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkCopyBehaviour.java
new file mode 100644
index 0000000..43c0cb1
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkCopyBehaviour.java
@@ -0,0 +1,24 @@
+package jogamp.opengl.util.pngj.chunks;
+
+/**
+ * Chunk copy policy to apply when copyng from a pngReader to a pngWriter http://www.w3.org/TR/PNG/#14
+ * <p>
+ * These are masks, can be OR-ed
+ **/
+public class ChunkCopyBehaviour {
+
+	/** dont copy anywhing */
+	public static final int COPY_NONE = 0;
+
+	/** copy the palette */
+	public static final int COPY_PALETTE = 1;
+
+	/** copy all 'safe to copy' chunks */
+	public static final int COPY_ALL_SAFE = 1 << 2;
+	public static final int COPY_ALL = 1 << 3; // includes palette!
+	public static final int COPY_PHYS = 1 << 4; // dpi
+	public static final int COPY_TEXTUAL = 1 << 5; // all textual types
+	public static final int COPY_TRANSPARENCY = 1 << 6; //
+	public static final int COPY_UNKNOWN = 1 << 7; // all unknown (by the factory!)
+	public static final int COPY_ALMOSTALL = 1 << 8; // almost all known (except HIST and TIME and textual)
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java
new file mode 100644
index 0000000..26dafd4
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkHelper.java
@@ -0,0 +1,134 @@
+package jogamp.opengl.util.pngj.chunks;
+
+// see http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
+// http://www.w3.org/TR/PNG/#5Chunk-naming-conventions
+// http://www.w3.org/TR/PNG/#table53
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Set;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.InflaterInputStream;
+
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+public class ChunkHelper {
+	public static final String IHDR = "IHDR";
+	public static final String PLTE = "PLTE";
+	public static final String IDAT = "IDAT";
+	public static final String IEND = "IEND";
+	public static final byte[] b_IHDR = toBytes(IHDR);
+	public static final byte[] b_PLTE = toBytes(PLTE);
+	public static final byte[] b_IDAT = toBytes(IDAT);
+	public static final byte[] b_IEND = toBytes(IEND);
+
+	public static final String cHRM = "cHRM";
+	public static final String gAMA = "gAMA";
+	public static final String iCCP = "iCCP";
+	public static final String sBIT = "sBIT";
+	public static final String sRGB = "sRGB";
+	public static final String bKGD = "bKGD";
+	public static final String hIST = "hIST";
+	public static final String tRNS = "tRNS";
+	public static final String pHYs = "pHYs";
+	public static final String sPLT = "sPLT";
+	public static final String tIME = "tIME";
+	public static final String iTXt = "iTXt";
+	public static final String tEXt = "tEXt";
+	public static final String zTXt = "zTXt";
+
+	public static Set<String> KNOWN_CHUNKS_CRITICAL = PngHelper.asSet(IHDR, PLTE, IDAT, IEND);
+
+	public static byte[] toBytes(String x) {
+		return x.getBytes(PngHelper.charsetLatin1);
+	}
+
+	public static String toString(byte[] x) {
+		return new String(x, PngHelper.charsetLatin1);
+	}
+
+	public static boolean isCritical(String id) { // critical chunk ?
+		// first letter is uppercase
+		return (Character.isUpperCase(id.charAt(0)));
+	}
+
+	public static boolean isPublic(String id) { // public chunk?
+		// second letter is uppercase
+		return (Character.isUpperCase(id.charAt(1)));
+	}
+
+	/**
+	 * "Unknown" just means that our chunk factory (even when it has been augmented by client code) did not recognize its id
+	 */
+	public static boolean isUnknown(PngChunk c) {
+		return c instanceof PngChunkUNKNOWN;
+	}
+
+	public static boolean isSafeToCopy(String id) { // safe to copy?
+		// fourth letter is lower case
+		return (!Character.isUpperCase(id.charAt(3)));
+	}
+
+	public static int posNullByte(byte[] b) {
+		for (int i = 0; i < b.length; i++)
+			if (b[i] == 0)
+				return i;
+		return -1;
+	}
+
+	public static boolean shouldLoad(String id, ChunkLoadBehaviour behav) {
+		if (isCritical(id))
+			return true;
+		boolean kwown = PngChunk.isKnown(id);
+		switch (behav) {
+		case LOAD_CHUNK_ALWAYS:
+			return true;
+		case LOAD_CHUNK_IF_SAFE:
+			return kwown || isSafeToCopy(id);
+		case LOAD_CHUNK_KNOWN:
+			return kwown;
+		case LOAD_CHUNK_NEVER:
+			return false;
+		}
+		return false; // should not reach here
+	}
+
+	public final static byte[] compressBytes(byte[] ori, boolean compress) {
+		return compressBytes(ori, 0, ori.length, compress);
+	}
+
+	public static byte[] compressBytes(byte[] ori, int offset, int len, boolean compress) {
+		try {
+			ByteArrayInputStream inb = new ByteArrayInputStream(ori, offset, len);
+			InputStream in = compress ? inb : new InflaterInputStream(inb);
+			ByteArrayOutputStream outb = new ByteArrayOutputStream();
+			OutputStream out = compress ? new DeflaterOutputStream(outb) : outb;
+			shovelInToOut(in, out);
+			in.close();
+			out.close();
+			return outb.toByteArray();
+		} catch (Exception e) {
+			throw new PngjException(e);
+		}
+	}
+
+	/**
+	 * Shovels all data from an input stream to an output stream.
+	 */
+	private static void shovelInToOut(InputStream in, OutputStream out) throws IOException {
+		byte[] buffer = new byte[1024];
+		int len;
+		while ((len = in.read(buffer)) > 0) {
+			out.write(buffer, 0, len);
+		}
+	}
+
+	public static boolean maskMatch(int v, int mask) {
+		return (v & mask) != 0;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkList.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkList.java
new file mode 100644
index 0000000..badbbd0
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkList.java
@@ -0,0 +1,282 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+/**
+ * All chunks that form an image, read or to be written
+ * 
+ * chunks include all chunks, but IDAT is a single pseudo chunk without data
+ **/
+public class ChunkList {
+	// ref: http://www.w3.org/TR/PNG/#table53
+	public static final int CHUNK_GROUP_0_IDHR = 0; // required - single
+	public static final int CHUNK_GROUP_1_AFTERIDHR = 1; // optional - multiple
+	public static final int CHUNK_GROUP_2_PLTE = 2; // optional - single
+	public static final int CHUNK_GROUP_3_AFTERPLTE = 3; // optional - multple
+	public static final int CHUNK_GROUP_4_IDAT = 4; // required (single pseudo chunk)
+	public static final int CHUNK_GROUP_5_AFTERIDAT = 5; // optional - multple
+	public static final int CHUNK_GROUP_6_END = 6; // only 1 chunk - requried
+
+	/**
+	 * All chunks, read, written (does not include IHDR, IDAT, END for written)
+	 */
+	private List<PngChunk> chunks = new ArrayList<PngChunk>();
+
+	/**
+	 * chunks not yet writen - does not include IHDR, IDAT, END, perhaps yes PLTE
+	 */
+	private Set<PngChunk> queuedChunks = new LinkedHashSet<PngChunk>();
+
+	final ImageInfo imageInfo; // only required for writing
+
+	public ChunkList(ImageInfo imfinfo) {
+		this.imageInfo = imfinfo;
+	}
+
+	/**
+	 * Adds chunk in next position. This is used when reading
+	 */
+	public void appendReadChunk(PngChunk chunk, int chunkGroup) {
+		chunk.setChunkGroup(chunkGroup);
+		chunks.add(chunk);
+	}
+
+	public List<PngChunk> getById(String id, boolean includeQueued, boolean includeProcessed) {
+		List<PngChunk> list = new ArrayList<PngChunk>();
+		if (includeQueued)
+			for (PngChunk c : queuedChunks)
+				if (c.id.equals(id))
+					list.add(c);
+		if (includeProcessed)
+			for (PngChunk c : chunks)
+				if (c.id.equals(id))
+					list.add(c);
+		return list;
+	}
+
+	/**
+	 * Remove Chunk: only from queued
+	 */
+	public boolean removeChunk(PngChunk c) {
+		return queuedChunks.remove(c);
+	}
+
+	/**
+	 * add chunk to write queue
+	 */
+	public void queueChunk(PngChunk chunk, boolean replace, boolean priority) {
+		chunk.setPriority(priority);
+		if (replace) {
+			List<PngChunk> current = getById(chunk.id, true, false);
+			for (PngChunk chunk2 : current)
+				removeChunk(chunk2);
+		}
+		queuedChunks.add(chunk);
+	}
+
+	/**
+	 * this should be called only for ancillary chunks and PLTE (groups 1 - 3 - 5)
+	 **/
+	private static boolean shouldWrite(PngChunk c, int currentGroup) {
+		if (currentGroup == CHUNK_GROUP_2_PLTE)
+			return c.id.equals(ChunkHelper.PLTE);
+		if (currentGroup % 2 == 0)
+			throw new RuntimeException("?");
+		int minChunkGroup, maxChunkGroup;
+		if (c.mustGoBeforePLTE())
+			minChunkGroup = maxChunkGroup = ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+		else if (c.mustGoBeforeIDAT()) {
+			maxChunkGroup = ChunkList.CHUNK_GROUP_3_AFTERPLTE;
+			minChunkGroup = c.mustGoAfterPLTE() ? ChunkList.CHUNK_GROUP_3_AFTERPLTE : ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+		} else {
+			maxChunkGroup = ChunkList.CHUNK_GROUP_5_AFTERIDAT;
+			minChunkGroup = ChunkList.CHUNK_GROUP_1_AFTERIDHR;
+		}
+
+		int preferred = maxChunkGroup;
+		if (c.isWritePriority())
+			preferred = minChunkGroup;
+		if (ChunkHelper.isUnknown(c) && c.getChunkGroup() > 0)
+			preferred = c.getChunkGroup();
+		if (currentGroup == preferred)
+			return true;
+		if (currentGroup > preferred && currentGroup <= maxChunkGroup)
+			return true;
+		return false;
+	}
+
+	public int writeChunks(OutputStream os, int currentGroup) {
+		int cont = 0;
+		Iterator<PngChunk> it = queuedChunks.iterator();
+		while (it.hasNext()) {
+			PngChunk c = it.next();
+			if (!shouldWrite(c, currentGroup))
+				continue;
+			c.write(os);
+			chunks.add(c);
+			c.setChunkGroup(currentGroup);
+			it.remove();
+			cont++;
+		}
+		return cont;
+	}
+
+	/**
+	 * returns a copy of processed (read or writen) chunks
+	 */
+	public List<PngChunk> getChunks() {
+		return new ArrayList<PngChunk>(chunks);
+	}
+
+	public List<String> getChunksUnkown() {
+		List<String> l = new ArrayList<String>();
+		for (PngChunk chunk : chunks)
+			if (ChunkHelper.isUnknown(chunk))
+				l.add(chunk.id);
+		return l;
+	}
+
+	/**
+	 * returns a copy of queued (for write) chunks
+	 */
+	public List<PngChunk> getQueuedChunks() {
+		return new ArrayList<PngChunk>(queuedChunks);
+	}
+
+	/**
+	 * behaviour:
+	 * 
+	 * a chunk already processed matches : exception a chunk queued matches and overwrite=true: replace it , return true
+	 * a chunk queued matches and overwrite=false: do nothing, return false no matching: set it, return true
+	 * 
+	 * @param c
+	 * @param overwriteIfPresent
+	 * @return true if added chunk
+	 */
+	public boolean setChunk(PngChunk c, boolean overwriteIfPresent) {
+		List<PngChunk> list = getMatching(c, false, true); // processed
+		if (!list.isEmpty())
+			throw new PngjException("chunk " + c.id + " already set ");
+		list = getMatching(c, true, false); // queued
+		if (!list.isEmpty()) {
+			if (overwriteIfPresent) {
+				for (PngChunk cx : list)
+					removeChunk(cx);
+				queueChunk(c, false, false);
+				return true;
+			}
+			return false;
+		}
+		queueChunk(c, false, false);
+		return true;
+	}
+
+	/**
+	 * returns only one chunk or null if nothing found - does not include queued
+	 * 
+	 * If innerid!=null , the chunk is assumed to be PngChunkTextVar or PngChunkSPLT, and filtered by that id
+	 * 
+	 * If more than one chunk (after filtering by inner id) is found, then an exception is thrown (failifMultiple=true)
+	 * or the last one is returned (failifMultiple=false)
+	 **/
+	public PngChunk getChunk1(String id, String innerid, boolean failIfMultiple) {
+		List<PngChunk> list = getChunks(id);
+		if (list.isEmpty())
+			return null;
+		if (innerid != null) {
+			List<PngChunk> list2 = new ArrayList<PngChunk>();
+			for (PngChunk c : list) {
+				if (c instanceof PngChunkTextVar)
+					if (((PngChunkTextVar) c).getKey().equals(innerid))
+						list2.add(c);
+				if (c instanceof PngChunkSPLT)
+					if (((PngChunkSPLT) c).getPalName().equals(innerid))
+						list2.add(c);
+			}
+			list = list2;
+		}
+		if (list.isEmpty())
+			return null;
+		if (list.size() > 1 && failIfMultiple)
+			throw new PngjException("unexpected multiple chunks id=" + id);
+		return list.get(list.size() - 1);
+	}
+
+	public PngChunk getChunk1(String id) {
+		return getChunk1(id, null, true);
+	}
+	
+	public List<PngChunk> getChunks(String id) { // not including queued
+		return getById(id, false, true);
+	}
+
+	private List<PngChunk> getMatching(PngChunk cnew, boolean includeQueued, boolean includeProcessed) {
+		List<PngChunk> list = new ArrayList<PngChunk>();
+		if (includeQueued)
+			for (PngChunk c : getQueuedChunks())
+				if (matches(cnew, c))
+					list.add(c);
+		if (includeProcessed)
+			for (PngChunk c : getChunks())
+				if (matches(cnew, c))
+					list.add(c);
+		return list;
+	}
+
+	/**
+	 * MY adhoc criteria: two chunks "match" if they have same id and (perhaps, if multiple are allowed) if the match
+	 * also in some "internal key" (eg: key for string values, palette for sPLT, etc)
+	 * 
+	 * @return true if "matches"
+	 */
+	public static boolean matches(PngChunk c2, PngChunk c1) {
+		if (c1 == null || c2 == null || !c1.id.equals(c2.id))
+			return false;
+		// same id
+		if (c1.getClass() != c2.getClass())
+			return false; // should not happen
+		if (!c2.allowsMultiple())
+			return true;
+		if (c1 instanceof PngChunkTextVar) {
+			return ((PngChunkTextVar) c1).getKey().equals(((PngChunkTextVar) c2).getKey());
+		}
+		if (c1 instanceof PngChunkSPLT) {
+			return ((PngChunkSPLT) c1).getPalName().equals(((PngChunkSPLT) c2).getPalName());
+		}
+		// unknown chunks that allow multiple? consider they don't match
+		return false;
+	}
+	
+	public String toString() {
+		return "ChunkList: processed: " + chunks.size() + " queue: " + queuedChunks.size();
+	}
+
+	/**
+	 * for debugging
+	 */
+	public String toStringFull() {
+		StringBuilder sb = new StringBuilder(toString());
+		sb.append("\n Processed:\n");
+		for (PngChunk chunk : chunks) {
+			sb.append(chunk).append(" G=" + chunk.getChunkGroup() + "\n");
+		}
+		if (!queuedChunks.isEmpty()) {
+			sb.append(" Queued:\n");
+			for (PngChunk chunk : chunks) {
+				sb.append(chunk).append("\n");
+			}
+
+		}
+		return sb.toString();
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java
new file mode 100644
index 0000000..a3f8535
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkLoadBehaviour.java
@@ -0,0 +1,10 @@
+package jogamp.opengl.util.pngj.chunks;
+
+public enum ChunkLoadBehaviour {
+	// what to do with non critical chunks when reading?
+	LOAD_CHUNK_NEVER, /* ignore non-critical chunks */
+	LOAD_CHUNK_KNOWN, /* load chunk if 'known' */
+	LOAD_CHUNK_IF_SAFE, /* load chunk if 'known' or safe to copy */
+	LOAD_CHUNK_ALWAYS /* load chunk always */
+	;
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java
new file mode 100644
index 0000000..6770d5e
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/ChunkRaw.java
@@ -0,0 +1,83 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.CRC32;
+
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjBadCrcException;
+import jogamp.opengl.util.pngj.PngjOutputException;
+
+
+/**
+ * Wraps the raw chunk data Short lived object, to be created while serialing/deserializing Do not reuse it for
+ * different chunks
+ * 
+ * see http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
+ */
+public class ChunkRaw {
+	public final int len;
+	public final byte[] idbytes = new byte[4]; // 4 bytes
+	public byte[] data = null; // crc not included
+	private int crcval = 0;
+
+	// public int offset=-1; // only for read chunks - informational
+	public ChunkRaw(int len, byte[] idbytes, boolean alloc) {
+		this.len = len;
+		System.arraycopy(idbytes, 0, this.idbytes, 0, 4);
+		if (alloc)
+			allocData();
+	}
+
+	public void writeChunk(OutputStream os) {
+		if (idbytes.length != 4)
+			throw new PngjOutputException("bad chunkid [" + ChunkHelper.toString(idbytes) + "]");
+		computeCrc();
+		PngHelper.writeInt4(os, len);
+		PngHelper.writeBytes(os, idbytes);
+		if (len > 0)
+			PngHelper.writeBytes(os, data, 0, len);
+		// System.err.println("writing chunk " + this.toString() + "crc=" + crcval);
+
+		PngHelper.writeInt4(os, crcval);
+	}
+
+	/**
+	 * called after setting data, before writing to os
+	 */
+	private void computeCrc() {
+		CRC32 crcengine = PngHelper.getCRC();
+		crcengine.reset();
+		crcengine.update(idbytes, 0, 4);
+		if (len > 0)
+			crcengine.update(data, 0, len); //
+		crcval = (int) crcengine.getValue();
+	}
+
+	public String toString() {
+		return "chunkid=" + ChunkHelper.toString(idbytes) + " len=" + len;
+	}
+
+	/**
+	 * position before: just after chunk id. positon after: after crc Data should be already allocated. Checks CRC
+	 * Return number of byte read.
+	 */
+	public int readChunkData(InputStream is) {
+		PngHelper.readBytes(is, data, 0, len);
+		int crcori = PngHelper.readInt4(is);
+		computeCrc();
+		if (crcori != crcval)
+			throw new PngjBadCrcException("crc invalid for chunk " + toString() + " calc=" + crcval + " read=" + crcori);
+		return len + 4;
+	}
+
+	public ByteArrayInputStream getAsByteStream() { // only the data
+		return new ByteArrayInputStream(data);
+	}
+
+	private void allocData() {
+		if (data == null || data.length < len)
+			data = new byte[len];
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java
new file mode 100644
index 0000000..2df9fd1
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunk.java
@@ -0,0 +1,152 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+import java.util.HashMap;
+import java.util.Map;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+// see http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
+public abstract class PngChunk {
+
+	public final String id; // 4 letters
+	public final boolean crit, pub, safe;
+	private int lenori = -1; // merely informational, for read chunks
+
+	private boolean writePriority = false; // for queued chunks
+	protected final ImageInfo imgInfo;
+
+	private int chunkGroup = -1; // chunk group where it was read or writen
+
+	/**
+	 * This static map defines which PngChunk class correspond to which ChunkID The client can add other chunks to this
+	 * map statically, before reading
+	 */
+	public final static Map<String, Class<? extends PngChunk>> factoryMap = new HashMap<String, Class<? extends PngChunk>>();
+	static {
+		factoryMap.put(ChunkHelper.IDAT, PngChunkIDAT.class);
+		factoryMap.put(ChunkHelper.IHDR, PngChunkIHDR.class);
+		factoryMap.put(ChunkHelper.PLTE, PngChunkPLTE.class);
+		factoryMap.put(ChunkHelper.IEND, PngChunkIEND.class);
+		factoryMap.put(ChunkHelper.tEXt, PngChunkTEXT.class);
+		factoryMap.put(ChunkHelper.iTXt, PngChunkITXT.class);
+		factoryMap.put(ChunkHelper.zTXt, PngChunkZTXT.class);
+		factoryMap.put(ChunkHelper.bKGD, PngChunkBKGD.class);
+		factoryMap.put(ChunkHelper.gAMA, PngChunkGAMA.class);
+		factoryMap.put(ChunkHelper.pHYs, PngChunkPHYS.class);
+		factoryMap.put(ChunkHelper.iCCP, PngChunkICCP.class);
+		factoryMap.put(ChunkHelper.tIME, PngChunkTIME.class);
+		factoryMap.put(ChunkHelper.tRNS, PngChunkTRNS.class);
+		factoryMap.put(ChunkHelper.cHRM, PngChunkCHRM.class);
+		factoryMap.put(ChunkHelper.sBIT, PngChunkSBIT.class);
+		factoryMap.put(ChunkHelper.sRGB, PngChunkSRGB.class);
+		factoryMap.put(ChunkHelper.hIST, PngChunkHIST.class);
+		factoryMap.put(ChunkHelper.sPLT, PngChunkSPLT.class);
+	}
+
+	protected PngChunk(String id, ImageInfo imgInfo) {
+		this.id = id;
+		this.imgInfo = imgInfo;
+		this.crit = ChunkHelper.isCritical(id);
+		this.pub = ChunkHelper.isPublic(id);
+		this.safe = ChunkHelper.isSafeToCopy(id);
+	}
+
+	public abstract ChunkRaw createChunk();
+
+	public abstract void parseFromChunk(ChunkRaw c);
+
+	// override to make deep copy from read data to write
+	public abstract void cloneDataFromRead(PngChunk other);
+
+	@SuppressWarnings("unchecked")
+	public static <T extends PngChunk> T cloneChunk(T chunk, ImageInfo info) {
+		PngChunk cn = factoryFromId(chunk.id, info);
+		if (cn.getClass() != chunk.getClass())
+			throw new PngjException("bad class cloning chunk: " + cn.getClass() + " " + chunk.getClass());
+		cn.cloneDataFromRead(chunk);
+		return (T) cn;
+	}
+
+	public static PngChunk factory(ChunkRaw chunk, ImageInfo info) {
+		PngChunk c = factoryFromId(ChunkHelper.toString(chunk.idbytes), info);
+		c.lenori = chunk.len;
+		c.parseFromChunk(chunk);
+		return c;
+	}
+
+	public static PngChunk factoryFromId(String cid, ImageInfo info) {
+		PngChunk chunk = null;
+		try {
+			Class<? extends PngChunk> cla = factoryMap.get(cid);
+			if (cla != null) {
+				Constructor<? extends PngChunk> constr = cla.getConstructor(ImageInfo.class);
+				chunk = constr.newInstance(info);
+			}
+		} catch (Exception e) {
+			// this can happend for unkown chunks
+		}
+		if (chunk == null)
+			chunk = new PngChunkUNKNOWN(cid, info);
+		return chunk;
+	}
+
+	protected ChunkRaw createEmptyChunk(int len, boolean alloc) {
+		ChunkRaw c = new ChunkRaw(len, ChunkHelper.toBytes(id), alloc);
+		return c;
+	}
+
+	@Override
+	public String toString() {
+		return "chunk id= " + id + " (" + lenori + ") c=" + getClass().getSimpleName();
+	}
+
+	void setPriority(boolean highPrioriy) {
+		writePriority = highPrioriy;
+	}
+
+	void write(OutputStream os) {
+		ChunkRaw c = createChunk();
+		if (c == null)
+			throw new PngjException("null chunk ! creation failed for " + this);
+		c.writeChunk(os);
+	}
+
+	public boolean isWritePriority() {
+		return writePriority;
+	}
+
+	/** must be overriden - only relevant for ancillary chunks */
+	public boolean allowsMultiple() {
+		return false; // override if allows multiple ocurrences
+	}
+
+	/** mustGoBeforeXX/After must be overriden - only relevant for ancillary chunks */
+	public boolean mustGoBeforeIDAT() {
+		return false;
+	}
+
+	public boolean mustGoBeforePLTE() {
+		return false;
+	}
+
+	public boolean mustGoAfterPLTE() {
+		return false;
+	}
+
+	static boolean isKnown(String id) {
+		return factoryMap.containsKey(id);
+	}
+
+	public int getChunkGroup() {
+		return chunkGroup;
+	}
+
+	public void setChunkGroup(int chunkGroup) {
+		this.chunkGroup = chunkGroup;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java
new file mode 100644
index 0000000..51bbcb8
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkBKGD.java
@@ -0,0 +1,122 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkBKGD extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11bKGD
+	// this chunk structure depends on the image type
+	// only one of these is meaningful
+	private int gray;
+	private int red, green, blue;
+	private int paletteIndex;
+
+	public PngChunkBKGD(ImageInfo info) {
+		super(ChunkHelper.bKGD, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoAfterPLTE() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = null;
+		if (imgInfo.greyscale) {
+			c = createEmptyChunk(2, true);
+			PngHelper.writeInt2tobytes(gray, c.data, 0);
+		} else if (imgInfo.indexed) {
+			c = createEmptyChunk(1, true);
+			c.data[0] = (byte) paletteIndex;
+		} else {
+			c = createEmptyChunk(6, true);
+			PngHelper.writeInt2tobytes(red, c.data, 0);
+			PngHelper.writeInt2tobytes(green, c.data, 0);
+			PngHelper.writeInt2tobytes(blue, c.data, 0);
+		}
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (imgInfo.greyscale) {
+			gray = PngHelper.readInt2fromBytes(c.data, 0);
+		} else if (imgInfo.indexed) {
+			paletteIndex = (int) (c.data[0] & 0xff);
+		} else {
+			red = PngHelper.readInt2fromBytes(c.data, 0);
+			green = PngHelper.readInt2fromBytes(c.data, 2);
+			blue = PngHelper.readInt2fromBytes(c.data, 4);
+		}
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkBKGD otherx = (PngChunkBKGD) other;
+		gray = otherx.gray;
+		red = otherx.red;
+		green = otherx.red;
+		blue = otherx.red;
+		paletteIndex = otherx.paletteIndex;
+	}
+
+	/**
+	 * Set gray value (0-255 if bitdept=8)
+	 * 
+	 * @param gray
+	 */
+	public void setGray(int gray) {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only gray images support this");
+		this.gray = gray;
+	}
+
+	public int getGray() {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only gray images support this");
+		return gray;
+	}
+
+	/**
+	 * Set pallette index
+	 * 
+	 */
+	public void setPaletteIndex(int i) {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed (pallete) images support this");
+		this.paletteIndex = i;
+	}
+
+	public int getPaletteIndex() {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed (pallete) images support this");
+		return paletteIndex;
+	}
+
+	/**
+	 * Set rgb values
+	 * 
+	 */
+	public void setRGB(int r, int g, int b) {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		red = r;
+		green = g;
+		blue = b;
+	}
+
+	public int[] getRGB() {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		return new int[] { red, green, blue };
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkCHRM.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkCHRM.java
new file mode 100644
index 0000000..4380761
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkCHRM.java
@@ -0,0 +1,88 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkCHRM extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11cHRM
+	private double whitex, whitey;
+	private double redx, redy;
+	private double greenx, greeny;
+	private double bluex, bluey;
+
+	public PngChunkCHRM(ImageInfo info) {
+		super(ChunkHelper.cHRM, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoBeforePLTE() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = null;
+		c = createEmptyChunk(32, true);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(whitex), c.data, 0);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(whitey), c.data, 4);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(redx), c.data, 8);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(redy), c.data, 12);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(greenx), c.data, 16);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(greeny), c.data, 20);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(bluex), c.data, 24);
+		PngHelper.writeInt4tobytes(PngHelper.doubleToInt100000(bluey), c.data, 28);
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (c.len != 32)
+			throw new PngjException("bad chunk " + c);
+		whitex = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 0));
+		whitey = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 4));
+		redx = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 8));
+		redy = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 12));
+		greenx = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 16));
+		greeny = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 20));
+		bluex = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 24));
+		bluey = PngHelper.intToDouble100000(PngHelper.readInt4fromBytes(c.data, 28));
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkCHRM otherx = (PngChunkCHRM) other;
+		whitex = otherx.whitex;
+		whitey = otherx.whitex;
+		redx = otherx.redx;
+		redy = otherx.redy;
+		greenx = otherx.greenx;
+		greeny = otherx.greeny;
+		bluex = otherx.bluex;
+		bluey = otherx.bluey;
+	}
+
+	public void setChromaticities(double whitex, double whitey, double redx, double redy, double greenx, double greeny,
+			double bluex, double bluey) {
+		this.whitex = whitex;
+		this.redx = redx;
+		this.greenx = greenx;
+		this.bluex = bluex;
+		this.whitey = whitey;
+		this.redy = redy;
+		this.greeny = greeny;
+		this.bluey = bluey;
+	}
+
+	public double[] getChromaticities() {
+		return new double[] { whitex, whitey, redx, redy, greenx, greeny, bluex, bluey };
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkGAMA.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkGAMA.java
new file mode 100644
index 0000000..184ee9f
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkGAMA.java
@@ -0,0 +1,56 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkGAMA extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11gAMA
+	private double gamma;
+
+	public PngChunkGAMA(ImageInfo info) {
+		super(ChunkHelper.gAMA, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoBeforePLTE() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = createEmptyChunk(4, true);
+		int g = (int) (gamma * 100000 + 0.5);
+		PngHelper.writeInt4tobytes(g, c.data, 0);
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw chunk) {
+		if (chunk.len != 4)
+			throw new PngjException("bad chunk " + chunk);
+		int g = PngHelper.readInt4fromBytes(chunk.data, 0);
+		gamma = ((double) g) / 100000.0;
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		gamma = ((PngChunkGAMA) other).gamma;
+	}
+
+	public double getGamma() {
+		return gamma;
+	}
+
+	public void setGamma(double gamma) {
+		this.gamma = gamma;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkHIST.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkHIST.java
new file mode 100644
index 0000000..b0f02ea
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkHIST.java
@@ -0,0 +1,67 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkHIST extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11hIST
+	// only for palette images
+
+	private int[] hist = new int[0]; // should have same lenght as palette
+
+	public PngChunkHIST(ImageInfo info) {
+		super(ChunkHelper.hIST, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoAfterPLTE() {
+		return true;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed images accept a HIST chunk");
+		int nentries = c.data.length / 2;
+		hist = new int[nentries];
+		for (int i = 0; i < hist.length; i++) {
+			hist[i] = PngHelper.readInt2fromBytes(c.data, i * 2);
+		}
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed images accept a HIST chunk");
+		ChunkRaw c = null;
+		c = createEmptyChunk(hist.length * 2, true);
+		for (int i = 0; i < hist.length; i++) {
+			PngHelper.writeInt2tobytes(hist[i], c.data, i * 2);
+		}
+		return c;
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkHIST otherx = (PngChunkHIST) other;
+		hist = new int[otherx.hist.length];
+		System.arraycopy(otherx.hist, 0, hist, 0, otherx.hist.length);
+	}
+
+	public int[] getHist() {
+		return hist;
+	}
+
+	public void setHist(int[] hist) {
+		this.hist = hist;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkICCP.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkICCP.java
new file mode 100644
index 0000000..db1c1ba
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkICCP.java
@@ -0,0 +1,85 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+
+/*
+ */
+public class PngChunkICCP extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11iCCP
+	private String profileName;
+	private byte[] compressedProfile; // copmression/decopmresion is done in getter/setter
+
+	public PngChunkICCP(ImageInfo info) {
+		super(ChunkHelper.iCCP, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoBeforePLTE() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = createEmptyChunk(profileName.length() + compressedProfile.length + 2, true);
+		System.arraycopy(ChunkHelper.toBytes(profileName), 0, c.data, 0, profileName.length());
+		c.data[profileName.length()] = 0;
+		c.data[profileName.length() + 1] = 0;
+		System.arraycopy(compressedProfile, 0, c.data, profileName.length() + 2, compressedProfile.length);
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw chunk) {
+		int pos0 = ChunkHelper.posNullByte(chunk.data);
+		profileName = new String(chunk.data, 0, pos0, PngHelper.charsetLatin1);
+		int comp = (chunk.data[pos0 + 1] & 0xff);
+		if (comp != 0)
+			throw new RuntimeException("bad compression for ChunkTypeICCP");
+		int compdatasize = chunk.data.length - (pos0 + 2);
+		compressedProfile = new byte[compdatasize];
+		System.arraycopy(chunk.data, pos0 + 2, compressedProfile, 0, compdatasize);
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkICCP otherx = (PngChunkICCP) other;
+		profileName = otherx.profileName;
+		compressedProfile = new byte[otherx.compressedProfile.length];
+		System.arraycopy(otherx.compressedProfile, 0, compressedProfile, 0, otherx.compressedProfile.length); // deep
+																												// copy
+	}
+
+	/**
+	 * The profile should be uncompressed bytes
+	 */
+	public void setProfileNameAndContent(String name, byte[] profile) {
+		profileName = name;
+		compressedProfile = ChunkHelper.compressBytes(profile, true);
+	}
+
+	public void setProfileNameAndContent(String name, String profile) {
+		setProfileNameAndContent(name, profile.getBytes(PngHelper.charsetLatin1));
+	}
+
+	public String getProfileName() {
+		return profileName;
+	}
+
+	/**
+	 * uncompressed
+	 **/
+	public byte[] getProfile() {
+		return ChunkHelper.compressBytes(compressedProfile, false);
+	}
+
+	public String getProfileAsString() {
+		return new String(getProfile(), PngHelper.charsetLatin1);
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIDAT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIDAT.java
new file mode 100644
index 0000000..a7cb95d
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIDAT.java
@@ -0,0 +1,25 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+
+public class PngChunkIDAT extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11IDAT
+	// This is dummy placeholder - we write/read this chunk (actually several)
+	// by special code.
+	public PngChunkIDAT(ImageInfo i) {
+		super(ChunkHelper.IDAT, i);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {// does nothing
+		return null;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) { // does nothing
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIEND.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIEND.java
new file mode 100644
index 0000000..0d5b266
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIEND.java
@@ -0,0 +1,26 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+
+public class PngChunkIEND extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11IEND
+	// this is a dummy placeholder
+	public PngChunkIEND(ImageInfo info) {
+		super(ChunkHelper.IEND, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = new ChunkRaw(0, ChunkHelper.b_IEND, false);
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		// this is not used
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIHDR.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIHDR.java
new file mode 100644
index 0000000..fcb4150
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkIHDR.java
@@ -0,0 +1,126 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.ByteArrayInputStream;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+/**
+ * this is a special chunk!
+ */
+public class PngChunkIHDR extends PngChunk {
+	private int cols;
+	private int rows;
+	private int bitspc;
+	private int colormodel;
+	private int compmeth;
+	private int filmeth;
+	private int interlaced;
+
+	// http://www.w3.org/TR/PNG/#11IHDR
+	//
+	public PngChunkIHDR(ImageInfo info) {
+		super(ChunkHelper.IHDR, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = new ChunkRaw(13, ChunkHelper.b_IHDR, true);
+		int offset = 0;
+		PngHelper.writeInt4tobytes(cols, c.data, offset);
+		offset += 4;
+		PngHelper.writeInt4tobytes(rows, c.data, offset);
+		offset += 4;
+		c.data[offset++] = (byte) bitspc;
+		c.data[offset++] = (byte) colormodel;
+		c.data[offset++] = (byte) compmeth;
+		c.data[offset++] = (byte) filmeth;
+		c.data[offset++] = (byte) interlaced;
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (c.len != 13)
+			throw new PngjException("Bad IDHR len " + c.len);
+		ByteArrayInputStream st = c.getAsByteStream();
+		cols = PngHelper.readInt4(st);
+		rows = PngHelper.readInt4(st);
+		// bit depth: number of bits per channel
+		bitspc = PngHelper.readByte(st);
+		colormodel = PngHelper.readByte(st);
+		compmeth = PngHelper.readByte(st);
+		filmeth = PngHelper.readByte(st);
+		interlaced = PngHelper.readByte(st);
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkIHDR otherx = (PngChunkIHDR) other;
+		cols = otherx.cols;
+		rows = otherx.rows;
+		bitspc = otherx.bitspc;
+		colormodel = otherx.colormodel;
+		compmeth = otherx.compmeth;
+		filmeth = otherx.filmeth;
+		interlaced = otherx.interlaced;
+	}
+
+	public int getCols() {
+		return cols;
+	}
+
+	public void setCols(int cols) {
+		this.cols = cols;
+	}
+
+	public int getRows() {
+		return rows;
+	}
+
+	public void setRows(int rows) {
+		this.rows = rows;
+	}
+
+	public int getBitspc() {
+		return bitspc;
+	}
+
+	public void setBitspc(int bitspc) {
+		this.bitspc = bitspc;
+	}
+
+	public int getColormodel() {
+		return colormodel;
+	}
+
+	public void setColormodel(int colormodel) {
+		this.colormodel = colormodel;
+	}
+
+	public int getCompmeth() {
+		return compmeth;
+	}
+
+	public void setCompmeth(int compmeth) {
+		this.compmeth = compmeth;
+	}
+
+	public int getFilmeth() {
+		return filmeth;
+	}
+
+	public void setFilmeth(int filmeth) {
+		this.filmeth = filmeth;
+	}
+
+	public int getInterlaced() {
+		return interlaced;
+	}
+
+	public void setInterlaced(int interlaced) {
+		this.interlaced = interlaced;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkITXT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkITXT.java
new file mode 100644
index 0000000..4e5c7c7
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkITXT.java
@@ -0,0 +1,119 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+/**
+ * UNTESTED!
+ */
+public class PngChunkITXT extends PngChunkTextVar {
+
+	private boolean compressed = false;
+	private String langTag = "";
+	private String translatedTag = "";
+
+	// http://www.w3.org/TR/PNG/#11iTXt
+	public PngChunkITXT(ImageInfo info) {
+		super(ChunkHelper.iTXt, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		if (val.isEmpty() || key.isEmpty())
+			return null;
+		try {
+			ByteArrayOutputStream ba = new ByteArrayOutputStream();
+			ba.write(key.getBytes(PngHelper.charsetLatin1));
+			ba.write(0); // separator
+			ba.write(compressed ? 1 : 0);
+			ba.write(0); // compression method (always 0)
+			ba.write(langTag.getBytes(PngHelper.charsetUTF8));
+			ba.write(0); // separator
+			ba.write(translatedTag.getBytes(PngHelper.charsetUTF8));
+			ba.write(0); // separator
+			byte[] textbytes = val.getBytes(PngHelper.charsetUTF8);
+			if (compressed) {
+				textbytes = ChunkHelper.compressBytes(textbytes, true);
+			}
+			ba.write(textbytes);
+			byte[] b = ba.toByteArray();
+			ChunkRaw chunk = createEmptyChunk(b.length, false);
+			chunk.data = b;
+			return chunk;
+		} catch (IOException e) {
+			throw new PngjException(e);
+		}
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		int nullsFound = 0;
+		int[] nullsIdx = new int[3];
+		for (int i = 0; i < c.data.length; i++) {
+			if (c.data[i] != 0)
+				continue;
+			nullsIdx[nullsFound] = i;
+			nullsFound++;
+			if (nullsFound == 1)
+				i += 2;
+			if (nullsFound == 3)
+				break;
+		}
+		if (nullsFound != 3)
+			throw new PngjException("Bad formed PngChunkITXT chunk");
+		key = new String(c.data, 0, nullsIdx[0], PngHelper.charsetLatin1);
+		int i = nullsIdx[0] + 1;
+		compressed = c.data[i] == 0 ? false : true;
+		i++;
+		if (compressed && c.data[i] != 0)
+			throw new PngjException("Bad formed PngChunkITXT chunk - bad compression method ");
+		langTag = new String(c.data, i, nullsIdx[1] - i, PngHelper.charsetLatin1);
+		translatedTag = new String(c.data, nullsIdx[1] + 1, nullsIdx[2] - nullsIdx[1] - 1, PngHelper.charsetUTF8);
+		i = nullsIdx[2] + 1;
+		if (compressed) {
+			byte[] bytes = ChunkHelper.compressBytes(c.data, i, c.data.length - i, false);
+			val = new String(bytes, PngHelper.charsetUTF8);
+		} else {
+			val = new String(c.data, i, c.data.length - i, PngHelper.charsetUTF8);
+		}
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkITXT otherx = (PngChunkITXT) other;
+		key = otherx.key;
+		val = otherx.val;
+		compressed = otherx.compressed;
+		langTag = otherx.langTag;
+		translatedTag = otherx.translatedTag;
+	}
+
+	public boolean isCompressed() {
+		return compressed;
+	}
+
+	public void setCompressed(boolean compressed) {
+		this.compressed = compressed;
+	}
+
+	public String getLangtag() {
+		return langTag;
+	}
+
+	public void setLangtag(String langtag) {
+		this.langTag = langtag;
+	}
+
+	public String getTranslatedTag() {
+		return translatedTag;
+	}
+
+	public void setTranslatedTag(String translatedTag) {
+		this.translatedTag = translatedTag;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPHYS.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPHYS.java
new file mode 100644
index 0000000..47e2c49
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPHYS.java
@@ -0,0 +1,108 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+public class PngChunkPHYS extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11pHYs
+	private long pixelsxUnitX;
+	private long pixelsxUnitY;
+	private int units; // 0: unknown 1:metre
+
+	public PngChunkPHYS(ImageInfo info) {
+		super(ChunkHelper.pHYs, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = createEmptyChunk(9, true);
+		PngHelper.writeInt4tobytes((int) pixelsxUnitX, c.data, 0);
+		PngHelper.writeInt4tobytes((int) pixelsxUnitY, c.data, 4);
+		c.data[8] = (byte) units;
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw chunk) {
+		if (chunk.len != 9)
+			throw new PngjException("bad chunk length " + chunk);
+		pixelsxUnitX = PngHelper.readInt4fromBytes(chunk.data, 0);
+		if (pixelsxUnitX < 0)
+			pixelsxUnitX += 0x100000000L;
+		pixelsxUnitY = PngHelper.readInt4fromBytes(chunk.data, 4);
+		if (pixelsxUnitY < 0)
+			pixelsxUnitY += 0x100000000L;
+		units = PngHelper.readInt1fromByte(chunk.data, 8);
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkPHYS otherx = (PngChunkPHYS) other;
+		this.pixelsxUnitX = otherx.pixelsxUnitX;
+		this.pixelsxUnitY = otherx.pixelsxUnitY;
+		this.units = otherx.units;
+	}
+
+	public long getPixelsxUnitX() {
+		return pixelsxUnitX;
+	}
+
+	public void setPixelsxUnitX(long pixelsxUnitX) {
+		this.pixelsxUnitX = pixelsxUnitX;
+	}
+
+	public long getPixelsxUnitY() {
+		return pixelsxUnitY;
+	}
+
+	public void setPixelsxUnitY(long pixelsxUnitY) {
+		this.pixelsxUnitY = pixelsxUnitY;
+	}
+
+	public int getUnits() {
+		return units;
+	}
+
+	public void setUnits(int units) {
+		this.units = units;
+	}
+
+	// special getters / setters
+
+	/**
+	 * returns -1 if the physicial unit is unknown, or X-Y are not equal
+	 */
+	public double getAsDpi() {
+		if (units != 1 || pixelsxUnitX != pixelsxUnitY)
+			return -1;
+		return ((double) pixelsxUnitX) * 0.0254;
+	}
+
+	/**
+	 * returns -1 if the physicial unit is unknown
+	 */
+	public double[] getAsDpi2() {
+		if (units != 1)
+			return new double[] { -1, -1 };
+		return new double[] { ((double) pixelsxUnitX) * 0.0254, ((double) pixelsxUnitY) * 0.0254 };
+	}
+
+	public void setAsDpi(double dpi) {
+		units = 1;
+		pixelsxUnitX = (long) (dpi / 0.0254 + 0.5);
+		pixelsxUnitY = pixelsxUnitX;
+	}
+
+	public void setAsDpi2(double dpix, double dpiy) {
+		units = 1;
+		pixelsxUnitX = (long) (dpix / 0.0254 + 0.5);
+		pixelsxUnitY = (long) (dpiy / 0.0254 + 0.5);
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPLTE.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPLTE.java
new file mode 100644
index 0000000..123080b
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkPLTE.java
@@ -0,0 +1,93 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ * Palette chunk *this is critical*
+ */
+public class PngChunkPLTE extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11PLTE
+	private int nentries = 0;
+	/**
+	 * RGB8 packed in one integer
+	 */
+	private int[] entries;
+
+	public PngChunkPLTE(ImageInfo info) {
+		super(ChunkHelper.PLTE, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		int len = 3 * nentries;
+		int[] rgb = new int[3];
+		ChunkRaw c = createEmptyChunk(len, true);
+		for (int n = 0, i = 0; n < nentries; n++) {
+			getEntryRgb(n, rgb);
+			c.data[i++] = (byte) rgb[0];
+			c.data[i++] = (byte) rgb[1];
+			c.data[i++] = (byte) rgb[2];
+		}
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw chunk) {
+		setNentries(chunk.len / 3);
+		for (int n = 0, i = 0; n < nentries; n++) {
+			setEntry(n, (int) (chunk.data[i++] & 0xff), (int) (chunk.data[i++] & 0xff), (int) (chunk.data[i++] & 0xff));
+		}
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkPLTE otherx = (PngChunkPLTE) other;
+		this.setNentries(otherx.getNentries());
+		System.arraycopy(otherx.entries, 0, entries, 0, nentries);
+	}
+
+	public void setNentries(int n) {
+		nentries = n;
+		if (nentries < 1 || nentries > 256)
+			throw new PngjException("invalid pallette - nentries=" + nentries);
+		if (entries == null || entries.length != nentries) { // alloc
+			entries = new int[nentries];
+		}
+	}
+
+	public int getNentries() {
+		return nentries;
+	}
+
+	public void setEntry(int n, int r, int g, int b) {
+		entries[n] = ((r << 16) | (g << 8) | b);
+	}
+
+	public int getEntry(int n) {
+		return entries[n];
+	}
+
+	public void getEntryRgb(int n, int[] rgb) {
+		getEntryRgb(n, rgb, 0);
+	}
+
+	public void getEntryRgb(int n, int[] rgb, int offset) {
+		int v = entries[n];
+		rgb[offset + 0] = ((v & 0xff0000) >> 16);
+		rgb[offset + 1] = ((v & 0xff00) >> 8);
+		rgb[offset + 2] = (v & 0xff);
+	}
+
+	public int minBitDepth() {
+		if (nentries <= 2)
+			return 1;
+		else if (nentries <= 4)
+			return 2;
+		else if (nentries <= 16)
+			return 4;
+		else
+			return 8;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java
new file mode 100644
index 0000000..6850d26
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSBIT.java
@@ -0,0 +1,124 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkSBIT extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11sBIT
+	// this chunk structure depends on the image type
+
+	// significant bits
+	private int graysb, alphasb;
+	private int redsb, greensb, bluesb;
+
+	public PngChunkSBIT(ImageInfo info) {
+		super(ChunkHelper.sBIT, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoBeforePLTE() {
+		return true;
+	}
+
+	private int getLen() {
+		int len = imgInfo.greyscale ? 1 : 3;
+		if (imgInfo.alpha)
+			len += 1;
+		return len;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (c.len != getLen())
+			throw new PngjException("bad chunk length " + c);
+		if (imgInfo.greyscale) {
+			graysb = PngHelper.readInt1fromByte(c.data, 0);
+			if (imgInfo.alpha)
+				alphasb = PngHelper.readInt1fromByte(c.data, 1);
+		} else {
+			redsb = PngHelper.readInt1fromByte(c.data, 0);
+			greensb = PngHelper.readInt1fromByte(c.data, 1);
+			bluesb = PngHelper.readInt1fromByte(c.data, 2);
+			if (imgInfo.alpha)
+				alphasb = PngHelper.readInt1fromByte(c.data, 3);
+		}
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = null;
+		c = createEmptyChunk(getLen(), true);
+		if (imgInfo.greyscale) {
+			c.data[0] = (byte) graysb;
+			if (imgInfo.alpha)
+				c.data[1] = (byte) alphasb;
+		} else {
+			c.data[0] = (byte) redsb;
+			c.data[1] = (byte) greensb;
+			c.data[2] = (byte) bluesb;
+			if (imgInfo.alpha)
+				c.data[3] = (byte) alphasb;
+		}
+		return c;
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkSBIT otherx = (PngChunkSBIT) other;
+		graysb = otherx.graysb;
+		redsb = otherx.redsb;
+		greensb = otherx.greensb;
+		bluesb = otherx.bluesb;
+		alphasb = otherx.alphasb;
+	}
+
+	public void setGraysb(int gray) {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only greyscale images support this");
+		graysb = gray;
+	}
+
+	public int getGraysb() {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only greyscale images support this");
+		return graysb;
+	}
+
+	public void setAlphasb(int a) {
+		if (!imgInfo.alpha)
+			throw new PngjException("only images with alpha support this");
+		alphasb = a;
+	}
+
+	public int getAlphasb() {
+		if (!imgInfo.alpha)
+			throw new PngjException("only images with alpha support this");
+		return alphasb;
+	}
+
+	/**
+	 * Set rgb values
+	 * 
+	 */
+	public void setRGB(int r, int g, int b) {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		redsb = r;
+		greensb = g;
+		bluesb = b;
+	}
+
+	public int[] getRGB() {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		return new int[] { redsb, greensb, bluesb };
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSPLT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSPLT.java
new file mode 100644
index 0000000..953adb7
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSPLT.java
@@ -0,0 +1,139 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+public class PngChunkSPLT extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11sPLT
+
+	private String palName;
+	private int sampledepth; // 8/16
+	private int[] palette; // 5 elements per entry
+
+	public PngChunkSPLT(ImageInfo info) {
+		super(ChunkHelper.sPLT, info);
+	}
+
+	@Override
+	public boolean allowsMultiple() {
+		return true; // allows multiple, but pallete name should be different
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		try {
+			ByteArrayOutputStream ba = new ByteArrayOutputStream();
+			ba.write(palName.getBytes(PngHelper.charsetLatin1));
+			ba.write(0); // separator
+			ba.write((byte) sampledepth);
+			int nentries = getNentries();
+			for (int n = 0; n < nentries; n++) {
+				for (int i = 0; i < 4; i++) {
+					if (sampledepth == 8)
+						PngHelper.writeByte(ba, (byte) palette[n * 5 + i]);
+					else
+						PngHelper.writeInt2(ba, palette[n * 5 + i]);
+				}
+				PngHelper.writeInt2(ba, palette[n * 5 + 4]);
+			}
+			byte[] b = ba.toByteArray();
+			ChunkRaw chunk = createEmptyChunk(b.length, false);
+			chunk.data = b;
+			return chunk;
+		} catch (IOException e) {
+			throw new PngjException(e);
+		}
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		int t = -1;
+		for (int i = 0; i < c.data.length; i++) { // look for first zero
+			if (c.data[i] == 0) {
+				t = i;
+				break;
+			}
+		}
+		if (t <= 0 || t > c.data.length - 2)
+			throw new PngjException("bad sPLT chunk: no separator found");
+		palName = new String(c.data, 0, t, PngHelper.charsetLatin1);
+		sampledepth = PngHelper.readInt1fromByte(c.data, t + 1);
+		t += 2;
+		int nentries = (c.data.length - t) / (sampledepth == 8 ? 6 : 10);
+		palette = new int[nentries * 5];
+		int r, g, b, a, f, ne;
+		ne = 0;
+		for (int i = 0; i < nentries; i++) {
+			if (sampledepth == 8) {
+				r = PngHelper.readInt1fromByte(c.data, t++);
+				g = PngHelper.readInt1fromByte(c.data, t++);
+				b = PngHelper.readInt1fromByte(c.data, t++);
+				a = PngHelper.readInt1fromByte(c.data, t++);
+			} else {
+				r = PngHelper.readInt2fromBytes(c.data, t);
+				t += 2;
+				g = PngHelper.readInt2fromBytes(c.data, t);
+				t += 2;
+				b = PngHelper.readInt2fromBytes(c.data, t);
+				t += 2;
+				a = PngHelper.readInt2fromBytes(c.data, t);
+				t += 2;
+			}
+			f = PngHelper.readInt2fromBytes(c.data, t);
+			t += 2;
+			palette[ne++] = r;
+			palette[ne++] = g;
+			palette[ne++] = b;
+			palette[ne++] = a;
+			palette[ne++] = f;
+		}
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkSPLT otherx = (PngChunkSPLT) other;
+		palName = otherx.palName;
+		sampledepth = otherx.sampledepth;
+		palette = new int[otherx.palette.length];
+		System.arraycopy(otherx.palette, 0, palette, 0, palette.length);
+	}
+
+	public int getNentries() {
+		return palette.length / 5;
+	}
+
+	public String getPalName() {
+		return palName;
+	}
+
+	public void setPalName(String palName) {
+		this.palName = palName;
+	}
+
+	public int getSampledepth() {
+		return sampledepth;
+	}
+
+	public void setSampledepth(int sampledepth) {
+		this.sampledepth = sampledepth;
+	}
+
+	public int[] getPalette() {
+		return palette;
+	}
+
+	public void setPalette(int[] palette) {
+		this.palette = palette;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSRGB.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSRGB.java
new file mode 100644
index 0000000..7745587
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkSRGB.java
@@ -0,0 +1,61 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkSRGB extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11sRGB
+
+	public static final int RENDER_INTENT_Perceptual = 0;
+	public static final int RENDER_INTENT_Relative_colorimetric = 1;
+	public static final int RENDER_INTENT_Saturation = 2;
+	public static final int RENDER_INTENT_Absolute_colorimetric = 3;
+
+	private int intent;
+
+	public PngChunkSRGB(ImageInfo info) {
+		super(ChunkHelper.sRGB, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoBeforePLTE() {
+		return true;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (c.len != 1)
+			throw new PngjException("bad chunk length " + c);
+		intent = PngHelper.readInt1fromByte(c.data, 0);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = null;
+		c = createEmptyChunk(1, true);
+		c.data[0] = (byte) intent;
+		return c;
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkSRGB otherx = (PngChunkSRGB) other;
+		intent = otherx.intent;
+	}
+
+	public int getIntent() {
+		return intent;
+	}
+
+	public void setIntent(int intent) {
+		this.intent = intent;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTEXT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTEXT.java
new file mode 100644
index 0000000..c535fe3
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTEXT.java
@@ -0,0 +1,34 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+
+public class PngChunkTEXT extends PngChunkTextVar {
+	public PngChunkTEXT(ImageInfo info) {
+		super(ChunkHelper.tEXt, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		if (val.isEmpty() || key.isEmpty())
+			return null;
+		byte[] b = (key + "\0" + val).getBytes(PngHelper.charsetLatin1);
+		ChunkRaw chunk = createEmptyChunk(b.length, false);
+		chunk.data = b;
+		return chunk;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		String[] k = (new String(c.data, PngHelper.charsetLatin1)).split("\0");
+		key = k[0];
+		val = k[1];
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkTEXT otherx = (PngChunkTEXT) other;
+		key = otherx.key;
+		val = otherx.val;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTIME.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTIME.java
new file mode 100644
index 0000000..37e617a
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTIME.java
@@ -0,0 +1,83 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.util.Calendar;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+public class PngChunkTIME extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11tIME
+	private int year, mon, day, hour, min, sec;
+
+	public PngChunkTIME(ImageInfo info) {
+		super(ChunkHelper.tIME, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = createEmptyChunk(7, true);
+		PngHelper.writeInt2tobytes(year, c.data, 0);
+		c.data[2] = (byte) mon;
+		c.data[3] = (byte) day;
+		c.data[4] = (byte) hour;
+		c.data[5] = (byte) min;
+		c.data[6] = (byte) sec;
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw chunk) {
+		if (chunk.len != 7)
+			throw new PngjException("bad chunk " + chunk);
+		year = PngHelper.readInt2fromBytes(chunk.data, 0);
+		mon = PngHelper.readInt1fromByte(chunk.data, 2);
+		day = PngHelper.readInt1fromByte(chunk.data, 3);
+		hour = PngHelper.readInt1fromByte(chunk.data, 4);
+		min = PngHelper.readInt1fromByte(chunk.data, 5);
+		sec = PngHelper.readInt1fromByte(chunk.data, 6);
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkTIME x = (PngChunkTIME) other;
+		year = x.year;
+		mon = x.mon;
+		day = x.day;
+		hour = x.hour;
+		min = x.min;
+		sec = x.sec;
+	}
+
+	public void setNow(int secsAgo) {
+		Calendar d = Calendar.getInstance();
+		d.setTimeInMillis(System.currentTimeMillis() - 1000 * (long) secsAgo);
+		year = d.get(Calendar.YEAR);
+		mon = d.get(Calendar.MONTH) + 1;
+		day = d.get(Calendar.DAY_OF_MONTH);
+		hour = d.get(Calendar.HOUR_OF_DAY);
+		min = d.get(Calendar.MINUTE);
+		sec = d.get(Calendar.SECOND);
+	}
+
+	public void setYMDHMS(int yearx, int monx, int dayx, int hourx, int minx, int secx) {
+		year = yearx;
+		mon = monx;
+		day = dayx;
+		hour = hourx;
+		min = minx;
+		sec = secx;
+	}
+	public int[] getYMDHMS() {
+		return new int[] { year, mon, day, hour, min, sec };
+	}
+
+	/** format YYYY/MM/DD HH:mm:SS */
+	public String getAsString() {
+		return String.format("%04/%02d/%02d %02d:%02d:%02d", year, mon, day, hour, min, sec);
+	}
+
+	
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java
new file mode 100644
index 0000000..9365e5e
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTRNS.java
@@ -0,0 +1,129 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/*
+ */
+public class PngChunkTRNS extends PngChunk {
+	// http://www.w3.org/TR/PNG/#11tRNS
+	// this chunk structure depends on the image type
+	// only one of these is meaningful
+	private int gray;
+	private int red, green, blue;
+	private int[] paletteAlpha = new int[] {};
+
+	public PngChunkTRNS(ImageInfo info) {
+		super(ChunkHelper.tRNS, info);
+	}
+
+	@Override
+	public boolean mustGoBeforeIDAT() {
+		return true;
+	}
+
+	@Override
+	public boolean mustGoAfterPLTE() {
+		return true;
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw c = null;
+		if (imgInfo.greyscale) {
+			c = createEmptyChunk(2, true);
+			PngHelper.writeInt2tobytes(gray, c.data, 0);
+		} else if (imgInfo.indexed) {
+			c = createEmptyChunk(paletteAlpha.length, true);
+			for (int n = 0; n < c.len; n++) {
+				c.data[n] = (byte) paletteAlpha[n];
+			}
+		} else {
+			c = createEmptyChunk(6, true);
+			PngHelper.writeInt2tobytes(red, c.data, 0);
+			PngHelper.writeInt2tobytes(green, c.data, 0);
+			PngHelper.writeInt2tobytes(blue, c.data, 0);
+		}
+		return c;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		if (imgInfo.greyscale) {
+			gray = PngHelper.readInt2fromBytes(c.data, 0);
+		} else if (imgInfo.indexed) {
+			int nentries = c.data.length;
+			paletteAlpha = new int[nentries];
+			for (int n = 0; n < nentries; n++) {
+				paletteAlpha[n] = (int) (c.data[n] & 0xff);
+			}
+		} else {
+			red = PngHelper.readInt2fromBytes(c.data, 0);
+			green = PngHelper.readInt2fromBytes(c.data, 2);
+			blue = PngHelper.readInt2fromBytes(c.data, 4);
+		}
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkTRNS otherx = (PngChunkTRNS) other;
+		gray = otherx.gray;
+		red = otherx.red;
+		green = otherx.red;
+		blue = otherx.red;
+		if (otherx.paletteAlpha != null) {
+			paletteAlpha = new int[otherx.paletteAlpha.length];
+			System.arraycopy(otherx.paletteAlpha, 0, paletteAlpha, 0, paletteAlpha.length);
+		}
+	}
+
+	/**
+	 * Set rgb values
+	 * 
+	 */
+	public void setRGB(int r, int g, int b) {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		red = r;
+		green = g;
+		blue = b;
+	}
+
+	public int[] getRGB() {
+		if (imgInfo.greyscale || imgInfo.indexed)
+			throw new PngjException("only rgb or rgba images support this");
+		return new int[] { red, green, blue };
+	}
+
+	public void setGray(int g) {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only grayscale images support this");
+		gray = g;
+	}
+
+	public int getGray() {
+		if (!imgInfo.greyscale)
+			throw new PngjException("only grayscale images support this");
+		return gray;
+	}
+
+	/**
+	 * WARNING: non deep copy
+	 */
+	public void setPalletteAlpha(int[] palAlpha) {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed images support this");
+		paletteAlpha = palAlpha;
+	}
+
+	/**
+	 * WARNING: non deep copy
+	 */
+	public int[] getPalletteAlpha() {
+		if (!imgInfo.indexed)
+			throw new PngjException("only indexed images support this");
+		return paletteAlpha;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTextVar.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTextVar.java
new file mode 100644
index 0000000..3d92a80
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkTextVar.java
@@ -0,0 +1,61 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+
+/**
+ * superclass for three textual chunks (TEXT, ITXT, ZTXT)
+ * 
+ * @author Hernan J Gonzalez
+ */
+public abstract class PngChunkTextVar extends PngChunk {
+	protected String key; // key/val: only for tEXt. lazy computed
+	protected String val;
+
+	// http://www.w3.org/TR/PNG/#11keywords
+	public final static String KEY_Title = "Title"; // Short (one line) title or caption for image
+	public final static String KEY_Author = "Author"; // Name of image's creator
+	public final static String KEY_Description = "Description"; // Description of image (possibly long)
+	public final static String KEY_Copyright = "Copyright"; // Copyright notice
+	public final static String KEY_Creation_Time = "Creation Time"; // Time of original image creation
+	public final static String KEY_Software = "Software"; // Software used to create the image
+	public final static String KEY_Disclaimer = "Disclaimer"; // Legal disclaimer
+	public final static String KEY_Warning = "Warning"; // Warning of nature of content
+	public final static String KEY_Source = "Source"; // Device used to create the image
+	public final static String KEY_Comment = "Comment"; // Miscellaneous comment
+
+	protected PngChunkTextVar(String id, ImageInfo info) {
+		super(id, info);
+	}
+
+	@Override
+	public boolean allowsMultiple() {
+		return true;
+	}
+
+	public static class PngTxtInfo {
+		public String title;
+		public String author;
+		public String description;
+		public String creation_time;// = (new Date()).toString();
+		public String software;
+		public String disclaimer;
+		public String warning;
+		public String source;
+		public String comment;
+
+	}
+
+	public String getKey() {
+		return key;
+	}
+
+	public String getVal() {
+		return val;
+	}
+
+	public void setKeyVal(String key, String val) {
+		this.key = key;
+		this.val = val;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkUNKNOWN.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkUNKNOWN.java
new file mode 100644
index 0000000..15a3593
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkUNKNOWN.java
@@ -0,0 +1,51 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+
+public class PngChunkUNKNOWN extends PngChunk { // unkown, custom or not
+
+	private byte[] data;
+
+	public PngChunkUNKNOWN(String id, ImageInfo info) {
+		super(id, info);
+	}
+
+	@Override
+	public boolean allowsMultiple() {
+		return true;
+	}
+
+	private PngChunkUNKNOWN(PngChunkUNKNOWN c, ImageInfo info) {
+		super(c.id, info);
+		System.arraycopy(c.data, 0, data, 0, c.data.length);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		ChunkRaw p = createEmptyChunk(data.length, false);
+		p.data = this.data;
+		return p;
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		data = c.data;
+	}
+
+	/* does not copy! */
+	public byte[] getData() {
+		return data;
+	}
+
+	/* does not copy! */
+	public void setData(byte[] data) {
+		this.data = data;
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		// THIS SHOULD NOT BE CALLED IF ALREADY CLONED WITH COPY CONSTRUCTOR
+		PngChunkUNKNOWN c = (PngChunkUNKNOWN) other;
+		data = c.data; // not deep copy
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkZTXT.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkZTXT.java
new file mode 100644
index 0000000..fd6c082
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngChunkZTXT.java
@@ -0,0 +1,62 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+import jogamp.opengl.util.pngj.ImageInfo;
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+
+public class PngChunkZTXT extends PngChunkTextVar {
+	// http://www.w3.org/TR/PNG/#11zTXt
+	public PngChunkZTXT(ImageInfo info) {
+		super(ChunkHelper.zTXt, info);
+	}
+
+	@Override
+	public ChunkRaw createChunk() {
+		if (val.isEmpty() || key.isEmpty())
+			return null;
+		try {
+			ByteArrayOutputStream ba = new ByteArrayOutputStream();
+			ba.write(key.getBytes(PngHelper.charsetLatin1));
+			ba.write(0); // separator
+			ba.write(0); // compression method: 0
+			byte[] textbytes = ChunkHelper.compressBytes(val.getBytes(PngHelper.charsetLatin1), true);
+			ba.write(textbytes);
+			byte[] b = ba.toByteArray();
+			ChunkRaw chunk = createEmptyChunk(b.length, false);
+			chunk.data = b;
+			return chunk;
+		} catch (IOException e) {
+			throw new PngjException(e);
+		}
+	}
+
+	@Override
+	public void parseFromChunk(ChunkRaw c) {
+		int nullsep = -1;
+		for (int i = 0; i < c.data.length; i++) { // look for first zero
+			if (c.data[i] != 0)
+				continue;
+			nullsep = i;
+			break;
+		}
+		if (nullsep < 0 || nullsep > c.data.length - 2)
+			throw new PngjException("bad zTXt chunk: no separator found");
+		key = new String(c.data, 0, nullsep, PngHelper.charsetLatin1);
+		int compmet = (int) c.data[nullsep + 1];
+		if (compmet != 0)
+			throw new PngjException("bad zTXt chunk: unknown compression method");
+		byte[] uncomp = ChunkHelper.compressBytes(c.data, nullsep + 2, c.data.length - nullsep - 2, false); // uncompress
+		val = new String(uncomp, PngHelper.charsetLatin1);
+	}
+
+	@Override
+	public void cloneDataFromRead(PngChunk other) {
+		PngChunkZTXT otherx = (PngChunkZTXT) other;
+		key = otherx.key;
+		val = otherx.val;
+	}
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java
new file mode 100644
index 0000000..a827545
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/PngMetadata.java
@@ -0,0 +1,135 @@
+package jogamp.opengl.util.pngj.chunks;
+
+import jogamp.opengl.util.pngj.PngHelper;
+import jogamp.opengl.util.pngj.PngjException;
+
+/**
+ * We consider "image metadata" every info inside the image except for the most basic image info (IHDR chunk - ImageInfo
+ * class) and the pixels values.
+ * 
+ * This includes the palette (if present) and all the ancillary chunks
+ * 
+ * This class provides a wrapper over the collection of chunks of a image (read or to write) and provides some high
+ * level methods to access them
+ * 
+ */
+public class PngMetadata {
+	private final ChunkList chunkList;
+	private final boolean readonly;
+
+	public PngMetadata(ChunkList chunks, boolean readonly) {
+		this.chunkList = chunks;
+		this.readonly = readonly;
+	}
+
+	/**
+	 * Queues the chunk at the writer
+	 */
+	public boolean setChunk(PngChunk c, boolean overwriteIfPresent) {
+		if (readonly)
+			throw new PngjException("cannot set chunk : readonly metadata");
+		return chunkList.setChunk(c, overwriteIfPresent);
+	}
+
+	
+	/**
+	 * Returns only one chunk or null if nothing found - does not include queued chunks
+	 *
+	 * If more than one chunk (after filtering by inner id) is found, then an exception is thrown (failifMultiple=true)
+	 * or the last one is returned (failifMultiple=false)
+	 * 
+	 * @param id Chunk id
+	 * @param innerid if not null, the chunk is assumed to be PngChunkTextVar or PngChunkSPLT, and filtered by that 'internal id'
+	 * @param failIfMultiple throw exception if more that one
+	 * @return chunk (not cloned)
+	 */
+	public PngChunk getChunk1(String id, String innerid, boolean failIfMultiple) {
+		return chunkList.getChunk1(id, innerid, failIfMultiple);
+	}
+
+	/**
+	 *  Same as  getChunk1(id,  innerid=null, failIfMultiple=true);
+	 */
+	public PngChunk getChunk1(String id) {
+		return chunkList.getChunk1(id);
+	}
+
+	// ///// high level utility methods follow ////////////
+
+	// //////////// DPI
+
+	/** 
+	 * returns -1 if not found or dimension unknown 
+	 **/
+	public double[] getDpi() {
+		PngChunk c = getChunk1(ChunkHelper.pHYs, null, true);
+		if (c == null)
+			return new double[] { -1, -1 };
+		else
+			return ((PngChunkPHYS) c).getAsDpi2();
+	}
+
+	public void setDpi(double x) {
+		setDpi(x, x);
+	}
+
+	public void setDpi(double x, double y) {
+		PngChunkPHYS c = new PngChunkPHYS(chunkList.imageInfo);
+		c.setAsDpi2(x, y);
+		setChunk(c, true);
+	}
+
+	// //////////// TIME
+
+	public void setTimeNow(int secsAgo) {
+		PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo);
+		c.setNow(secsAgo);
+		setChunk(c, true);
+	}
+
+	public void setTimeYMDHMS(int yearx, int monx, int dayx, int hourx, int minx, int secx) {
+		PngChunkTIME c = new PngChunkTIME(chunkList.imageInfo);
+		c.setYMDHMS(yearx, monx, dayx, hourx, minx, secx);
+		setChunk(c, true);
+	}
+
+	public String getTimeAsString() {
+		PngChunk c = getChunk1(ChunkHelper.tIME, null, true);
+		return c != null ? ((PngChunkTIME) c).getAsString() : "";
+	}
+
+	// //////////// TEXT
+
+	public void setText(String k, String val, boolean useLatin1, boolean compress) {
+		if (compress && !useLatin1)
+			throw new PngjException("cannot compress non latin text");
+		PngChunkTextVar c;
+		if (useLatin1) {
+			if (compress) {
+				c = new PngChunkZTXT(chunkList.imageInfo);
+			} else {
+				c = new PngChunkTEXT(chunkList.imageInfo);
+			}
+		} else {
+			c = new PngChunkITXT(chunkList.imageInfo);
+			((PngChunkITXT) c).setLangtag(k); // we use the same orig tag (this is not quite right)
+		}
+		c.setKeyVal(k, val);
+		setChunk(c, true);
+	}
+
+	public void setText(String k, String val) {
+		setText(k, val, false, val.length() > 400);
+	}
+
+	/** tries all text chunks - returns null if not found */
+	public String getTxtForKey(String k) {
+		PngChunk c = getChunk1(ChunkHelper.tEXt, k, true);
+		if (c == null)
+			c = getChunk1(ChunkHelper.zTXt, k, true);
+		if (c == null)
+			c = getChunk1(ChunkHelper.iTXt, k, true);
+		return c != null ? ((PngChunkTextVar) c).getVal() : null;
+	}
+
+}
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/chunks/package.html b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/package.html
new file mode 100644
index 0000000..1374066
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/chunks/package.html
@@ -0,0 +1,9 @@
+<html>
+<body bgcolor="white">
+<p>
+Contains the code related to chunk management for the PNGJ library.</p>
+<p>
+Only needed by client code if some special chunk handling is required.
+</p>
+</body>
+</html>
diff --git a/src/jogl/classes/jogamp/opengl/util/pngj/package.html b/src/jogl/classes/jogamp/opengl/util/pngj/package.html
new file mode 100644
index 0000000..209b39c
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/util/pngj/package.html
@@ -0,0 +1,11 @@
+<html>
+<body bgcolor="white">
+<p>
+Contains the main classes for the PNGJ library.<p>
+Client code should rarely need more than the public members of this package.
+</p>
+<p>
+See also the <code>nosandbox</code> package if available.
+</p>
+</body>
+</html>
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java
index adfdddd..5ff63d9 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLGLCapabilities.java
@@ -28,47 +28,19 @@
 
 package jogamp.opengl.windows.wgl;
 
-import java.util.Comparator;
-
 import jogamp.nativewindow.windows.GDI;
 import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR;
+
+import javax.media.nativewindow.NativeWindowException;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
 public class WGLGLCapabilities extends GLCapabilities {
-  final PIXELFORMATDESCRIPTOR pfd;
-  final int pfdID;
-  int arb_pixelformat; // -1 PFD, 0 NOP, 1 ARB
-
-  /** Comparing pfd id only */
-  public static class PfdIDComparator implements Comparator {
-
-      public int compare(Object o1, Object o2) {
-        if ( ! ( o1 instanceof WGLGLCapabilities ) ) {
-            Class c = (null != o1) ? o1.getClass() : null ;
-            throw new ClassCastException("arg1 not a WGLGLCapabilities object: " + c);
-        }
-        if ( ! ( o2 instanceof WGLGLCapabilities ) ) {
-            Class c = (null != o2) ? o2.getClass() : null ;
-            throw new ClassCastException("arg2 not a WGLGLCapabilities object: " + c);
-        }
-
-        final WGLGLCapabilities caps1 = (WGLGLCapabilities) o1;
-        final long id1 = caps1.getPFDID();
-
-        final WGLGLCapabilities caps2 = (WGLGLCapabilities) o2;
-        final long id2 = caps2.getPFDID();
-
-        if(id1 > id2) {
-            return 1;
-        } else if(id1 < id2) {
-            return -1;
-        }
-        return 0;
-      }
-  }
+  final private PIXELFORMATDESCRIPTOR pfd;
+  final private int pfdID;
+  private int arb_pixelformat; // -1 PFD, 0 NOP, 1 ARB
 
   public WGLGLCapabilities(PIXELFORMATDESCRIPTOR pfd, int pfdID, GLProfile glp) {
       super(glp);
@@ -224,11 +196,23 @@ public class WGLGLCapabilities extends GLCapabilities {
   final public boolean isSetByGDI() { return 0 > arb_pixelformat; }
   final public boolean isSet()      { return 0 != arb_pixelformat; }
   
-  public StringBuffer toString(StringBuffer sink) {
+  @Override
+  final public int getVisualID(VIDType type) throws NativeWindowException {
+      switch(type) {
+          case INTRINSIC:
+          case NATIVE:
+          case WIN32_PFD:
+              return getPFDID();
+          default:
+              throw new NativeWindowException("Invalid type <"+type+">");
+      }      
+  }
+  
+  public StringBuilder toString(StringBuilder sink) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
-    sink.append(pfdID).append(" ");
+    sink.append("wgl vid 0x").append(Integer.toHexString(pfdID)).append(" ");
     switch (arb_pixelformat) {
         case -1: 
             sink.append("gdi");
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java
new file mode 100644
index 0000000..f1598d5
--- /dev/null
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WGLUtil.java
@@ -0,0 +1,95 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ *
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ *
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package jogamp.opengl.windows.wgl;
+
+import jogamp.nativewindow.windows.GDI;
+import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR;
+import jogamp.opengl.Debug;
+
+public class WGLUtil {
+    /**
+     * Switch to use the <code>wgl</code> variants of {@link jogamp.opengl.windows.wgl.WGL} 
+     * to replace the following 5 GDI based functions (see below).
+     * <p>
+     * Disabled per default.
+     * </p> 
+     * <p>
+     * You can enable it by defining the property <code>jogl.windows.useWGLVersionOf5WGLGDIFuncSet</code>.
+     * </p>
+     * 
+     * @see jogamp.nativewindow.windows.GDI#ChoosePixelFormat(long, PIXELFORMATDESCRIPTOR)
+     * @see jogamp.nativewindow.windows.GDI#DescribePixelFormat(long, int, int, PIXELFORMATDESCRIPTOR)
+     * @see jogamp.nativewindow.windows.GDI#GetPixelFormat(long)
+     * @see jogamp.nativewindow.windows.GDI#SetPixelFormat(long, int, PIXELFORMATDESCRIPTOR)
+     * @see jogamp.nativewindow.windows.GDI#SwapBuffers(long)
+     */
+    public static final boolean USE_WGLVersion_Of_5WGLGDIFuncSet;
+    
+    static {
+        USE_WGLVersion_Of_5WGLGDIFuncSet = Debug.isPropertyDefined("jogl.windows.useWGLVersionOf5WGLGDIFuncSet", true);
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            System.err.println("Use WGL version of 5 WGL/GDI functions.");
+        }
+    }
+
+    public static int ChoosePixelFormat(long hdc, PIXELFORMATDESCRIPTOR pfd)  {
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            return WGL.wglChoosePixelFormat(hdc, pfd);
+        } else {
+            return GDI.ChoosePixelFormat(hdc, pfd);
+        }        
+    }
+    public static int DescribePixelFormat(long hdc, int pfdid, int pfdSize, PIXELFORMATDESCRIPTOR pfd)  {
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            return WGL.wglDescribePixelFormat(hdc, pfdid, pfdSize, pfd);
+        } else {
+            return GDI.DescribePixelFormat(hdc, pfdid, pfdSize, pfd);
+        }                
+    }
+    public static int GetPixelFormat(long hdc)  {
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            return WGL.wglGetPixelFormat(hdc);
+        } else {
+            return GDI.GetPixelFormat(hdc);
+        }                
+    }
+    public static boolean SetPixelFormat(long hdc, int pfdid, PIXELFORMATDESCRIPTOR pfd)  {        
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            return WGL.wglSetPixelFormat(hdc, pfdid, pfd);
+        } else {
+            return GDI.SetPixelFormat(hdc, pfdid, pfd);
+        }                
+    }
+    public static boolean SwapBuffers(long hdc)  {        
+        if(USE_WGLVersion_Of_5WGLGDIFuncSet) {
+            return WGL.wglSwapBuffers(hdc);
+        } else {
+            return GDI.SwapBuffers(hdc);
+        }                
+    }
+}
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java
index 0bd83b9..3ba5508 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsDummyWGLDrawable.java
@@ -68,7 +68,7 @@ public class WindowsDummyWGLDrawable extends WindowsWGLDrawable {
         WindowsWGLGraphicsConfiguration config = (WindowsWGLGraphicsConfiguration)ns.getGraphicsConfiguration();
         config.updateGraphicsConfiguration(factory, ns, null);
         if (DEBUG) {
-          System.err.println("!!! WindowsDummyWGLDrawable: "+config);
+          System.err.println("WindowsDummyWGLDrawable: "+config);
         }
     } catch (Throwable t) {
         destroyImpl();
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java
index f33dd21..7457820 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLContext.java
@@ -50,7 +50,8 @@ import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.WrappedSurface;
+
 import jogamp.nativewindow.windows.GDI;
 import jogamp.opengl.GLContextShareSet;
 
@@ -62,10 +63,10 @@ public class WindowsExternalWGLContext extends WindowsWGLContext {
     super(drawable, null);
     this.contextHandle = ctx;
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! Created external OpenGL context " + toHexString(ctx) + " for " + this);
+      System.err.println(getThreadName() + ": Created external OpenGL context " + toHexString(ctx) + " for " + this);
     }
     GLContextShareSet.contextCreated(this);
-    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY);  // use GL_VERSION
+    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT);  // use GL_VERSION
     getGLStateTracker().setEnabled(false); // external context usage can't track state in Java
   }
 
@@ -85,7 +86,7 @@ public class WindowsExternalWGLContext extends WindowsWGLContext {
     }
     AbstractGraphicsScreen aScreen = DefaultGraphicsScreen.createDefault(NativeWindowFactory.TYPE_WINDOWS);
     WindowsWGLGraphicsConfiguration cfg;
-    final int pfdID = GDI.GetPixelFormat(hdc);
+    final int pfdID = WGLUtil.GetPixelFormat(hdc);
     if (0 == pfdID) {
         // This could have happened if the HDC was released right after the GL ctx made current (SWT),
         // WinXP-32bit will not be able to use this HDC afterwards.
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java
index ede5047..ad2e91b 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsExternalWGLDrawable.java
@@ -49,7 +49,8 @@ import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.WrappedSurface;
+
 import jogamp.nativewindow.windows.GDI;
 
 public class WindowsExternalWGLDrawable extends WindowsWGLDrawable {
@@ -63,7 +64,7 @@ public class WindowsExternalWGLDrawable extends WindowsWGLDrawable {
     if (0==hdc) {
       throw new GLException("Error: attempted to make an external GLDrawable without a drawable current, werr " + GDI.GetLastError());
     }
-    int pfdID = GDI.GetPixelFormat(hdc);
+    int pfdID = WGLUtil.GetPixelFormat(hdc);
     if (pfdID == 0) {
       throw new GLException("Error: attempted to make an external GLContext without a valid pixelformat, werr " + GDI.GetLastError());
     }
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsOnscreenWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsOnscreenWGLDrawable.java
index 4f34c94..6ad330c 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsOnscreenWGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsOnscreenWGLDrawable.java
@@ -42,7 +42,6 @@ package jogamp.opengl.windows.wgl;
 
 import javax.media.nativewindow.*;
 import javax.media.opengl.*;
-import jogamp.opengl.*;
 
 public class WindowsOnscreenWGLDrawable extends WindowsWGLDrawable {
   protected WindowsOnscreenWGLDrawable(GLDrawableFactory factory, NativeSurface component) {
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java
index ff59e15..217d88f 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLContext.java
@@ -185,7 +185,6 @@ public class WindowsWGLContext extends GLContextImpl {
       System.err.println(getThreadName()+" - WindowWGLContext.createContextARBImpl: "+getGLVersion(major, minor, ctp, "@creation") +
                          ", handle "+toHexString(drawable.getHandle()) + ", share "+toHexString(share)+", direct "+direct+
                          ", wglCreateContextAttribsARB: "+toHexString(wglExtProcAddressTable._addressof_wglCreateContextAttribsARB));
-      Thread.dumpStack();
     }
 
     boolean ctBwdCompat = 0 != ( CTX_PROFILE_COMPAT & ctp ) ;
@@ -296,13 +295,14 @@ public class WindowsWGLContext extends GLContextImpl {
         if (!WGL.wglMakeCurrent(drawable.getHandle(), temp_ctx)) {
             throw new GLException("Error making temp context current: 0x" + toHexString(temp_ctx) + ", werr: "+GDI.GetLastError());
         }
-        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY);  // use GL_VERSION
-        boolean isCreateContextAttribsARBAvailable = isFunctionAvailable("wglCreateContextAttribsARB");
+        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT);  // use GL_VERSION
         WGL.wglMakeCurrent(0, 0); // release temp context
 
         if( !createContextARBTried) {
-            if(isCreateContextAttribsARBAvailable &&
-               isExtensionAvailable("WGL_ARB_create_context") ) {
+            // is*Available calls are valid since setGLFunctionAvailability(..) was called
+            final boolean isProcCreateContextAttribsARBAvailable = isFunctionAvailable("wglCreateContextAttribsARB");
+            final boolean isExtARBCreateContextAvailable = isExtensionAvailable("WGL_ARB_create_context");
+            if ( isProcCreateContextAttribsARBAvailable && isExtARBCreateContextAvailable ) {
                 // initial ARB context creation
                 contextHandle = createContextARB(share, true);
                 createContextARBTried=true;
@@ -314,7 +314,8 @@ public class WindowsWGLContext extends GLContextImpl {
                     }
                 }
             } else if (DEBUG) {
-                System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - extension not available - share "+share);
+                System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - extension not available - share "+share+
+                                   ", isProcCreateContextAttribsARBAvailable "+isProcCreateContextAttribsARBAvailable+", isExtGLXARBCreateContextAvailable "+isExtARBCreateContextAvailable);            
             }
         }
     }
@@ -393,7 +394,7 @@ public class WindowsWGLContext extends GLContextImpl {
     final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
     final String key = "WGL-"+adevice.getUniqueID();
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! Initializing WGL extension address table: "+key);
+      System.err.println(getThreadName() + ": Initializing WGL extension address table: "+key);
     }
     wglGetExtensionsStringEXTInitialized=false;
     wglGetExtensionsStringEXTAvailable=false;
@@ -407,26 +408,22 @@ public class WindowsWGLContext extends GLContextImpl {
     if(null != table) {
         wglExtProcAddressTable = (WGLExtProcAddressTable) table;
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! GLContext WGL ProcAddressTable reusing key("+key+") -> "+table.hashCode());
+            System.err.println(getThreadName() + ": GLContext WGL ProcAddressTable reusing key("+key+") -> "+toHexString(table.hashCode()));
         }
     } else {
-        if (wglExtProcAddressTable == null) {
-          // FIXME: cache ProcAddressTables by OpenGL context type bits so we can
-          // share them among contexts classes (GL4, GL4bc, GL3, GL3bc, ..)
-          wglExtProcAddressTable = new WGLExtProcAddressTable(new GLProcAddressResolver());
-        }
+        wglExtProcAddressTable = new WGLExtProcAddressTable(new GLProcAddressResolver());
         resetProcAddressTable(wglExtProcAddressTable);
         synchronized(mappedContextTypeObjectLock) {
             mappedGLXProcAddress.put(key, getWGLExtProcAddressTable());
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext WGL ProcAddressTable mapping key("+key+") -> "+getWGLExtProcAddressTable().hashCode());
+                System.err.println(getThreadName() + ": GLContext WGL ProcAddressTable mapping key("+key+") -> "+toHexString(getWGLExtProcAddressTable().hashCode()));
             }
         }
     }
   }
   
-  protected final StringBuffer getPlatformExtensionsStringImpl() {
-    StringBuffer sb = new StringBuffer();
+  protected final StringBuilder getPlatformExtensionsStringImpl() {
+    StringBuilder sb = new StringBuilder();
     
     if (!wglGetExtensionsStringEXTInitialized) {
       wglGetExtensionsStringEXTAvailable = (WGL.wglGetProcAddress("wglGetExtensionsStringEXT") != 0);
@@ -439,7 +436,7 @@ public class WindowsWGLContext extends GLContextImpl {
   }
   
   @Override
-  protected void setSwapIntervalImpl(int interval) {
+  protected boolean setSwapIntervalImpl(int interval) {
     WGLExt wglExt = getWGLExt();
     if(0==hasSwapIntervalSGI) {
         try {
@@ -448,11 +445,10 @@ public class WindowsWGLContext extends GLContextImpl {
     }
     if (hasSwapIntervalSGI>0) {
         try {
-            if ( wglExt.wglSwapIntervalEXT(interval) ) {
-                currentSwapInterval = interval ;
-            }
+            return wglExt.wglSwapIntervalEXT(interval);
         } catch (Throwable t) { hasSwapIntervalSGI=-1; }
     }
+    return false;
   }
   
   private final int initSwapGroupImpl(WGLExt wglExt) {
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java
index 2e0f6b8..579b119 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawable.java
@@ -40,8 +40,6 @@
 
 package jogamp.opengl.windows.wgl;
 
-import java.security.AccessController;
-
 import javax.media.nativewindow.NativeSurface;
 import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLException;
@@ -53,7 +51,7 @@ import jogamp.opengl.GLDynamicLookupHelper;
 
 
 public abstract class WindowsWGLDrawable extends GLDrawableImpl {
-  private static final boolean PROFILING = Debug.isPropertyDefined("jogl.debug.GLDrawable.profiling", true, AccessController.getContext());
+  private static final boolean PROFILING = Debug.isPropertyDefined("jogl.debug.GLDrawable.profiling", true);
   private static final int PROFILING_TICKS = 200;
   private int  profilingSwapBuffersTicks;
   private long profilingSwapBuffersTime;
@@ -71,28 +69,28 @@ public abstract class WindowsWGLDrawable extends GLDrawableImpl {
     WindowsWGLGraphicsConfiguration config = (WindowsWGLGraphicsConfiguration)ns.getGraphicsConfiguration();
     config.updateGraphicsConfiguration(getFactory(), ns, null);
     if (DEBUG) {
-      System.err.println("!!! WindowsWGLDrawable.setRealized(true): "+config);
+      System.err.println("WindowsWGLDrawable.setRealized(true): "+config);
     }
   }
 
   protected final void swapBuffersImpl() {
     // single-buffer is already filtered out @ GLDrawableImpl#swapBuffers()        
-    long startTime = 0;
+    final long t0;
     if (PROFILING) {
-      startTime = System.currentTimeMillis();
+      t0 = System.currentTimeMillis();
+    } else {
+      t0 = 0;
     }
 
-    if (!GDI.SwapBuffers(getHandle()) && (GDI.GetLastError() != GDI.ERROR_SUCCESS)) {
+    if (!WGLUtil.SwapBuffers(getHandle()) && (GDI.GetLastError() != GDI.ERROR_SUCCESS)) {
       throw new GLException("Error swapping buffers");
     }
 
     if (PROFILING) {
-      long endTime = System.currentTimeMillis();
-      profilingSwapBuffersTime += (endTime - startTime);
-      int ticks = PROFILING_TICKS;
-      if (++profilingSwapBuffersTicks == ticks) {
-        System.err.println("SwapBuffers calls: " + profilingSwapBuffersTime + " ms / " + ticks + "  calls (" +
-                           ((float) profilingSwapBuffersTime / (float) ticks) + " ms/call)");
+      profilingSwapBuffersTime += System.currentTimeMillis() - t0;
+      if (++profilingSwapBuffersTicks == PROFILING_TICKS) {
+        System.err.println("SwapBuffers calls: " + profilingSwapBuffersTime + " ms / " + PROFILING_TICKS + "  calls (" +
+                           ((float) profilingSwapBuffersTime / (float) PROFILING_TICKS) + " ms/call)");
         profilingSwapBuffersTime = 0;
         profilingSwapBuffersTicks = 0;
       }
@@ -102,8 +100,4 @@ public abstract class WindowsWGLDrawable extends GLDrawableImpl {
   public GLDynamicLookupHelper getGLDynamicLookupHelper() {
     return getFactoryImpl().getGLDynamicLookupHelper(0);
   }
-
-  static String getThreadName() {
-    return Thread.currentThread().getName();
-  }
 }
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java
index 43c1624..f4069d4 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDrawableFactory.java
@@ -50,10 +50,9 @@ import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.DefaultGraphicsScreen;
 import javax.media.nativewindow.NativeSurface;
-import javax.media.nativewindow.ProxySurface;
 import javax.media.nativewindow.NativeWindowFactory;
-import javax.media.nativewindow.windows.WindowsGraphicsDevice;
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
+import javax.media.nativewindow.ProxySurface;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLCapabilitiesChooser;
@@ -68,8 +67,9 @@ import com.jogamp.common.nio.PointerBuffer;
 import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.ReflectionUtil;
 import com.jogamp.common.util.VersionNumber;
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.windows.WindowsGraphicsDevice;
 
-import jogamp.nativewindow.WrappedSurface;
 import jogamp.nativewindow.windows.GDI;
 import jogamp.nativewindow.windows.GDIUtil;
 import jogamp.nativewindow.windows.GDISurface;
@@ -95,14 +95,16 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
                 if(DEBUG) {
                     gle.printStackTrace();
                 }
-            }
-            windowsWGLDynamicLookupHelper = tmp;
-            if(null!=windowsWGLDynamicLookupHelper) {
+            }            
+            if(null!=tmp && tmp.isLibComplete()) {
+                windowsWGLDynamicLookupHelper = tmp;
                 WGL.getWGLProcAddressTable().reset(windowsWGLDynamicLookupHelper);
             }               
         }
     }
     
+    defaultDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT);
+    
     if(null!=windowsWGLDynamicLookupHelper) {
         // Register our GraphicsConfigurationFactory implementations
         // The act of constructing them causes them to be registered
@@ -114,7 +116,6 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
             } catch (JogampRuntimeException jre) { /* n/a .. */ }
         }
     
-        defaultDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT);
         sharedMap = new HashMap<String, SharedResourceRunner.Resource>();
     
         // Init shared resources off thread
@@ -164,7 +165,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
             if ( GDI.GetProcessAffinityMask(pid, procMask, sysMask) ) {
                 if(DEBUG) {
                     System.err.println("WindowsWGLDrawableFactory.enterThreadCriticalZone() - 0x" + Long.toHexString(pid) + " - " + Thread.currentThread().getName());
-                    Thread.dumpStack();
+                    // Thread.dumpStack();
                 }
                 processAffinityChanges = pid;
                 GDI.SetProcessAffinityMask(pid, 1);
@@ -292,7 +293,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
             sharedDevice.lock();
             try {
                 AbstractGraphicsScreen absScreen = new DefaultGraphicsScreen(sharedDevice, 0);
-                GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP);
+                GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false);
                 if (null == glp) {
                     throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice);
                 }
@@ -324,14 +325,14 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
                     sharedContext.release();
                 }
                 if (DEBUG) {
-                    System.err.println("!!! SharedDevice:  " + sharedDevice);
-                    System.err.println("!!! SharedScreen:  " + absScreen);
-                    System.err.println("!!! SharedContext: " + sharedContext);
-                    System.err.println("!!! pixelformat:   " + hasARBPixelFormat);
-                    System.err.println("!!! multisample:   " + hasARBMultisample);
-                    System.err.println("!!! pbuffer:       " + hasARBPBuffer);
-                    System.err.println("!!! readDrawable:  " + hasARBReadDrawableAvailable);
-                    System.err.println("!!! vendor:        " + vendor);
+                    System.err.println("SharedDevice:  " + sharedDevice);
+                    System.err.println("SharedScreen:  " + absScreen);
+                    System.err.println("SharedContext: " + sharedContext);
+                    System.err.println("pixelformat:   " + hasARBPixelFormat);
+                    System.err.println("multisample:   " + hasARBMultisample);
+                    System.err.println("pbuffer:       " + hasARBPBuffer);
+                    System.err.println("readDrawable:  " + hasARBReadDrawableAvailable);
+                    System.err.println("vendor:        " + vendor);
                 }
                 return new SharedResource(sharedDevice, absScreen, sharedDrawable, sharedContext, 
                                           hasARBPixelFormat, hasARBMultisample,
@@ -346,11 +347,11 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
         public void releaseSharedResource(SharedResourceRunner.Resource shared) {
             SharedResource sr = (SharedResource) shared;
             if (DEBUG) {
-              System.err.println("!!! Shutdown Shared:");
-              System.err.println("!!!   Device  : " + sr.device);
-              System.err.println("!!!   Screen  : " + sr.screen);
-              System.err.println("!!!   Drawable: " + sr.drawable);
-              System.err.println("!!!   CTX     : " + sr.context);
+              System.err.println("Shutdown Shared:");
+              System.err.println("Device  : " + sr.device);
+              System.err.println("Screen  : " + sr.screen);
+              System.err.println("Drawable: " + sr.drawable);
+              System.err.println("CTX     : " + sr.context);
             }
 
             if (null != sr.context) {
@@ -379,7 +380,7 @@ public class WindowsWGLDrawableFactory extends GLDrawableFactoryImpl {
   }
 
   public final boolean getIsDeviceCompatible(AbstractGraphicsDevice device) {
-      if(device instanceof WindowsGraphicsDevice) {
+      if(null!=windowsWGLDynamicLookupHelper && device instanceof WindowsGraphicsDevice) {
           return true;
       }
       return false;
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java
index ea7dc81..a553bd4 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLDynamicLibraryBundleInfo.java
@@ -36,6 +36,7 @@ public class WindowsWGLDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryB
         super();
     }
 
+    @Override
     public List<List<String>> getToolLibNames() {
         final List<List<String>> libsList = new ArrayList<List<String>>();
         final List<String> libsGL = new ArrayList<String>();
@@ -44,12 +45,14 @@ public class WindowsWGLDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryB
         return libsList;
     }
     
+    @Override
     public final List<String> getToolGetProcAddressFuncNameList() {
         List<String> res = new ArrayList<String>();
         res.add("wglGetProcAddress");
         return res;
     }
 
+    @Override
     public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
         return WGL.wglGetProcAddress(toolGetProcAddressHandle, funcName);
     }
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java
index 2fcded8..5682b35 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfiguration.java
@@ -47,17 +47,15 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLPbuffer;
 import javax.media.opengl.GLProfile;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
+
 import jogamp.nativewindow.windows.DWM_BLURBEHIND;
 import jogamp.nativewindow.windows.GDI;
 import jogamp.nativewindow.windows.MARGINS;
 import jogamp.nativewindow.windows.PIXELFORMATDESCRIPTOR;
 import jogamp.opengl.GLGraphicsConfigurationUtil;
 
-public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable {
-    // Keep this under the same debug flag as the drawable factory for convenience
-    protected static final boolean DEBUG = jogamp.opengl.Debug.debug("GraphicsConfiguration");
-    
+public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguration implements Cloneable {    
     protected static final int MAX_PFORMATS = 256;
     protected static final int MAX_ATTRIBS  = 256;
 
@@ -161,7 +159,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
             throw new GLException("Error: HDC is null");
         }
     
-        if (!GDI.SetPixelFormat(hdc, caps.getPFDID(), caps.getPFD())) {
+        if (!WGLUtil.SetPixelFormat(hdc, caps.getPFDID(), caps.getPFD())) {
             throw new GLException("Unable to set pixel format " + caps +
                                   " for device context " + toHexString(hdc) +
                                   ": error code " + GDI.GetLastError());
@@ -181,11 +179,11 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
                 ok = GDI.DwmExtendFrameIntoClientArea(hwnd, m);
             }
             if(DEBUG) {
-                System.err.println("!!! translucency enabled on wnd: 0x"+Long.toHexString(hwnd)+" - ok: "+ok);
+                System.err.println("translucency enabled on wnd: 0x"+Long.toHexString(hwnd)+" - ok: "+ok);
             }
         }
         if (DEBUG) {
-            System.err.println("!!! setPixelFormat (ARB): hdc "+toHexString(hdc) +", "+caps);
+            System.err.println("setPixelFormat (ARB): hdc "+toHexString(hdc) +", "+caps);
         }
         setCapsPFD(caps);
     }
@@ -456,18 +454,22 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
           iattributes[niattribs++] = GL.GL_FALSE;
         }
         
-        iattributes[niattribs++] = WGLExt.WGL_DEPTH_BITS_ARB;
-        iattributes[niattribs++] = caps.getDepthBits();
         iattributes[niattribs++] = WGLExt.WGL_RED_BITS_ARB;
         iattributes[niattribs++] = caps.getRedBits();
         iattributes[niattribs++] = WGLExt.WGL_GREEN_BITS_ARB;
         iattributes[niattribs++] = caps.getGreenBits();
         iattributes[niattribs++] = WGLExt.WGL_BLUE_BITS_ARB;
         iattributes[niattribs++] = caps.getBlueBits();
-        iattributes[niattribs++] = WGLExt.WGL_ALPHA_BITS_ARB;
-        iattributes[niattribs++] = caps.getAlphaBits();
-        iattributes[niattribs++] = WGLExt.WGL_STENCIL_BITS_ARB;
-        iattributes[niattribs++] = caps.getStencilBits();
+        if(caps.getAlphaBits()>0) {
+            iattributes[niattribs++] = WGLExt.WGL_ALPHA_BITS_ARB;
+            iattributes[niattribs++] = caps.getAlphaBits();
+        }
+        if(caps.getStencilBits()>0) {
+            iattributes[niattribs++] = WGLExt.WGL_STENCIL_BITS_ARB;
+            iattributes[niattribs++] = caps.getStencilBits();
+        }
+        iattributes[niattribs++] = WGLExt.WGL_DEPTH_BITS_ARB;
+        iattributes[niattribs++] = caps.getDepthBits();
         if (caps.getAccumRedBits()   > 0 ||
             caps.getAccumGreenBits() > 0 ||
             caps.getAccumBlueBits()  > 0 ||
@@ -610,7 +612,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
         }
         PIXELFORMATDESCRIPTOR pfd = createPixelFormatDescriptor();
 
-        if (GDI.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) {
+        if (WGLUtil.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) {
             // remove displayable bits, since pfdID is non displayable
             drawableTypeBits = drawableTypeBits & ~(GLGraphicsConfigurationUtil.WINDOW_BIT | GLGraphicsConfigurationUtil.BITMAP_BIT);
             if( 0 == drawableTypeBits ) {
@@ -629,7 +631,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
     //
 
     static int[] wglAllGDIPFIDs(long hdc) {
-        int numFormats = GDI.DescribePixelFormat(hdc, 1, 0, null);
+        int numFormats = WGLUtil.DescribePixelFormat(hdc, 1, 0, null);
         if (numFormats == 0) {
             throw new GLException("DescribePixelFormat: No formats - HDC 0x" + Long.toHexString(hdc) +
                                   ", LastError: " + GDI.GetLastError());
@@ -736,7 +738,7 @@ public class WindowsWGLGraphicsConfiguration extends MutableGraphicsConfiguratio
     pfd.setNSize((short) PIXELFORMATDESCRIPTOR.size());
     pfd.setNVersion((short) 1);
     if(0 != hdc && 1 <= pfdID) {
-        if (GDI.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) {
+        if (WGLUtil.DescribePixelFormat(hdc, pfdID, PIXELFORMATDESCRIPTOR.size(), pfd) == 0) {
             // Accelerated pixel formats that are non displayable
             if(DEBUG) {
                 System.err.println("Info: Non displayable pixel format " + pfdID + " of device context: error code " + GDI.GetLastError());
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java
index edcaa4a..2c8c031 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/WindowsWGLGraphicsConfigurationFactory.java
@@ -42,6 +42,7 @@ import javax.media.nativewindow.GraphicsConfigurationFactory;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.NativeSurface;
 import javax.media.nativewindow.NativeWindowFactory;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLContext;
@@ -64,11 +65,10 @@ import java.util.List;
     GraphicsDevice and GraphicsConfiguration abstractions. */
 
 public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    protected static final boolean DEBUG = jogamp.opengl.Debug.debug("GraphicsConfiguration");
-    static WGLGLCapabilities.PfdIDComparator PfdIDComparator = new WGLGLCapabilities.PfdIDComparator();
+    static VisualIDHolder.VIDComparator PfdIDComparator = new VisualIDHolder.VIDComparator(VisualIDHolder.VIDType.WIN32_PFD);
 
     static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.windows.WindowsGraphicsDevice.class, new WindowsWGLGraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.windows.WindowsGraphicsDevice.class, new WindowsWGLGraphicsConfigurationFactory());
     }
     private WindowsWGLGraphicsConfigurationFactory() {
     }
@@ -200,8 +200,8 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
                     // set PFD if not set yet
                     int pfdID = -1;
                     boolean set = false;
-                    if ( 1 > ( pfdID = GDI.GetPixelFormat(hdc) ) ) {
-                        if (!GDI.SetPixelFormat(hdc, config.getPixelFormatID(), config.getPixelFormat())) {
+                    if ( 1 > ( pfdID = WGLUtil.GetPixelFormat(hdc) ) ) {
+                        if (!WGLUtil.SetPixelFormat(hdc, config.getPixelFormatID(), config.getPixelFormat())) {
                             throw new GLException("Unable to set pixel format " + config.getPixelFormatID() +
                                                   " for device context " + toHexString(hdc) +
                                                   ": error code " + GDI.GetLastError());
@@ -209,8 +209,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
                         set = true;                        
                     }
                     if (DEBUG) {
-                        System.err.println("!!! setPixelFormat (post): hdc "+toHexString(hdc) +", "+pfdID+" -> "+config.getPixelFormatID()+", set: "+set);
-                        Thread.dumpStack();
+                        System.err.println("setPixelFormat (post): hdc "+toHexString(hdc) +", "+pfdID+" -> "+config.getPixelFormatID()+", set: "+set);
                     }
                 }
             }
@@ -231,6 +230,9 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
         if (config == null) {
             throw new IllegalArgumentException("WindowsWGLGraphicsConfiguration is null");
         }
+        if ( !(_factory instanceof WindowsWGLDrawableFactory) ) {
+            throw new GLException("GLDrawableFactory is not a WindowsWGLDrawableFactory, but: "+_factory.getClass().getSimpleName());
+        }
         WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory) _factory;
         WindowsWGLDrawable sharedDrawable = factory.getOrCreateSharedDrawable(device);
         if(null == sharedDrawable) {
@@ -259,7 +261,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
             } else {
                 System.err.println("updateGraphicsConfiguration(using target): hdc "+toHexString(hdc));
             }
-            System.err.println("!!! user chosen caps " + config.getChosenCapabilities());
+            System.err.println("user chosen caps " + config.getChosenCapabilities());
         }
         AbstractGraphicsDevice device = config.getScreen().getDevice();
         WindowsWGLDrawableFactory.SharedResource sharedResource = ((WindowsWGLDrawableFactory)factory).getOrCreateSharedResource(device);
@@ -306,12 +308,12 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
         GLProfile glProfile = capsChosen.getGLProfile();
         
         if(DEBUG) {
-            System.err.println("!!! translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+" -> translucency "+(!isOpaque));
+            System.err.println("translucency requested: "+(!capsChosen.isBackgroundOpaque())+", compositioning enabled: "+GDI.DwmIsCompositionEnabled()+" -> translucency "+(!isOpaque));
         }
 
         WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps
         boolean pixelFormatSet = false; // indicates a preset PFD ID [caps]
-        final int presetPFDID = extHDC ? -1 : GDI.GetPixelFormat(hdc) ;
+        final int presetPFDID = extHDC ? -1 : WGLUtil.GetPixelFormat(hdc) ;
         if ( 1 <= presetPFDID ) {
             // Pixelformat already set by either
             //  - a previous preselectGraphicsConfiguration() call on the same HDC,
@@ -361,6 +363,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
                 }
                 if (null == pformats) {
                     if (DEBUG) {
+                        System.err.println("updateGraphicsConfigurationARB: failed, return false");
                         Thread.dumpStack();
                     }
                     return false;
@@ -403,7 +406,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
             }
             pixelFormatCaps = (WGLGLCapabilities) GLGraphicsConfigurationUtil.fixOpaqueGLCapabilities(pixelFormatCaps, isOpaque);
             if (DEBUG) {
-                System.err.println("!!! chosen pfdID (ARB): native recommended "+ (recommendedIndex+1) +
+                System.err.println("chosen pfdID (ARB): native recommended "+ (recommendedIndex+1) +
                                    " chosen "+pixelFormatCaps);
             }
         }
@@ -433,7 +436,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
         WGLGLCapabilities pixelFormatCaps = null; // chosen or preset PFD ID's caps
         boolean pixelFormatSet = false; // indicates a preset PFD ID [caps]
 
-        if ( !extHDC && 1 <= ( pfdID = GDI.GetPixelFormat(hdc) ) ) {
+        if ( !extHDC && 1 <= ( pfdID = WGLUtil.GetPixelFormat(hdc) ) ) {
             // Pixelformat already set by either
             //  - a previous preselectGraphicsConfiguration() call on the same HDC,
             //  - the graphics driver, copying the HDC's pixelformat to the new one,
@@ -457,7 +460,7 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
             // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice
             PIXELFORMATDESCRIPTOR pfd = WindowsWGLGraphicsConfiguration.createPixelFormatDescriptor();
             pfd = WindowsWGLGraphicsConfiguration.GLCapabilities2PFD(capsChosen, pfd);
-            pfdID = GDI.ChoosePixelFormat(hdc, pfd);
+            pfdID = WGLUtil.ChoosePixelFormat(hdc, pfd);
             int recommendedIndex = -1 ;
             if( 1 <= pfdID ) {
                 // seek index ..
@@ -473,13 +476,14 @@ public class WindowsWGLGraphicsConfigurationFactory extends GLGraphicsConfigurat
             int chosenIndex = chooseCapabilities(chooser, capsChosen, availableCaps, recommendedIndex);
             if ( 0 > chosenIndex ) {
                 if (DEBUG) {
+                    System.err.println("updateGraphicsConfigurationGDI: failed, return false");
                     Thread.dumpStack();
                 }
                 return false;
             }
             pixelFormatCaps = availableCaps.get(chosenIndex);
             if (DEBUG) {
-                System.err.println("!!! chosen pfdID (GDI): native recommended "+ (recommendedIndex+1) +
+                System.err.println("chosen pfdID (GDI): native recommended "+ (recommendedIndex+1) +
                                    ", caps " + pixelFormatCaps);
             }
         }
diff --git a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java
index 0f9786f..bd64b58 100644
--- a/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/windows/wgl/awt/WindowsAWTWGLGraphicsConfigurationFactory.java
@@ -35,6 +35,11 @@ package jogamp.opengl.windows.wgl.awt;
 
 
 import com.jogamp.common.util.ArrayHashSet;
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
+import com.jogamp.nativewindow.windows.WindowsGraphicsDevice;
+
 import jogamp.nativewindow.jawt.windows.Win32SunJDKReflection;
 import jogamp.opengl.GLGraphicsConfigurationFactory;
 import java.awt.GraphicsConfiguration;
@@ -47,23 +52,18 @@ import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.DefaultGraphicsScreen;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
-import javax.media.nativewindow.windows.WindowsGraphicsDevice;
 
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLException;
 
+import jogamp.opengl.windows.wgl.WindowsWGLDrawableFactory;
 import jogamp.opengl.windows.wgl.WindowsWGLGraphicsConfiguration;
 import javax.media.opengl.GLDrawableFactory;
 
 public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    protected static final boolean DEBUG = jogamp.opengl.Debug.debug("GraphicsConfiguration");
-
     public static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.awt.AWTGraphicsDevice.class, new WindowsAWTWGLGraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new WindowsAWTWGLGraphicsConfigurationFactory());
     }
     private WindowsAWTWGLGraphicsConfigurationFactory() {        
     }
@@ -106,8 +106,6 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu
         WindowsGraphicsDevice winDevice = new WindowsGraphicsDevice(AbstractGraphicsDevice.DEFAULT_UNIT);
         DefaultGraphicsScreen winScreen = new DefaultGraphicsScreen(winDevice, awtScreen.getIndex());
         GraphicsConfigurationFactory configFactory = GraphicsConfigurationFactory.getFactory(winDevice);
-        GLDrawableFactory drawableFactory = GLDrawableFactory.getFactory( ((GLCapabilitiesImmutable)capsChosen).getGLProfile() );
-
         WindowsWGLGraphicsConfiguration winConfig = (WindowsWGLGraphicsConfiguration)
                                                        configFactory.chooseGraphicsConfiguration(capsChosen,
                                                                                                  capsRequested,
@@ -116,61 +114,68 @@ public class WindowsAWTWGLGraphicsConfigurationFactory extends GLGraphicsConfigu
             throw new GLException("Unable to choose a GraphicsConfiguration: "+capsChosen+",\n\t"+chooser+"\n\t"+winScreen);
         }
 
+        GLDrawableFactory drawableFactory = GLDrawableFactory.getFactory(((GLCapabilitiesImmutable)capsChosen).getGLProfile());        
         GraphicsConfiguration chosenGC = null;
 
-        // 1st Choice: Create an AWT GraphicsConfiguration with the desired PFD
-        // This gc will probably not be able to support GDI (WGL_SUPPORT_GDI_ARB, PFD_SUPPORT_GDI)
-        // however on most GPUs this is the current situation for Windows,
-        // otherwise no hardware accelerated PFD could be achieved.
-        //   - preselect with no constrains
-        //   - try to create dedicated GC
-        try {
-            winConfig.preselectGraphicsConfiguration(drawableFactory, null);
-            if ( 1 <= winConfig.getPixelFormatID() ) {
-                chosenGC = Win32SunJDKReflection.graphicsConfigurationGet(device, winConfig.getPixelFormatID());
-                if(DEBUG) {
-                    System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: Found new AWT PFD ID "+winConfig.getPixelFormatID()+" -> "+winConfig);
+        if ( drawableFactory instanceof WindowsWGLDrawableFactory ) {
+            // 1st Choice: Create an AWT GraphicsConfiguration with the desired PFD
+            // This gc will probably not be able to support GDI (WGL_SUPPORT_GDI_ARB, PFD_SUPPORT_GDI)
+            // however on most GPUs this is the current situation for Windows,
+            // otherwise no hardware accelerated PFD could be achieved.
+            //   - preselect with no constrains
+            //   - try to create dedicated GC
+            try {
+                winConfig.preselectGraphicsConfiguration(drawableFactory, null);
+                if ( 1 <= winConfig.getPixelFormatID() ) {
+                    chosenGC = Win32SunJDKReflection.graphicsConfigurationGet(device, winConfig.getPixelFormatID());
+                    if(DEBUG) {
+                        System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: Found new AWT PFD ID "+winConfig.getPixelFormatID()+" -> "+winConfig);
+                    }
                 }
-            }
-        } catch (GLException gle0) {
-            gle0.printStackTrace();
-            // go on ..
-        }
-
-        if( null == chosenGC ) {
-            // 2nd Choice: Choose and match the GL Visual with AWT:
-            //   - collect all AWT PFDs
-            //   - choose a GL config from the pool of AWT PFDs
-            //
-            // The resulting GraphicsConfiguration has to be 'forced' on the AWT native peer,
-            // ie. returned by GLCanvas's getGraphicsConfiguration() befor call by super.addNotify().
-            //
-
-            // collect all available PFD IDs
-            GraphicsConfiguration[] configs = device.getConfigurations();
-            int[] pfdIDs = new int[configs.length];
-            ArrayHashSet pfdIDOSet = new ArrayHashSet();
-            for (int i = 0; i < configs.length; i++) {
-                GraphicsConfiguration gc = configs[i];
-                pfdIDs[i] = Win32SunJDKReflection.graphicsConfigurationGetPixelFormatID(gc);
-                pfdIDOSet.add(new Integer(pfdIDs[i]));
+            } catch (GLException gle0) {
                 if(DEBUG) {
-                    System.err.println("AWT pfd["+i+"] "+pfdIDs[i]);
+                    gle0.printStackTrace();
                 }
+                // go on ..
             }
-            if(DEBUG) {
-                System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: PFD IDs: "+pfdIDs.length+", unique: "+pfdIDOSet.size());
-            }
-            winConfig.preselectGraphicsConfiguration(drawableFactory, pfdIDs);
-            int gcIdx = pfdIDOSet.indexOf(new Integer(winConfig.getPixelFormatID()));
-            if( 0 > gcIdx ) {
-                chosenGC = configs[gcIdx];
+    
+            if( null == chosenGC ) {
+                // 2nd Choice: Choose and match the GL Visual with AWT:
+                //   - collect all AWT PFDs
+                //   - choose a GL config from the pool of AWT PFDs
+                //
+                // The resulting GraphicsConfiguration has to be 'forced' on the AWT native peer,
+                // ie. returned by GLCanvas's getGraphicsConfiguration() befor call by super.addNotify().
+                //
+    
+                // collect all available PFD IDs
+                GraphicsConfiguration[] configs = device.getConfigurations();
+                int[] pfdIDs = new int[configs.length];
+                ArrayHashSet<Integer> pfdIDOSet = new ArrayHashSet<Integer>();
+                for (int i = 0; i < configs.length; i++) {
+                    GraphicsConfiguration gc = configs[i];
+                    pfdIDs[i] = Win32SunJDKReflection.graphicsConfigurationGetPixelFormatID(gc);
+                    pfdIDOSet.add(new Integer(pfdIDs[i]));
+                    if(DEBUG) {
+                        System.err.println("AWT pfd["+i+"] "+pfdIDs[i]);
+                    }
+                }
                 if(DEBUG) {
-                    System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: Found matching AWT PFD ID "+winConfig.getPixelFormatID()+" -> "+winConfig);
+                    System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: PFD IDs: "+pfdIDs.length+", unique: "+pfdIDOSet.size());
                 }
-            }
+                winConfig.preselectGraphicsConfiguration(drawableFactory, pfdIDs);
+                int gcIdx = pfdIDOSet.indexOf(new Integer(winConfig.getPixelFormatID()));
+                if( 0 > gcIdx ) {
+                    chosenGC = configs[gcIdx];
+                    if(DEBUG) {
+                        System.err.println("WindowsAWTWGLGraphicsConfigurationFactory: Found matching AWT PFD ID "+winConfig.getPixelFormatID()+" -> "+winConfig);
+                    }
+                }
+            }                
+        } else {
+            chosenGC = device.getDefaultConfiguration();
         }
-
+        
         if ( null == chosenGC ) {
             throw new GLException("Unable to determine GraphicsConfiguration: "+winConfig);
         }
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java b/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java
index 33e85dd..7cc2d0f 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/GLXUtil.java
@@ -33,16 +33,30 @@
 
 package jogamp.opengl.x11.glx;
 
-import javax.media.nativewindow.x11.X11GraphicsDevice;
 import javax.media.opengl.GLException;
 
 import jogamp.opengl.Debug;
 
 import com.jogamp.common.util.VersionNumber;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
 
 public class GLXUtil {
     public static final boolean DEBUG = Debug.debug("GLXUtil");
     
+    public static synchronized boolean isGLXAvailableOnServer(X11GraphicsDevice x11Device) {
+        if(null == x11Device) {
+            throw new IllegalArgumentException("null X11GraphicsDevice");
+        }
+        if(0 == x11Device.getHandle()) {
+            throw new IllegalArgumentException("null X11GraphicsDevice display handle");
+        }        
+        boolean glXAvailable = false;
+        try {
+            glXAvailable = GLX.glXQueryExtension(x11Device.getHandle(), null, 0, null, 0);
+        } catch (Throwable t) { /* n/a */ }
+        return glXAvailable;        
+    }
+    
     public static VersionNumber getGLXServerVersionNumber(long display) {
         int[] major = new int[1];
         int[] minor = new int[1];
@@ -90,22 +104,18 @@ public class GLXUtil {
     }
     public static VersionNumber getClientVersionNumber() {
         return clientVersionNumber;
-    }    
-    public static synchronized boolean initGLXClientDataSingleton(X11GraphicsDevice x11Device) { 
+    }
+    
+    public static synchronized void initGLXClientDataSingleton(X11GraphicsDevice x11Device) { 
         if(null != clientVendorName) {
-            return false;
-        }
-        if(DEBUG) {
-            System.err.println("initGLXClientDataSingleton: "+x11Device);
-            Thread.dumpStack();
+            return; // already initialized
         }
         if(null == x11Device) {
-            throw new GLException("null X11GraphicsDevice");
+            throw new IllegalArgumentException("null X11GraphicsDevice");
         }
         if(0 == x11Device.getHandle()) {
-            throw new GLException("null X11GraphicsDevice display handle");
-        }
-        
+            throw new IllegalArgumentException("null X11GraphicsDevice display handle");
+        }        
         clientMultisampleAvailable = isMultisampleAvailable(GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_EXTENSIONS));
         clientVendorName = GLX.glXGetClientString(x11Device.getHandle(), GLX.GLX_VENDOR);
         
@@ -121,7 +131,6 @@ public class GLXUtil {
               minor[0] = 2;
         }
         clientVersionNumber = new VersionNumber(major[0], minor[0], 0);
-        return true;
     }
     private static boolean clientMultisampleAvailable = false;
     private static String clientVendorName = null;
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java
index 6be74c0..a1039e5 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11DummyGLXDrawable.java
@@ -30,7 +30,10 @@ package jogamp.opengl.x11.glx;
 
 import javax.media.opengl.*;
 
-import javax.media.nativewindow.x11.*;
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
+
 import jogamp.nativewindow.*;
 import jogamp.nativewindow.x11.*;
 
@@ -55,7 +58,7 @@ public class X11DummyGLXDrawable extends X11OnscreenGLXDrawable {
     X11GraphicsDevice device = (X11GraphicsDevice) screen.getDevice();
     long dpy = device.getHandle();
     int scrn = screen.getIndex();
-    long visualID = config.getVisualID();
+    int visualID = config.getXVisualID();
 
     dummyWindow = X11Lib.CreateDummyWindow(dpy, scrn, visualID, f_dim, f_dim);
     ns.setSurfaceHandle( dummyWindow );
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
index 4a949ea..700b256 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXContext.java
@@ -40,11 +40,18 @@
 
 package jogamp.opengl.x11.glx;
 
-import javax.media.nativewindow.*;
-import javax.media.nativewindow.x11.*;
-import javax.media.opengl.*;
-import jogamp.opengl.*;
-import jogamp.nativewindow.WrappedSurface;
+import javax.media.nativewindow.NativeSurface;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLContext;
+import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+import jogamp.opengl.GLContextImpl;
+import jogamp.opengl.GLContextShareSet;
+
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 public class X11ExternalGLXContext extends X11GLXContext {
   private GLContext lastContext;
@@ -53,7 +60,7 @@ public class X11ExternalGLXContext extends X11GLXContext {
     super(drawable, null);
     this.contextHandle = ctx;
     GLContextShareSet.contextCreated(this);
-    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY);
+    setGLFunctionAvailability(false, 0, 0, CTX_PROFILE_COMPAT);
     getGLStateTracker().setEnabled(false); // external context usage can't track state in Java
   }
 
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java
index ca30fde..4d02761 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11ExternalGLXDrawable.java
@@ -39,10 +39,15 @@
 
 package jogamp.opengl.x11.glx;
 
-import javax.media.nativewindow.*;
-import javax.media.nativewindow.x11.*;
-import javax.media.opengl.*;
-import jogamp.nativewindow.WrappedSurface;
+import javax.media.nativewindow.NativeSurface;
+import javax.media.opengl.GLContext;
+import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 
 public class X11ExternalGLXDrawable extends X11GLXDrawable {
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java
index f4f0119..96d4c77 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLCapabilities.java
@@ -29,43 +29,17 @@
 package jogamp.opengl.x11.glx;
 
 import jogamp.nativewindow.x11.XVisualInfo;
+
+import javax.media.nativewindow.NativeWindowException;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
-import java.util.Comparator;
 
 public class X11GLCapabilities extends GLCapabilities {
-  final XVisualInfo xVisualInfo; // maybe null if !onscreen
-  final long fbcfg;
-  final int  fbcfgid;
-
-  /** Comparing xvisual id only */
-  public static class XVisualIDComparator implements Comparator {
-
-      public int compare(Object o1, Object o2) {
-        if ( ! ( o1 instanceof X11GLCapabilities ) ) {
-            Class<?> c = (null != o1) ? o1.getClass() : null ;
-            throw new ClassCastException("arg1 not a X11GLCapabilities object: " + c);
-        }
-        if ( ! ( o2 instanceof X11GLCapabilities ) ) {
-            Class<?> c = (null != o2) ? o2.getClass() : null ;
-            throw new ClassCastException("arg2 not a X11GLCapabilities object: " + c);
-        }
-
-        final X11GLCapabilities caps1 = (X11GLCapabilities) o1;
-        final long id1 = caps1.getXVisualID();
-
-        final X11GLCapabilities caps2 = (X11GLCapabilities) o2;
-        final long id2 = caps2.getXVisualID();
-
-        if(id1 > id2) {
-            return 1;
-        } else if(id1 < id2) {
-            return -1;
-        }
-        return 0;
-      }
-  }
+  final private XVisualInfo xVisualInfo; // maybe null if !onscreen
+  final private long fbcfg;
+  final private int  fbcfgid;
 
   public X11GLCapabilities(XVisualInfo xVisualInfo, long fbcfg, int fbcfgid, GLProfile glp) {
       super(glp);
@@ -78,7 +52,7 @@ public class X11GLCapabilities extends GLCapabilities {
       super(glp);
       this.xVisualInfo = xVisualInfo;
       this.fbcfg = 0;
-      this.fbcfgid = -1;
+      this.fbcfgid = VisualIDHolder.VID_UNDEFINED;
   }
 
   public Object cloneMutable() {
@@ -94,25 +68,38 @@ public class X11GLCapabilities extends GLCapabilities {
   }
 
   final public XVisualInfo getXVisualInfo() { return xVisualInfo; }
-  final public long getXVisualID() { return (null!=xVisualInfo) ? xVisualInfo.getVisualid() : 0; }
+  final public int getXVisualID() { return (null!=xVisualInfo) ? (int) xVisualInfo.getVisualid() : 0; }
   final public boolean hasXVisualInfo() { return null!=xVisualInfo; }
 
   final public long getFBConfig() { return fbcfg; }
   final public int getFBConfigID() { return fbcfgid; }
-  final public boolean hasFBConfig() { return 0!=fbcfg && fbcfgid>0; }
-
-  final static String na_str = "----" ;
-
-  public StringBuffer toString(StringBuffer sink) {
+  final public boolean hasFBConfig() { return 0!=fbcfg && fbcfgid!=VisualIDHolder.VID_UNDEFINED; }
+
+  @Override
+  final public int getVisualID(VIDType type) throws NativeWindowException {
+      switch(type) {
+          case INTRINSIC:
+          case NATIVE:
+          case X11_XVISUAL:
+              return getXVisualID();
+          case X11_FBCONFIG:
+              return getFBConfigID();
+          default:
+              throw new NativeWindowException("Invalid type <"+type+">");
+      }      
+  }
+  
+  public StringBuilder toString(StringBuilder sink) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
+    sink.append("glx vid ");
     if(hasXVisualInfo()) {
         sink.append("0x").append(Long.toHexString(xVisualInfo.getVisualid()));
     } else {
         sink.append(na_str);
     }
-    sink.append(" ");
+    sink.append(", fbc ");
     if(hasFBConfig()) {
         sink.append("0x").append(Integer.toHexString(fbcfgid));
     } else {
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java
index c860019..2fd8cbc 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXContext.java
@@ -63,8 +63,6 @@ import com.jogamp.gluegen.runtime.ProcAddressTable;
 import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver;
 
 public abstract class X11GLXContext extends GLContextImpl {
-  protected static final boolean TRACE_CONTEXT_CURRENT = false; // true;
-
   private static final Map<String, String> functionNameMap;
   private static final Map<String, String> extensionNameMap;
   private GLXExt _glXExt;
@@ -139,11 +137,6 @@ public abstract class X11GLXContext extends GLContextImpl {
     boolean res = false;
 
     try {
-        if(TRACE_CONTEXT_CURRENT) {
-            Throwable t = new Throwable(Thread.currentThread()+" - glXMakeContextCurrent("+toHexString(dpy)+", "+
-                    toHexString(writeDrawable)+", "+toHexString(readDrawable)+", "+toHexString(ctx)+") - GLX >= 1.3 "+ isGLXVersionGreaterEqualOneThree());
-            t.printStackTrace();
-        }
         if ( isGLXVersionGreaterEqualOneThree() ) {
             res = GLX.glXMakeContextCurrent(dpy, writeDrawable, readDrawable, ctx);
         } else if ( writeDrawable == readDrawable ) {
@@ -153,8 +146,8 @@ public abstract class X11GLXContext extends GLContextImpl {
             throw new InternalError("Given readDrawable but no driver support");
         }
     } catch (RuntimeException re) {
-        if(DEBUG) {
-          System.err.println("Warning: X11GLXContext.glXMakeContextCurrent failed: "+re+", with "+
+        if(TRACE_SWITCH) {
+          System.err.println(getThreadName()+": Warning: X11GLXContext.glXMakeContextCurrent failed: "+re+", with "+
             "dpy "+toHexString(dpy)+
             ", write "+toHexString(writeDrawable)+
             ", read "+toHexString(readDrawable)+
@@ -190,10 +183,9 @@ public abstract class X11GLXContext extends GLContextImpl {
     updateGLXProcAddressTable();
     GLXExt _glXExt = getGLXExt();
     if(DEBUG) {
-      System.err.println("X11GLXContext.createContextARBImpl: "+getGLVersion(major, minor, ctp, "@creation") +
+      System.err.println(getThreadName()+": X11GLXContext.createContextARBImpl: "+getGLVersion(major, minor, ctp, "@creation") +
                          ", handle "+toHexString(drawable.getHandle()) + ", share "+toHexString(share)+", direct "+direct+
                          ", glXCreateContextAttribsARB: "+toHexString(glXExtProcAddressTable._addressof_glXCreateContextAttribsARB));
-      Thread.dumpStack();
     }
 
     boolean ctBwdCompat = 0 != ( CTX_PROFILE_COMPAT & ctp ) ;
@@ -220,7 +212,7 @@ public abstract class X11GLXContext extends GLContextImpl {
         if( !ctBwdCompat && ctFwdCompat ) {
             flags |= GLX.GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
         }
-        if( ctDebug) {
+        if( ctDebug ) {
             flags |= GLX.GLX_CONTEXT_DEBUG_BIT_ARB;
         }
         attribs.put(ctx_arb_attribs_idx_flags + 1, flags);
@@ -238,14 +230,14 @@ public abstract class X11GLXContext extends GLContextImpl {
         X11Lib.XSync(display, false);
     } catch (RuntimeException re) {
         if(DEBUG) {
-          Throwable t = new Throwable("Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re);
+          Throwable t = new Throwable(getThreadName()+": Info: X11GLXContext.createContextARBImpl glXCreateContextAttribsARB failed with "+getGLVersion(major, minor, ctp, "@creation"), re);
           t.printStackTrace();
         }
     }
     if(0!=ctx) {
         if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), ctx)) {
             if(DEBUG) {
-              System.err.println("X11GLXContext.createContextARBImpl couldn't make current "+getGLVersion(major, minor, ctp, "@creation"));
+              System.err.println(getThreadName()+": X11GLXContext.createContextARBImpl couldn't make current "+getGLVersion(major, minor, ctp, "@creation"));
             }
             // release & destroy
             glXMakeContextCurrent(display, 0, 0, 0);
@@ -263,7 +255,7 @@ public abstract class X11GLXContext extends GLContextImpl {
 
   protected boolean createImpl(GLContextImpl shareWith) {
       // covers the whole context creation loop incl createContextARBImpl and destroyContextARBImpl
-      X11Util.setX11ErrorHandler(true, true);
+      X11Util.setX11ErrorHandler(true, DEBUG ? false : true);
       try {
           return createImplRaw(shareWith);
       } finally {
@@ -296,16 +288,16 @@ public abstract class X11GLXContext extends GLContextImpl {
     if(config.getFBConfigID()<0) {
         // not able to use FBConfig
         if(glp.isGL3()) {
-          throw new GLException("Unable to create OpenGL >= 3.1 context");
+          throw new GLException(getThreadName()+": Unable to create OpenGL >= 3.1 context");
         }
         contextHandle = GLX.glXCreateContext(display, config.getXVisualInfo(), share, direct);
         if (contextHandle == 0) {
-          throw new GLException("Unable to create context(0)");
+          throw new GLException(getThreadName()+": Unable to create context(0)");
         }
         if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) {
-          throw new GLException("Error making temp context(0) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable);
+          throw new GLException(getThreadName()+": Error making temp context(0) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable);
         }
-        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); // use GL_VERSION
+        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT); // use GL_VERSION
         isDirect = GLX.glXIsDirect(display, contextHandle);
         if (DEBUG) {
             System.err.println(getThreadName() + ": createContextImpl: OK (old-1) share "+share+", direct "+isDirect+"/"+direct);
@@ -330,18 +322,19 @@ public abstract class X11GLXContext extends GLContextImpl {
         // so we are able to use GetProcAddress
         temp_ctx = GLX.glXCreateNewContext(display, config.getFBConfig(), GLX.GLX_RGBA_TYPE, share, direct);
         if (temp_ctx == 0) {
-            throw new GLException("Unable to create temp OpenGL context(1)");
+            throw new GLException(getThreadName()+": Unable to create temp OpenGL context(1)");
         }
         if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), temp_ctx)) {
-          throw new GLException("Error making temp context(1) current: display "+toHexString(display)+", context "+toHexString(temp_ctx)+", drawable "+drawable);
+          throw new GLException(getThreadName()+": Error making temp context(1) current: display "+toHexString(display)+", context "+toHexString(temp_ctx)+", drawable "+drawable);
         }
-        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); // use GL_VERSION
-        boolean isCreateContextAttribsARBAvailable = isFunctionAvailable("glXCreateContextAttribsARB");
+        setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT); // use GL_VERSION
         glXMakeContextCurrent(display, 0, 0, 0); // release temp context
 
         if( !createContextARBTried ) {
-            if ( isCreateContextAttribsARBAvailable &&
-                 isExtensionAvailable("GLX_ARB_create_context") ) {
+            // is*Available calls are valid since setGLFunctionAvailability(..) was called
+            final boolean isProcCreateContextAttribsARBAvailable = isFunctionAvailable("glXCreateContextAttribsARB");
+            final boolean isExtARBCreateContextAvailable = isExtensionAvailable("GLX_ARB_create_context");
+            if ( isProcCreateContextAttribsARBAvailable && isExtARBCreateContextAvailable ) {
                 // initial ARB context creation
                 contextHandle = createContextARB(share, direct);
                 createContextARBTried=true;
@@ -353,7 +346,8 @@ public abstract class X11GLXContext extends GLContextImpl {
                     }
                 }
             } else if (DEBUG) {
-                System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - extension not available - share "+share);
+                System.err.println(getThreadName() + ": createContextImpl: NOT OK (ARB, initial) - extension not available - share "+share+
+                                   ", isProcCreateContextAttribsARBAvailable "+isProcCreateContextAttribsARBAvailable+", isExtGLXARBCreateContextAvailable "+isExtARBCreateContextAvailable);
             }
         }
     }
@@ -363,17 +357,17 @@ public abstract class X11GLXContext extends GLContextImpl {
             glXMakeContextCurrent(display, 0, 0, 0);
             GLX.glXDestroyContext(display, temp_ctx);
             if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) {
-                throw new GLException("Cannot make previous verified context current");
+                throw new GLException(getThreadName()+": Cannot make previous verified context current");
             }
         }
     } else {
         if(glp.isGL3()) {
           glXMakeContextCurrent(display, 0, 0, 0);
           GLX.glXDestroyContext(display, temp_ctx);
-          throw new GLException("X11GLXContext.createContextImpl ctx !ARB, context > GL2 requested - requested: "+glp+", current: "+getGLVersion()+", ");
+          throw new GLException(getThreadName()+": X11GLXContext.createContextImpl ctx !ARB, context > GL2 requested - requested: "+glp+", current: "+getGLVersion()+", ");
         }
         if(DEBUG) {
-          System.err.println("X11GLXContext.createContextImpl failed, fall back to !ARB context "+getGLVersion());
+          System.err.println(getThreadName()+": X11GLXContext.createContextImpl failed, fall back to !ARB context "+getGLVersion());
         }
 
         // continue with temp context for GL <= 3.0
@@ -381,7 +375,7 @@ public abstract class X11GLXContext extends GLContextImpl {
         if (!glXMakeContextCurrent(display, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) {
           glXMakeContextCurrent(display, 0, 0, 0);
           GLX.glXDestroyContext(display, temp_ctx);
-          throw new GLException("Error making context(1) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable);
+          throw new GLException(getThreadName()+": Error making context(1) current: display "+toHexString(display)+", context "+toHexString(contextHandle)+", drawable "+drawable);
         }
         if (DEBUG) {
             System.err.println(getThreadName() + ": createContextImpl: OK (old-2) share "+share);
@@ -398,10 +392,10 @@ public abstract class X11GLXContext extends GLContextImpl {
     long dpy = drawable.getNativeSurface().getDisplayHandle();
 
     if (GLX.glXGetCurrentContext() != contextHandle) {
-        X11Util.setX11ErrorHandler(true, true);
+        X11Util.setX11ErrorHandler(true, DEBUG ? false : true);
         try {
             if (!glXMakeContextCurrent(dpy, drawable.getHandle(), drawableRead.getHandle(), contextHandle)) {
-                throw new GLException("Error making context current: "+this);
+                throw new GLException(getThreadName()+": Error making context current: "+this);
             }
         } finally {
             X11Util.setX11ErrorHandler(false, false);
@@ -411,10 +405,10 @@ public abstract class X11GLXContext extends GLContextImpl {
 
   protected void releaseImpl() throws GLException {
     long display = drawable.getNativeSurface().getDisplayHandle();
-    X11Util.setX11ErrorHandler(true, true);
+    X11Util.setX11ErrorHandler(true, DEBUG ? false : true);
     try {
         if (!glXMakeContextCurrent(display, 0, 0, 0)) {
-            throw new GLException("Error freeing OpenGL context");
+            throw new GLException(getThreadName()+": Error freeing OpenGL context");
         }
     } finally {
         X11Util.setX11ErrorHandler(false, false);
@@ -430,7 +424,7 @@ public abstract class X11GLXContext extends GLContextImpl {
     long src = source.getHandle();
     long display = drawable.getNativeSurface().getDisplayHandle();
     if (0 == display) {
-      throw new GLException("Connection to X display not yet set up");
+      throw new GLException(getThreadName()+": Connection to X display not yet set up");
     }
     GLX.glXCopyContext(display, src, dst, mask);
     // Should check for X errors and raise GLException
@@ -441,7 +435,7 @@ public abstract class X11GLXContext extends GLContextImpl {
     final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice();
     final String key = "GLX-"+adevice.getUniqueID();
     if (DEBUG) {
-      System.err.println(getThreadName() + ": !!! Initializing GLX extension address table: "+key);
+      System.err.println(getThreadName() + ": Initializing GLX extension address table: "+key);
     }
     ProcAddressTable table = null;
     synchronized(mappedContextTypeObjectLock) {
@@ -450,27 +444,24 @@ public abstract class X11GLXContext extends GLContextImpl {
     if(null != table) {
         glXExtProcAddressTable = (GLXExtProcAddressTable) table;
         if(DEBUG) {
-            System.err.println(getThreadName() + ": !!! GLContext GLX ProcAddressTable reusing key("+key+") -> "+table.hashCode());
+            System.err.println(getThreadName() + ": GLContext GLX ProcAddressTable reusing key("+key+") -> "+toHexString(table.hashCode()));
         }
     } else {
-        if (glXExtProcAddressTable == null) {
-          glXExtProcAddressTable = new GLXExtProcAddressTable(new GLProcAddressResolver());
-        }
+        glXExtProcAddressTable = new GLXExtProcAddressTable(new GLProcAddressResolver());
         resetProcAddressTable(getGLXExtProcAddressTable());
         synchronized(mappedContextTypeObjectLock) {
             mappedGLXProcAddress.put(key, getGLXExtProcAddressTable());
             if(DEBUG) {
-                System.err.println(getThreadName() + ": !!! GLContext GLX ProcAddressTable mapping key("+key+") -> "+getGLXExtProcAddressTable().hashCode());
-                Thread.dumpStack();
+                System.err.println(getThreadName() + ": GLContext GLX ProcAddressTable mapping key("+key+") -> "+toHexString(getGLXExtProcAddressTable().hashCode()));
             }
         }
     }
   }
 
-  protected final StringBuffer getPlatformExtensionsStringImpl() {
-    StringBuffer sb = new StringBuffer();
+  protected final StringBuilder getPlatformExtensionsStringImpl() {
+    StringBuilder sb = new StringBuilder();
     if (DEBUG) {
-      System.err.println("!!! GLX Version client version "+ GLXUtil.getClientVersionNumber()+
+      System.err.println("GLX Version client version "+ GLXUtil.getClientVersionNumber()+
                          ", server: "+         
         ((X11GLXDrawableFactory)drawable.getFactoryImpl()).getGLXVersionNumber(drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice()));
     }
@@ -479,21 +470,21 @@ public abstract class X11GLXContext extends GLContextImpl {
         {
             final String ret = GLX.glXGetClientString(ns.getDisplayHandle(), GLX.GLX_EXTENSIONS);
             if (DEBUG) {
-              System.err.println("!!! GLX extensions (glXGetClientString): " + ret);
+              System.err.println("GLX extensions (glXGetClientString): " + ret);
             }
             sb.append(ret).append(" ");
         }
         {
             final String ret = GLX.glXQueryExtensionsString(ns.getDisplayHandle(), ns.getScreenIndex());
             if (DEBUG) {
-              System.err.println("!!! GLX extensions (glXQueryExtensionsString): " + ret);
+              System.err.println("GLX extensions (glXQueryExtensionsString): " + ret);
             }
             sb.append(ret).append(" ");
         }
         {
             final String ret = GLX.glXQueryServerString(ns.getDisplayHandle(), ns.getScreenIndex(), GLX.GLX_EXTENSIONS);
             if (DEBUG) {
-              System.err.println("!!! GLX extensions (glXQueryServerString): " + ret);
+              System.err.println("GLX extensions (glXQueryServerString): " + ret);
             }
             sb.append(ret).append(" ");
         }
@@ -511,10 +502,10 @@ public abstract class X11GLXContext extends GLContextImpl {
   }
 
   @Override
-  protected void setSwapIntervalImpl(int interval) {
+  protected boolean setSwapIntervalImpl(int interval) {
     X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)drawable.getNativeSurface().getGraphicsConfiguration();
     GLCapabilitiesImmutable glCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities();
-    if(!glCaps.isOnscreen()) return;
+    if(!glCaps.isOnscreen()) { return false; }
 
     GLXExt glXExt = getGLXExt();
     if(0==hasSwapIntervalSGI) {
@@ -524,11 +515,10 @@ public abstract class X11GLXContext extends GLContextImpl {
     }
     if (hasSwapIntervalSGI>0) {
         try {
-            if( 0 == glXExt.glXSwapIntervalSGI(interval) ) {
-                currentSwapInterval = interval;
-            }
+            return 0 == glXExt.glXSwapIntervalSGI(interval);
         } catch (Throwable t) { hasSwapIntervalSGI=-1; }
     }
+    return false;
   }
 
   private final int initSwapGroupImpl(GLXExt glXExt) {
@@ -616,7 +606,7 @@ public abstract class X11GLXContext extends GLContextImpl {
   }
 
   public String toString() {
-    StringBuffer sb = new StringBuffer();
+    StringBuilder sb = new StringBuilder();
     sb.append(getClass().getSimpleName());
     sb.append(" [");
     super.append(sb);
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java
index 28c02cd..61f2ef9 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawable.java
@@ -60,7 +60,7 @@ public abstract class X11GLXDrawable extends GLDrawableImpl {
         config.updateGraphicsConfiguration();
 
         if (DEBUG) {
-          System.err.println("!!! X11GLXDrawable.setRealized(true): "+config);
+          System.err.println("X11GLXDrawable.setRealized(true): "+config);
         }
     }
   }
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java
index 235aea4..223c504 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDrawableFactory.java
@@ -49,8 +49,6 @@ import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.NativeSurface;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.nativewindow.ProxySurface;
-import javax.media.nativewindow.x11.X11GraphicsDevice;
-import javax.media.nativewindow.x11.X11GraphicsScreen;
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLContext;
@@ -59,7 +57,6 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 import javax.media.opengl.GLProfile.ShutdownType;
 
-import jogamp.nativewindow.WrappedSurface;
 import jogamp.nativewindow.x11.X11Lib;
 import jogamp.nativewindow.x11.X11Util;
 import jogamp.opengl.DesktopGLDynamicLookupHelper;
@@ -70,6 +67,9 @@ import jogamp.opengl.GLDynamicLookupHelper;
 import jogamp.opengl.SharedResourceRunner;
 
 import com.jogamp.common.util.VersionNumber;
+import com.jogamp.nativewindow.WrappedSurface;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
   
@@ -93,20 +93,21 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
                 if(DEBUG) {
                     gle.printStackTrace();
                 }
-            }
-            x11GLXDynamicLookupHelper = tmp;
-            if(null!=x11GLXDynamicLookupHelper) {
+            }            
+            if(null!=tmp && tmp.isLibComplete()) {
+                x11GLXDynamicLookupHelper = tmp;
                 GLX.getGLXProcAddressTable().reset(x11GLXDynamicLookupHelper);
             }
         }
     }
     
-    if(null!=x11GLXDynamicLookupHelper) {        
+    defaultDevice = new X11GraphicsDevice(X11Util.getNullDisplayName(), AbstractGraphicsDevice.DEFAULT_UNIT);
+    
+    if(null!=x11GLXDynamicLookupHelper) {
         // Register our GraphicsConfigurationFactory implementations
         // The act of constructing them causes them to be registered
         X11GLXGraphicsConfigurationFactory.registerFactory();
         
-        defaultDevice = new X11GraphicsDevice(X11Util.getNullDisplayName(), AbstractGraphicsDevice.DEFAULT_UNIT);
         sharedMap = new HashMap<String, SharedResourceRunner.Resource>();
         
         // Init shared resources off thread
@@ -139,7 +140,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
     X11Util.shutdown( false, DEBUG );
   }
 
-  public GLDynamicLookupHelper getGLDynamicLookupHelper(int profile) {
+  public final GLDynamicLookupHelper getGLDynamicLookupHelper(int profile) {
       return x11GLXDynamicLookupHelper;
   }
 
@@ -219,7 +220,10 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
                     //                       NativeWindowFactory.getNullToolkitLock(), true); // own non-shared display connection, no locking
             sharedDevice.lock();
             try {
-                GLXUtil.initGLXClientDataSingleton(sharedDevice);
+                if(!GLXUtil.isGLXAvailableOnServer(sharedDevice)) {
+                    throw new GLException("GLX not available on device/server: "+sharedDevice);
+                }
+                GLXUtil.initGLXClientDataSingleton(sharedDevice);                
                 final String glXServerVendorName = GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_VENDOR);
                 final VersionNumber glXServerVersion = GLXUtil.getGLXServerVersionNumber(sharedDevice.getHandle());
                 final boolean glXServerMultisampleAvailable = GLXUtil.isMultisampleAvailable(GLX.glXQueryServerString(sharedDevice.getHandle(), 0, GLX.GLX_EXTENSIONS));                
@@ -229,7 +233,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
                 }
                 X11GraphicsScreen sharedScreen = new X11GraphicsScreen(sharedDevice, 0);
 
-                GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP);
+                GLProfile glp = GLProfile.get(sharedDevice, GLProfile.GL_PROFILE_LIST_MIN_DESKTOP, false);
                 if (null == glp) {
                     throw new GLException("Couldn't get default GLProfile for device: "+sharedDevice);
                 }
@@ -250,15 +254,15 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
                     sharedContext.release();
                 }
                 if (DEBUG) {
-                    System.err.println("!!! SharedDevice:  " + sharedDevice);
-                    System.err.println("!!! SharedScreen:  " + sharedScreen);
-                    System.err.println("!!! SharedContext: " + sharedContext + ", madeCurrent " + madeCurrent);
-                    System.err.println("!!! GLX Server Vendor:      " + glXServerVendorName);
-                    System.err.println("!!! GLX Server Version:     " + glXServerVersion);
-                    System.err.println("!!! GLX Server Multisample: " + glXServerMultisampleAvailable);
-                    System.err.println("!!! GLX Client Vendor:      " + GLXUtil.getClientVendorName());
-                    System.err.println("!!! GLX Client Version:     " + GLXUtil.getClientVersionNumber());
-                    System.err.println("!!! GLX Client Multisample: " + GLXUtil.isClientMultisampleAvailable());
+                    System.err.println("SharedDevice:  " + sharedDevice);
+                    System.err.println("SharedScreen:  " + sharedScreen);
+                    System.err.println("SharedContext: " + sharedContext + ", madeCurrent " + madeCurrent);
+                    System.err.println("GLX Server Vendor:      " + glXServerVendorName);
+                    System.err.println("GLX Server Version:     " + glXServerVersion);
+                    System.err.println("GLX Server Multisample: " + glXServerMultisampleAvailable);
+                    System.err.println("GLX Client Vendor:      " + GLXUtil.getClientVendorName());
+                    System.err.println("GLX Client Version:     " + GLXUtil.getClientVersionNumber());
+                    System.err.println("GLX Client Multisample: " + GLXUtil.isClientMultisampleAvailable());
                 }
                 return new SharedResource(sharedDevice, sharedScreen, sharedDrawable, sharedContext, 
                                           glXServerVersion, glXServerVendorName, 
@@ -273,17 +277,16 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
         public void releaseSharedResource(SharedResourceRunner.Resource shared) {
             SharedResource sr = (SharedResource) shared;
             if (DEBUG) {
-                System.err.println("!!! Shutdown Shared:");
-                System.err.println("!!!   Device  : " + sr.device);
-                System.err.println("!!!   Screen  : " + sr.screen);
-                System.err.println("!!!   Drawable: " + sr.drawable);
-                System.err.println("!!!   CTX     : " + sr.context);
+                System.err.println("Shutdown Shared:");
+                System.err.println("Device  : " + sr.device);
+                System.err.println("Screen  : " + sr.screen);
+                System.err.println("Drawable: " + sr.drawable);
+                System.err.println("CTX     : " + sr.context);
                 Thread.dumpStack();
             }
 
             if (null != sr.context) {
                 // may cause JVM SIGSEGV:
-                sr.context.makeCurrent();
                 sr.context.destroy();
                 sr.context = null;
             }
@@ -311,7 +314,7 @@ public class X11GLXDrawableFactory extends GLDrawableFactoryImpl {
   }
 
   public final boolean getIsDeviceCompatible(AbstractGraphicsDevice device) {
-      if(device instanceof X11GraphicsDevice) {
+      if(null != x11GLXDynamicLookupHelper && device instanceof X11GraphicsDevice) {
           return true;
       }
       return false;
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java
index eb6c17c..108c157 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXDynamicLibraryBundleInfo.java
@@ -36,6 +36,7 @@ public class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBundl
         super();
     }
 
+    @Override
     public List<List<String>> getToolLibNames() {
         final List<List<String>> libsList = new ArrayList<List<String>>();
         final List<String> libsGL = new ArrayList<String>();
@@ -65,8 +66,10 @@ public class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBundl
      * http://dri.sourceforge.net/doc/DRIuserguide.html
      * </pre>
      */
+    @Override
     public boolean shallLinkGlobal() { return true; }
 
+    @Override
     public final List<String> getToolGetProcAddressFuncNameList() {
         List<String> res = new ArrayList<String>();
         res.add("glXGetProcAddressARB");
@@ -74,6 +77,7 @@ public class X11GLXDynamicLibraryBundleInfo extends DesktopGLDynamicLibraryBundl
         return res;
     }
 
+    @Override
     public final long toolGetProcAddress(long toolGetProcAddressHandle, String funcName) {
         return GLX.glXGetProcAddress(toolGetProcAddressHandle, funcName);
     }
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java
index 4d0c3ee..0af6239 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfiguration.java
@@ -36,8 +36,6 @@ package jogamp.opengl.x11.glx;
 import java.util.ArrayList;
 
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.x11.X11GraphicsConfiguration;
-import javax.media.nativewindow.x11.X11GraphicsScreen;
 import javax.media.opengl.DefaultGLCapabilitiesChooser;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLCapabilities;
@@ -51,14 +49,13 @@ import jogamp.nativewindow.x11.X11Lib;
 import jogamp.nativewindow.x11.XRenderDirectFormat;
 import jogamp.nativewindow.x11.XRenderPictFormat;
 import jogamp.nativewindow.x11.XVisualInfo;
-import jogamp.opengl.Debug;
 import jogamp.opengl.GLGraphicsConfigurationUtil;
 
 import com.jogamp.common.nio.PointerBuffer;
+import com.jogamp.nativewindow.x11.X11GraphicsConfiguration;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implements Cloneable {
-    protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration");
-    
     public static final int MAX_ATTRIBS = 128;
     private GLCapabilitiesChooser chooser; 
 
@@ -109,7 +106,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem
             setXVisualInfo(newConfig.getXVisualInfo());
             setChosenCapabilities(newConfig.getChosenCapabilities());
             if(DEBUG) {
-                System.err.println("!!! updateGraphicsConfiguration: "+this);
+                System.err.println("updateGraphicsConfiguration: "+this);
             }
         }
     }
@@ -176,14 +173,16 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem
         res[idx++] = caps.getGreenBits();
         res[idx++] = GLX.GLX_BLUE_SIZE;
         res[idx++] = caps.getBlueBits();
-        res[idx++] = GLX.GLX_ALPHA_SIZE;
-        res[idx++] = caps.getAlphaBits();
-        res[idx++] = GLX.GLX_DEPTH_SIZE;
-        res[idx++] = caps.getDepthBits();
+        if(caps.getAlphaBits()>0) {
+            res[idx++] = GLX.GLX_ALPHA_SIZE;
+            res[idx++] = caps.getAlphaBits();
+        }
         if (caps.getStencilBits() > 0) {
           res[idx++] = GLX.GLX_STENCIL_SIZE;
           res[idx++] = caps.getStencilBits();
         }
+        res[idx++] = GLX.GLX_DEPTH_SIZE;
+        res[idx++] = caps.getDepthBits();
         if (caps.getAccumRedBits()   > 0 ||
             caps.getAccumGreenBits() > 0 ||
             caps.getAccumBlueBits()  > 0 ||
@@ -383,8 +382,8 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem
       }  
       XVisualInfo res = XVisualInfo.create(infos[0]);
       if (DEBUG) {
-        System.err.println("!!! Fetched XVisualInfo for visual ID " + toHexString(visualID));
-        System.err.println("!!! Resulting XVisualInfo: visualid = " + toHexString(res.getVisualid()));
+        System.err.println("Fetched XVisualInfo for visual ID " + toHexString(visualID));
+        System.err.println("Resulting XVisualInfo: visualid = " + toHexString(res.getVisualid()));
       }
       return res;
   }
@@ -475,7 +474,7 @@ public class X11GLXGraphicsConfiguration extends X11GraphicsConfiguration implem
   }
 
   public String toString() {
-    return "X11GLXGraphicsConfiguration["+getScreen()+", visualID " + toHexString(getVisualID()) + ", fbConfigID " + toHexString(getFBConfigID()) +
+    return "X11GLXGraphicsConfiguration["+getScreen()+", visualID " + toHexString(getXVisualID()) + ", fbConfigID " + toHexString(getFBConfigID()) +
                                         ",\n\trequested " + getRequestedCapabilities()+
                                         ",\n\tchosen    " + getChosenCapabilities()+
                                         "]";
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java
index a72de8c..0ec2f23 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11GLXGraphicsConfigurationFactory.java
@@ -39,8 +39,7 @@ import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
-import javax.media.nativewindow.x11.X11GraphicsScreen;
-import javax.media.nativewindow.x11.X11GraphicsDevice;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.opengl.DefaultGLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLCapabilitiesChooser;
@@ -50,9 +49,11 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
 import com.jogamp.common.nio.PointerBuffer;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
+
 import jogamp.nativewindow.x11.X11Lib;
 import jogamp.nativewindow.x11.XVisualInfo;
-import jogamp.opengl.Debug;
 import jogamp.opengl.GLGraphicsConfigurationFactory;
 import jogamp.opengl.GLGraphicsConfigurationUtil;
 
@@ -67,11 +68,19 @@ import java.util.List;
     GraphicsDevice and GraphicsConfiguration abstractions. */
 
 public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationFactory {
-    protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration");
-    static X11GLCapabilities.XVisualIDComparator XVisualIDComparator = new X11GLCapabilities.XVisualIDComparator();
+    static VisualIDHolder.VIDComparator XVisualIDComparator = new VisualIDHolder.VIDComparator(VisualIDHolder.VIDType.X11_XVISUAL);
 
+    static GraphicsConfigurationFactory fallbackX11GraphicsConfigurationFactory = null;
     static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.x11.X11GraphicsDevice.class, new X11GLXGraphicsConfigurationFactory());
+        final GraphicsConfigurationFactory newFactory = new X11GLXGraphicsConfigurationFactory();
+        final GraphicsConfigurationFactory oldFactory = GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, newFactory);
+        if(oldFactory == newFactory) {
+            throw new InternalError("GraphicsConfigurationFactory lifecycle impl. error");
+        }
+        if(null == oldFactory) {
+            throw new InternalError("Missing fallback GraphicsConfigurationFactory");
+        }
+        fallbackX11GraphicsConfigurationFactory = oldFactory;
     }
     private X11GLXGraphicsConfigurationFactory() {
     }
@@ -93,6 +102,16 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) {
             throw new IllegalArgumentException("This NativeWindowFactory accepts only GLCapabilitiesChooser objects");
         }
+        
+        if(!GLXUtil.isGLXAvailableOnServer((X11GraphicsDevice)absScreen.getDevice())) {
+            if(null != fallbackX11GraphicsConfigurationFactory) {
+                if(DEBUG) {
+                    System.err.println("No GLX available, fallback to "+fallbackX11GraphicsConfigurationFactory.getClass().getSimpleName()+" for: "+absScreen);
+                }
+                return fallbackX11GraphicsConfigurationFactory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, absScreen);
+            }
+            throw new InternalError("No GLX and no fallback GraphicsConfigurationFactory available for: "+absScreen);
+        }        
         return chooseGraphicsConfigurationStatic((GLCapabilitiesImmutable)capsChosen, (GLCapabilitiesImmutable)capsRequested,
                                                  (GLCapabilitiesChooser)chooser, (X11GraphicsScreen)absScreen);
     }
@@ -187,7 +206,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         if (capsChosen == null) {
             capsChosen = new GLCapabilities(null);
         }
-        X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice();
+        X11GraphicsDevice x11Device = (X11GraphicsDevice) x11Screen.getDevice();        
         X11GLXDrawableFactory factory = (X11GLXDrawableFactory) GLDrawableFactory.getDesktopFactory();
 
         capsChosen = GLGraphicsConfigurationUtil.fixGLCapabilities( capsChosen, factory.canCreateGLPbuffer(x11Device) );
@@ -266,13 +285,13 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
             if(availableCaps.size() > 0) {
                 recommendedIndex = capsChosen.isBackgroundOpaque() ? 0 : -1; // only use recommended idx if not translucent
                 if (DEBUG) {
-                    System.err.println("!!! glXChooseFBConfig recommended fbcfg " + toHexString(fbcfgsL.get(0)) + ", idx " + recommendedIndex);
-                    System.err.println("!!! user  caps " + capsChosen);
-                    System.err.println("!!! fbcfg caps " + availableCaps.get(0));
+                    System.err.println("glXChooseFBConfig recommended fbcfg " + toHexString(fbcfgsL.get(0)) + ", idx " + recommendedIndex);
+                    System.err.println("user  caps " + capsChosen);
+                    System.err.println("fbcfg caps " + availableCaps.get(0));
                 }
             } else if (DEBUG) {
-                System.err.println("!!! glXChooseFBConfig no caps for recommended fbcfg " + toHexString(fbcfgsL.get(0)));
-                System.err.println("!!! user  caps " + capsChosen);
+                System.err.println("glXChooseFBConfig no caps for recommended fbcfg " + toHexString(fbcfgsL.get(0)));
+                System.err.println("user  caps " + capsChosen);
             }
         }
 
@@ -300,6 +319,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         int chosenIndex = chooseCapabilities(chooser, capsChosen, availableCaps, recommendedIndex);
         if ( 0 > chosenIndex ) {
             if (DEBUG) {
+                System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: failed, return null");
                 Thread.dumpStack();
             }
             return null;
@@ -333,7 +353,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         // 1st choice: get GLCapabilities based on users GLCapabilities setting recommendedIndex as preferred choice
         XVisualInfo recommendedVis = GLX.glXChooseVisual(display, screen, attribs, 0);
         if (DEBUG) {
-            System.err.print("!!! glXChooseVisual recommended ");
+            System.err.print("glXChooseVisual recommended ");
             if (recommendedVis == null) {
                 System.err.println("null visual");
             } else {
@@ -353,7 +373,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         for (int i = 0; i < infos.length; i++) {
             if( !X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(availableCaps, glProfile, display, infos[i], winattrmask, isMultisampleAvailable) ) {
                 if(DEBUG) {
-                    System.err.println("X11GLXGraphicsConfiguration.getAvailableGLCapabilitiesXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid()));
+                    System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual: XVisual invalid: ("+x11Screen+"): fbcfg: "+toHexString(infos[i].getVisualid()));
                 }
             } else {
                 // Attempt to find the visual chosenIndex by glXChooseVisual, if not translucent
@@ -366,6 +386,7 @@ public class X11GLXGraphicsConfigurationFactory extends GLGraphicsConfigurationF
         int chosenIndex = chooseCapabilities(chooser, capsChosen, availableCaps, recommendedIndex);
         if ( 0 > chosenIndex ) {
             if (DEBUG) {
+                System.err.println("X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual: failed, return null");
                 Thread.dumpStack();
             }
             return null;
diff --git a/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java b/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java
index 333486a..b2a8326 100644
--- a/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java
+++ b/src/jogl/classes/jogamp/opengl/x11/glx/X11OnscreenGLXDrawable.java
@@ -75,7 +75,7 @@ public class X11OnscreenGLXDrawable extends X11GLXDrawable {
   }
 
   @Override
-  protected void updateHandle() {
+  protected final void updateHandle() {
     if(USE_GLXWINDOW) {
         X11GLXGraphicsConfiguration config = (X11GLXGraphicsConfiguration)getNativeSurface().getGraphicsConfiguration();
         if(config.getFBConfig()>=0) {
@@ -86,7 +86,7 @@ public class X11OnscreenGLXDrawable extends X11GLXDrawable {
             }
             glXWindow = GLX.glXCreateWindow(dpy, config.getFBConfig(), getNativeSurface().getSurfaceHandle(), null, 0);
             if (DEBUG) {
-              System.err.println("!!! X11OnscreenGLXDrawable.setRealized(true): glXWindow: "+toHexString(getNativeSurface().getSurfaceHandle())+" -> "+toHexString(glXWindow));
+              System.err.println("X11OnscreenGLXDrawable.setRealized(true): glXWindow: "+toHexString(getNativeSurface().getSurfaceHandle())+" -> "+toHexString(glXWindow));
             }
             if(0==glXWindow) {
                 throw new GLException("X11OnscreenGLXDrawable.setRealized(true): GLX.glXCreateWindow() failed: "+this);
diff --git a/src/jogl/native/JoglCommon.c b/src/jogl/native/JoglCommon.c
index 16f60e4..d9f5edd 100644
--- a/src/jogl/native/JoglCommon.c
+++ b/src/jogl/native/JoglCommon.c
@@ -1,46 +1,82 @@
 
+#include "jogamp_opengl_GLContextImpl.h"
 #include "JoglCommon.h"
 
+#include <assert.h>
+#include <KHR/khrplatform.h>
+
 static const char * const ClazzNameRuntimeException = "java/lang/RuntimeException";
 static jclass    runtimeExceptionClz=NULL;
 
+static JavaVM *_jvmHandle = NULL;
+static int _jvmVersion = 0;
+
+void JoglCommon_init(JNIEnv *env) {
+    if(NULL==runtimeExceptionClz) {
+        jclass c = (*env)->FindClass(env, ClazzNameRuntimeException);
+        if(NULL==c) {
+            JoglCommon_FatalError(env, "JOGL: can't find %s", ClazzNameRuntimeException);
+        }
+        runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c);
+        (*env)->DeleteLocalRef(env, c);
+        if(NULL==runtimeExceptionClz) {
+            JoglCommon_FatalError(env, "JOGL: can't use %s", ClazzNameRuntimeException);
+        }
+    }
+    if(0 != (*env)->GetJavaVM(env, &_jvmHandle)) {
+        JoglCommon_FatalError(env, "JOGL: can't fetch JavaVM handle");
+    } else {
+        _jvmVersion = (*env)->GetVersion(env);
+    }
+}
+
 void JoglCommon_FatalError(JNIEnv *env, const char* msg, ...)
 {
     char buffer[512];
     va_list ap;
+    int shallBeDetached = 0;
+
+    if(NULL == env) {
+        env = JoglCommon_GetJNIEnv (&shallBeDetached);
+    }
 
     va_start(ap, msg);
     vsnprintf(buffer, sizeof(buffer), msg, ap);
     va_end(ap);
 
     fprintf(stderr, "%s\n", buffer);
-    (*env)->FatalError(env, buffer);
+    if(NULL != env) {
+        (*env)->FatalError(env, buffer);
+        JoglCommon_ReleaseJNIEnv (shallBeDetached);
+    }
 }
 
 void JoglCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...)
 {
     char buffer[512];
     va_list ap;
+    int shallBeDetached = 0;
+
+    if(NULL == env) {
+        env = JoglCommon_GetJNIEnv (&shallBeDetached);
+    }
 
     va_start(ap, msg);
     vsnprintf(buffer, sizeof(buffer), msg, ap);
     va_end(ap);
 
-    (*env)->ThrowNew(env, runtimeExceptionClz, buffer);
+    if(NULL != env) {
+        (*env)->ThrowNew(env, runtimeExceptionClz, buffer);
+        JoglCommon_ReleaseJNIEnv (shallBeDetached);
+    }
 }
 
-void JoglCommon_init(JNIEnv *env) {
-    if(NULL==runtimeExceptionClz) {
-        jclass c = (*env)->FindClass(env, ClazzNameRuntimeException);
-        if(NULL==c) {
-            JoglCommon_FatalError(env, "JOGL: can't find %s", ClazzNameRuntimeException);
-        }
-        runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c);
-        (*env)->DeleteLocalRef(env, c);
-        if(NULL==runtimeExceptionClz) {
-            JoglCommon_FatalError(env, "JOGL: can't use %s", ClazzNameRuntimeException);
-        }
-    }
+JavaVM *JoglCommon_GetJVMHandle() {
+    return _jvmHandle;
+}
+
+int JoglCommon_GetJVMVersion() {
+    return _jvmVersion;
 }
 
 jchar* JoglCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str)
@@ -53,3 +89,63 @@ jchar* JoglCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str)
     return strChars;
 }
 
+JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached)
+{
+    JNIEnv* curEnv = NULL;
+    JNIEnv* newEnv = NULL;
+    int envRes;
+
+    if(NULL == _jvmHandle) {
+        fprintf(stderr, "JOGL: No JavaVM handle registered, call JoglCommon_init(..) 1st");
+        return NULL;
+    }
+
+    // retrieve this thread's JNIEnv curEnv - or detect it's detached
+    envRes = (*_jvmHandle)->GetEnv(_jvmHandle, (void **) &curEnv, _jvmVersion) ;
+    if( JNI_EDETACHED == envRes ) {
+        // detached thread - attach to JVM
+        if( JNI_OK != ( envRes = (*_jvmHandle)->AttachCurrentThread(_jvmHandle, (void**) &newEnv, NULL) ) ) {
+            fprintf(stderr, "JNIEnv: can't attach thread: %d\n", envRes);
+            return NULL;
+        }
+        curEnv = newEnv;
+    } else if( JNI_OK != envRes ) {
+        // oops ..
+        fprintf(stderr, "can't GetEnv: %d\n", envRes);
+        return NULL;
+    }
+    if (curEnv==NULL) {
+        fprintf(stderr, "env is NULL\n");
+        return NULL;
+    }
+    *shallBeDetached = NULL != newEnv;
+    return curEnv;
+}
+
+void JoglCommon_ReleaseJNIEnv (int shallBeDetached) {
+    if(NULL == _jvmHandle) {
+        fprintf(stderr, "JOGL: No JavaVM handle registered, call JoglCommon_init(..) 1st");
+    }
+
+    if(shallBeDetached) {
+        (*_jvmHandle)->DetachCurrentThread(_jvmHandle);
+    }
+}
+
+/*
+ * Class:     jogamp_opengl_GLContextImpl
+ * Method:    glGetStringInt
+ * Signature: (IJ)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL 
+Java_jogamp_opengl_GLContextImpl_glGetStringInt(JNIEnv *env, jclass _unused, jint name, jlong procAddress) {
+  typedef const khronos_uint8_t *  (KHRONOS_APIENTRY*_local_PFNGLGETSTRINGPROC)(unsigned int name);
+  _local_PFNGLGETSTRINGPROC ptr_glGetString;
+  const khronos_uint8_t *  _res;
+  ptr_glGetString = (_local_PFNGLGETSTRINGPROC) (intptr_t) procAddress;
+  assert(ptr_glGetString != NULL);
+  _res = (* ptr_glGetString) ((unsigned int) name);
+  if (NULL == _res) return NULL;
+  return (*env)->NewStringUTF(env, _res);
+}
+
diff --git a/src/jogl/native/JoglCommon.h b/src/jogl/native/JoglCommon.h
index d82b445..023b4be 100644
--- a/src/jogl/native/JoglCommon.h
+++ b/src/jogl/native/JoglCommon.h
@@ -7,9 +7,45 @@
 
 void JoglCommon_init(JNIEnv *env);
 
+/** Set by JoglCommon_init */
+JavaVM *JoglCommon_GetJVMHandle();
+
+/** Set by JoglCommon_init */
+int JoglCommon_GetJVMVersion();
+
 jchar* JoglCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str);
 
+/** env may be NULL, in which case JoglCommon_GetJNIEnv() is being used. */
 void JoglCommon_FatalError(JNIEnv *env, const char* msg, ...);
+
+/** env may be NULL, in which case JoglCommon_GetJNIEnv() is being used. */
 void JoglCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...);
 
+/**
+ *
+ * 1) Store jvmHandle and jvmVersion is done by 'JoglCommon_init(JNIEnv*)'
+ *    and internally used by 'JoglCommon_GetJNIEnv(..)' and 'JoglCommon_ReleaseJNIEnv(..)'.
+ *
+ * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv
+ *
+    int shallBeDetached = 0;
+    JNIEnv* env = NewtCommon_GetJNIEnv(&shallBeDetached);
+    if(NULL==env) {
+        DBG_PRINT("drawRect: null JNIEnv\n");
+        return;
+    }
+    
+ *
+ * 3) Use JNIEnv ..
+ *
+    .. your JNIEnv code here ..
+
+ *
+ * 4) Detach thread from JVM, if required
+ *
+    JoglCommon_ReleaseJNIEnv (shallBeDetached);
+ */
+JNIEnv* JoglCommon_GetJNIEnv (int * shallBeDetached);
+void JoglCommon_ReleaseJNIEnv (int shallBeDetached);
+
 #endif
diff --git a/src/jogl/native/libav/ffmpeg_tool.h b/src/jogl/native/libav/ffmpeg_tool.h
new file mode 100644
index 0000000..3181a8a
--- /dev/null
+++ b/src/jogl/native/libav/ffmpeg_tool.h
@@ -0,0 +1,106 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+ 
+#ifndef _FFMPEG_TOOL_H
+#define _FFMPEG_TOOL_H
+
+#ifdef _WIN32
+    #include <windows.h>
+    // __declspec(dllimport) void __stdcall Sleep(unsigned long dwMilliseconds);
+
+    #define usleep(t)    Sleep((t) / 1000)
+#endif
+
+#include <gluegen_stdint.h>
+#include <gluegen_inttypes.h>
+#include <gluegen_stddef.h>
+#include <gluegen_stdint.h>
+
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/**
+ *  AV_TIME_BASE   1000000
+ */
+#define AV_TIME_BASE_MSEC    (AV_TIME_BASE/1000)
+
+static inline float my_av_q2f(AVRational a){
+    return a.num / (float) a.den;
+}
+static inline int32_t my_av_q2i32(int32_t snum, AVRational a){
+    return (snum * a.num) / a.den;
+}
+
+typedef struct {
+    int32_t          verbose;
+
+    AVFormatContext* pFormatCtx;
+    int32_t          vid;
+    AVStream*        pVStream;
+    AVCodecContext*  pVCodecCtx;
+    AVCodec*         pVCodec;
+    AVFrame*         pVFrame; 
+    uint32_t         vBufferPlanes; // 1 for RGB*, 3 for YUV, ..
+    uint32_t         vBitsPerPixel;
+    uint32_t         vBytesPerPixelPerPlane;
+    enum PixelFormat vPixFmt;    // native decoder fmt
+    int32_t          vPTS;       // msec - overall last video PTS
+    int32_t          vLinesize[3];  // decoded video linesize in bytes for each plane
+    int32_t          vTexWidth[3];  // decoded video tex width in bytes for each plane
+
+
+    int32_t          aid;
+    AVStream*        pAStream;
+    AVCodecContext*  pACodecCtx;
+    AVCodec*         pACodec;
+    AVFrame*         pAFrame;
+    int32_t          aSampleRate;
+    int32_t          aChannels;
+    int32_t          aFrameSize;
+    enum AVSampleFormat aSampleFmt; // native decoder fmt
+    int32_t          aPTS;       // msec - overall last audio PTS
+
+    float            fps;        // frames per seconds
+    int32_t          bps_stream; // bits per seconds
+    int32_t          bps_video;  // bits per seconds
+    int32_t          bps_audio;  // bits per seconds
+    int32_t          totalFrames;
+    int32_t          duration;   // msec
+    int32_t          start_time; // msec
+
+    char             acodec[64];
+    char             vcodec[64];
+
+} FFMPEGToolBasicAV_t ;
+
+#endif /* _FFMPEG_TOOL_H */
+
diff --git a/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c b/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c
new file mode 100644
index 0000000..647de15
--- /dev/null
+++ b/src/jogl/native/libav/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c
@@ -0,0 +1,717 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+ 
+#include "jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.h"
+
+#include "JoglCommon.h"
+#include "ffmpeg_tool.h"
+#include <libavutil/pixdesc.h>
+#include <GL/gl.h>
+
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+
+static const char * const ClazzNameFFMPEGMediaPlayer = "jogamp/opengl/util/av/impl/FFMPEGMediaPlayer";
+
+static jclass ffmpegMediaPlayerClazz = NULL;
+static jmethodID jni_mid_updateAttributes1 = NULL;
+static jmethodID jni_mid_updateAttributes2 = NULL;
+
+#define HAS_FUNC(f) (NULL!=(f))
+
+typedef unsigned (APIENTRYP AVCODEC_VERSION)(void);
+typedef unsigned (APIENTRYP AVUTIL_VERSION)(void);
+typedef unsigned (APIENTRYP AVFORMAT_VERSION)(void);
+
+static AVCODEC_VERSION sp_avcodec_version;
+static AVFORMAT_VERSION sp_avformat_version; 
+static AVUTIL_VERSION sp_avutil_version;
+// count: 3
+
+
+// libavcodec
+typedef int (APIENTRYP AVCODEC_CLOSE)(AVCodecContext *avctx);
+typedef void (APIENTRYP AVCODEC_STRING)(char *buf, int buf_size, AVCodecContext *enc, int encode);
+typedef AVCodec *(APIENTRYP AVCODEC_FIND_DECODER)(enum CodecID id);
+typedef int (APIENTRYP AVCODEC_OPEN2)(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options);                          // 53.6.0
+typedef int (APIENTRYP AVCODEC_OPEN)(AVCodecContext *avctx, AVCodec *codec);
+typedef AVFrame *(APIENTRYP AVCODEC_ALLOC_FRAME)(void);
+typedef int (APIENTRYP AVCODEC_DEFAULT_GET_BUFFER)(AVCodecContext *s, AVFrame *pic);
+typedef void (APIENTRYP AVCODEC_DEFAULT_RELEASE_BUFFER)(AVCodecContext *s, AVFrame *pic);
+typedef void (APIENTRYP AV_FREE_PACKET)(AVPacket *pkt);
+typedef int (APIENTRYP AVCODEC_DECODE_AUDIO4)(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, AVPacket *avpkt);     // 53.25.0
+typedef int (APIENTRYP AVCODEC_DECODE_AUDIO3)(AVCodecContext *avctx, int16_t *samples, int *frame_size_ptr, AVPacket *avpkt);  // 52.23.0
+typedef int (APIENTRYP AVCODEC_DECODE_VIDEO2)(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt); // 52.23.0
+
+static AVCODEC_CLOSE sp_avcodec_close;
+static AVCODEC_STRING sp_avcodec_string;
+static AVCODEC_FIND_DECODER sp_avcodec_find_decoder;
+static AVCODEC_OPEN2 sp_avcodec_open2;                    // 53.6.0
+static AVCODEC_OPEN sp_avcodec_open;
+static AVCODEC_ALLOC_FRAME sp_avcodec_alloc_frame;
+static AVCODEC_DEFAULT_GET_BUFFER sp_avcodec_default_get_buffer;
+static AVCODEC_DEFAULT_RELEASE_BUFFER sp_avcodec_default_release_buffer;
+static AV_FREE_PACKET sp_av_free_packet;
+static AVCODEC_DECODE_AUDIO4 sp_avcodec_decode_audio4;    // 53.25.0
+static AVCODEC_DECODE_AUDIO3 sp_avcodec_decode_audio3;    // 52.23.0
+static AVCODEC_DECODE_VIDEO2 sp_avcodec_decode_video2;    // 52.23.0
+// count: 15
+
+// libavutil
+typedef void (APIENTRYP AV_FREE)(void *ptr);
+typedef int (APIENTRYP AV_GET_BITS_PER_PIXEL)(const AVPixFmtDescriptor *pixdesc);
+static const AVPixFmtDescriptor* sp_av_pix_fmt_descriptors;
+static AV_FREE sp_av_free;
+static AV_GET_BITS_PER_PIXEL sp_av_get_bits_per_pixel;
+// count: 18
+
+// libavformat
+typedef AVFormatContext *(APIENTRYP AVFORMAT_ALLOC_CONTEXT)(void);
+typedef void (APIENTRYP AVFORMAT_FREE_CONTEXT)(AVFormatContext *s);  // 52.96.0
+typedef void (APIENTRYP AVFORMAT_CLOSE_INPUT)(AVFormatContext **s);  // 53.17.0
+typedef void (APIENTRYP AV_CLOSE_INPUT_FILE)(AVFormatContext *s);
+typedef void (APIENTRYP AV_REGISTER_ALL)(void);
+typedef int (APIENTRYP AVFORMAT_OPEN_INPUT)(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options);
+typedef void (APIENTRYP AV_DUMP_FORMAT)(AVFormatContext *ic, int index, const char *url, int is_output);
+typedef int (APIENTRYP AV_READ_FRAME)(AVFormatContext *s, AVPacket *pkt);
+typedef int (APIENTRYP AV_SEEK_FRAME)(AVFormatContext *s, int stream_index, int64_t timestamp, int flags);
+typedef int (APIENTRYP AVFORMAT_NETWORK_INIT)(void);                                                 // 53.13.0
+typedef int (APIENTRYP AVFORMAT_NETWORK_DEINIT)(void);                                               // 53.13.0
+typedef int (APIENTRYP AVFORMAT_FIND_STREAM_INFO)(AVFormatContext *ic, AVDictionary **options);      // 53.3.0
+typedef int (APIENTRYP AV_FIND_STREAM_INFO)(AVFormatContext *ic);
+
+static AVFORMAT_ALLOC_CONTEXT sp_avformat_alloc_context;
+static AVFORMAT_FREE_CONTEXT sp_avformat_free_context;            // 52.96.0
+static AVFORMAT_CLOSE_INPUT sp_avformat_close_input;              // 53.17.0
+static AV_CLOSE_INPUT_FILE sp_av_close_input_file;
+static AV_REGISTER_ALL sp_av_register_all;
+static AVFORMAT_OPEN_INPUT sp_avformat_open_input;
+static AV_DUMP_FORMAT sp_av_dump_format;
+static AV_READ_FRAME sp_av_read_frame;
+static AV_SEEK_FRAME sp_av_seek_frame;
+static AVFORMAT_NETWORK_INIT sp_avformat_network_init;            // 53.13.0
+static AVFORMAT_NETWORK_DEINIT sp_avformat_network_deinit;        // 53.13.0
+static AVFORMAT_FIND_STREAM_INFO sp_avformat_find_stream_info;    // 53.3.0
+static AV_FIND_STREAM_INFO sp_av_find_stream_info;
+// count: 31
+
+#define SYMBOL_COUNT 31
+
+JNIEXPORT jboolean JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGDynamicLibraryBundleInfo_initSymbols0
+  (JNIEnv *env, jclass clazz, jobject jSymbols, jint count)
+{
+    int64_t* symbols; // jlong -> int64_t -> intptr_t -> FUNC_PTR
+    int i;
+
+    if(SYMBOL_COUNT != count) {
+        fprintf(stderr, "FFMPEGDynamicLibraryBundleInfo.initSymbols0: Wrong symbol count: Expected %d, Is %d\n", 
+                SYMBOL_COUNT, count);
+        return JNI_FALSE;
+    }
+    JoglCommon_init(env);
+
+    i = 0;
+    symbols = (int64_t *) (*env)->GetPrimitiveArrayCritical(env, jSymbols, NULL);
+
+    sp_avcodec_version = (AVCODEC_VERSION) (intptr_t) symbols[i++];
+    sp_avformat_version = (AVFORMAT_VERSION) (intptr_t) symbols[i++];
+    sp_avutil_version = (AVUTIL_VERSION) (intptr_t) symbols[i++];
+    // count:  3
+
+    sp_avcodec_close = (AVCODEC_CLOSE)  (intptr_t) symbols[i++];
+    sp_avcodec_string = (AVCODEC_STRING) (intptr_t) symbols[i++];
+    sp_avcodec_find_decoder = (AVCODEC_FIND_DECODER) (intptr_t) symbols[i++];
+    sp_avcodec_open2 = (AVCODEC_OPEN2) (intptr_t) symbols[i++];
+    sp_avcodec_open  = (AVCODEC_OPEN) (intptr_t) symbols[i++];
+    sp_avcodec_alloc_frame = (AVCODEC_ALLOC_FRAME) (intptr_t) symbols[i++];
+    sp_avcodec_default_get_buffer = (AVCODEC_DEFAULT_GET_BUFFER) (intptr_t) symbols[i++];
+    sp_avcodec_default_release_buffer = (AVCODEC_DEFAULT_RELEASE_BUFFER) (intptr_t) symbols[i++];
+    sp_av_free_packet = (AV_FREE_PACKET) (intptr_t) symbols[i++];
+    sp_avcodec_decode_audio4 = (AVCODEC_DECODE_AUDIO4) (intptr_t) symbols[i++];
+    sp_avcodec_decode_audio3 = (AVCODEC_DECODE_AUDIO3) (intptr_t) symbols[i++];
+    sp_avcodec_decode_video2 = (AVCODEC_DECODE_VIDEO2) (intptr_t) symbols[i++];
+    // count: 15
+
+    sp_av_pix_fmt_descriptors = (const AVPixFmtDescriptor*)  (intptr_t) symbols[i++];
+    sp_av_free = (AV_FREE) (intptr_t) symbols[i++];
+    sp_av_get_bits_per_pixel = (AV_GET_BITS_PER_PIXEL) (intptr_t) symbols[i++];
+    // count: 18
+
+    sp_avformat_alloc_context = (AVFORMAT_ALLOC_CONTEXT) (intptr_t) symbols[i++];;
+    sp_avformat_free_context = (AVFORMAT_FREE_CONTEXT) (intptr_t) symbols[i++];
+    sp_avformat_close_input = (AVFORMAT_CLOSE_INPUT) (intptr_t) symbols[i++];
+    sp_av_close_input_file = (AV_CLOSE_INPUT_FILE) (intptr_t) symbols[i++];
+    sp_av_register_all = (AV_REGISTER_ALL) (intptr_t) symbols[i++];
+    sp_avformat_open_input = (AVFORMAT_OPEN_INPUT) (intptr_t) symbols[i++];
+    sp_av_dump_format = (AV_DUMP_FORMAT) (intptr_t) symbols[i++];
+    sp_av_read_frame = (AV_READ_FRAME) (intptr_t) symbols[i++];
+    sp_av_seek_frame = (AV_SEEK_FRAME) (intptr_t) symbols[i++];
+    sp_avformat_network_init = (AVFORMAT_NETWORK_INIT) (intptr_t) symbols[i++];
+    sp_avformat_network_deinit = (AVFORMAT_NETWORK_DEINIT) (intptr_t) symbols[i++];
+    sp_avformat_find_stream_info = (AVFORMAT_FIND_STREAM_INFO) (intptr_t) symbols[i++];
+    sp_av_find_stream_info = (AV_FIND_STREAM_INFO) (intptr_t) symbols[i++];
+    // count: 31
+
+    (*env)->ReleasePrimitiveArrayCritical(env, jSymbols, symbols, 0);
+
+    if(SYMBOL_COUNT != i) {
+        // boom
+        fprintf(stderr, "FFMPEGDynamicLibraryBundleInfo.initSymbols0: Wrong symbol assignment count: Expected %d, Is %d\n", 
+                SYMBOL_COUNT, i);
+        return JNI_FALSE;
+    }
+
+    return JNI_TRUE;
+}
+
+static void _updateJavaAttributes(JNIEnv *env, jobject instance, FFMPEGToolBasicAV_t* pAV)
+{
+    // int shallBeDetached = 0;
+    // JNIEnv  * env = JoglCommon_GetJNIEnv (&shallBeDetached); 
+    if(NULL!=env) {
+        int32_t w, h;
+        if( NULL != pAV->pVCodecCtx ) {
+            // FIXME: Libav Binary compatibility! JAU01
+            w = pAV->pVCodecCtx->width; h = pAV->pVCodecCtx->height;
+        } else {
+            w = 0;                      h = 0;
+        }
+
+        (*env)->CallVoidMethod(env, instance, jni_mid_updateAttributes1,
+                               w, h, 
+                               pAV->bps_stream, pAV->bps_video, pAV->bps_audio,
+                               pAV->fps, (int32_t)((pAV->duration/1000)*pAV->fps), pAV->duration,
+                               (*env)->NewStringUTF(env, pAV->vcodec),
+                               (*env)->NewStringUTF(env, pAV->acodec) );
+        (*env)->CallVoidMethod(env, instance, jni_mid_updateAttributes2,
+                               pAV->vPixFmt, pAV->vBufferPlanes, 
+                               pAV->vBitsPerPixel, pAV->vBytesPerPixelPerPlane,
+                               pAV->vLinesize[0], pAV->vLinesize[1], pAV->vLinesize[2],
+                               pAV->vTexWidth[0], pAV->vTexWidth[1], pAV->vTexWidth[2]);
+        // JoglCommon_ReleaseJNIEnv (shallBeDetached);
+    }
+}
+
+static void freeInstance(FFMPEGToolBasicAV_t* pAV) {
+    int i;
+    if(NULL != pAV) {
+        // Close the V codec
+        if(NULL != pAV->pVCodecCtx) {
+            sp_avcodec_close(pAV->pVCodecCtx);
+            pAV->pVCodecCtx = NULL;
+        }
+        pAV->pVCodec=NULL;
+
+        // Close the A codec
+        if(NULL != pAV->pACodecCtx) {
+            sp_avcodec_close(pAV->pACodecCtx);
+            pAV->pACodecCtx = NULL;
+        }
+        pAV->pACodec=NULL;
+
+        // Close the frames
+        if(NULL != pAV->pVFrame) {
+            sp_av_free(pAV->pVFrame);
+            pAV->pVFrame = NULL;
+        }
+        if(NULL != pAV->pAFrame) {
+            sp_av_free(pAV->pAFrame);
+            pAV->pAFrame = NULL;
+        }
+
+        // Close the video file
+        if(NULL != pAV->pFormatCtx) {
+            if(HAS_FUNC(sp_avformat_close_input)) {
+                sp_avformat_close_input(&pAV->pFormatCtx);
+            } else {
+                sp_av_close_input_file(pAV->pFormatCtx);
+                if(HAS_FUNC(sp_avformat_free_context)) {
+                    sp_avformat_free_context(pAV->pFormatCtx);
+                }
+            }
+            pAV->pFormatCtx = NULL;
+        }
+        free(pAV);
+    }
+}
+
+static int my_getPlaneCount(AVPixFmtDescriptor *pDesc) {
+    int i, p=-1;
+    for(i=pDesc->nb_components-1; i>=0; i--) {
+        int p0 = pDesc->comp[i].plane;
+        if( p < p0 ) {
+            p = p0;
+        }
+    }
+    return p+1;
+}
+
+static int my_is_hwaccel_pix_fmt(enum PixelFormat pix_fmt) {
+    return sp_av_pix_fmt_descriptors[pix_fmt].flags & PIX_FMT_HWACCEL;
+}
+
+#if 0
+static enum PixelFormat my_get_format(struct AVCodecContext *s, const enum PixelFormat * fmt) {
+    int i=0;
+    enum PixelFormat f0, fR = PIX_FMT_NONE;
+    char buf[256];
+
+    fprintf(stderr, "get_format ****\n");
+    while (fmt[i] != PIX_FMT_NONE /* && ff_is_hwaccel_pix_fmt(fmt[i]) */) {
+        f0 = fmt[i];
+        if(fR==PIX_FMT_NONE && !my_is_hwaccel_pix_fmt(f0)) {
+            fR = f0;
+        }
+        sp_av_get_pix_fmt_string(buf, sizeof(buf), f0);
+        fprintf(stderr, "get_format %d: %d - %s - %s\n", i, f0, sp_av_get_pix_fmt_name(f0), buf);
+        ++i;
+    }
+    fprintf(stderr, "get_format %d - %s *** \n", fR, sp_av_get_pix_fmt_name(fR));
+    fflush(NULL);
+    return fR;
+}
+#endif
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_getAvUtilVersion0
+  (JNIEnv *env, jclass clazz) {
+    return (jint) sp_avutil_version();
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_getAvFormatVersion0
+  (JNIEnv *env, jclass clazz) {
+    return (jint) sp_avformat_version();
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_getAvCodecVersion0
+  (JNIEnv *env, jclass clazz) {
+    return (jint) sp_avcodec_version();
+}
+
+JNIEXPORT jboolean JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_initIDs0
+  (JNIEnv *env, jclass clazz)
+{
+    JoglCommon_init(env);
+
+    jclass c;
+    if (ffmpegMediaPlayerClazz != NULL) {
+        return;
+    }
+
+    c = (*env)->FindClass(env, ClazzNameFFMPEGMediaPlayer);
+    if(NULL==c) {
+        JoglCommon_FatalError(env, "JOGL FFMPEG: can't find %s", ClazzNameFFMPEGMediaPlayer);
+    }
+    ffmpegMediaPlayerClazz = (jclass)(*env)->NewGlobalRef(env, c);
+    (*env)->DeleteLocalRef(env, c);
+    if(NULL==ffmpegMediaPlayerClazz) {
+        JoglCommon_FatalError(env, "JOGL FFMPEG: can't use %s", ClazzNameFFMPEGMediaPlayer);
+    }
+
+    jni_mid_updateAttributes1 = (*env)->GetMethodID(env, ffmpegMediaPlayerClazz, "updateAttributes", "(IIIIIFIILjava/lang/String;Ljava/lang/String;)V");
+    jni_mid_updateAttributes2 = (*env)->GetMethodID(env, ffmpegMediaPlayerClazz, "updateAttributes2", "(IIIIIIIIII)V");
+
+    if(jni_mid_updateAttributes1 == NULL ||
+       jni_mid_updateAttributes2 == NULL) {
+        return JNI_FALSE;
+    }
+    return JNI_TRUE;
+}
+
+JNIEXPORT jlong JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_createInstance0
+  (JNIEnv *env, jobject instance, jboolean verbose)
+{
+    FFMPEGToolBasicAV_t * pAV = calloc(1, sizeof(FFMPEGToolBasicAV_t));
+    if(NULL==pAV) {
+        JoglCommon_throwNewRuntimeException(env, "Couldn't alloc instance");
+        return 0;
+    }
+    // Register all formats and codecs
+    sp_av_register_all();
+    // Network too ..
+    if(HAS_FUNC(sp_avformat_network_init)) {
+        sp_avformat_network_init();
+    }
+
+    pAV->verbose = verbose;
+    pAV->vid=-1;
+    pAV->aid=-1;
+
+    return (jlong) (intptr_t) pAV;
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_destroyInstance0
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr));
+  if (pAV != NULL) {
+      // stop assumed ..
+      freeInstance(pAV);
+  }
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_setStream0
+  (JNIEnv *env, jobject instance, jlong ptr, jstring jURL, jint vid, jint aid)
+{
+    int res, i;
+    jboolean iscopy;
+    FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)(intptr_t)ptr;
+
+    if (pAV == NULL) {
+        JoglCommon_throwNewRuntimeException(env, "NULL AV ptr");
+        return;
+    }
+
+    pAV->pFormatCtx = sp_avformat_alloc_context();
+
+    // Open video file
+    const char *urlPath = (*env)->GetStringUTFChars(env, jURL, &iscopy);
+    res = sp_avformat_open_input(&pAV->pFormatCtx, urlPath, NULL, NULL);
+    if(res != 0) {
+        (*env)->ReleaseStringChars(env, jURL, (const jchar *)urlPath);
+        JoglCommon_throwNewRuntimeException(env, "Couldn't open URL");
+        return;
+    }
+
+    // Retrieve detailed stream information
+    if(HAS_FUNC(sp_avformat_find_stream_info)) {
+        if(sp_avformat_find_stream_info(pAV->pFormatCtx, NULL)<0) {
+            (*env)->ReleaseStringChars(env, jURL, (const jchar *)urlPath);
+            JoglCommon_throwNewRuntimeException(env, "Couldn't find stream information");
+            return;
+        }
+    } else {
+        if(sp_av_find_stream_info(pAV->pFormatCtx)<0) {
+            (*env)->ReleaseStringChars(env, jURL, (const jchar *)urlPath);
+            JoglCommon_throwNewRuntimeException(env, "Couldn't find stream information");
+            return;
+        }
+    }
+
+    if(pAV->verbose) {
+        // Dump information about file onto standard error
+        sp_av_dump_format(pAV->pFormatCtx, 0, urlPath, JNI_FALSE);
+    }
+    (*env)->ReleaseStringChars(env, jURL, (const jchar *)urlPath);
+    // FIXME: Libav Binary compatibility! JAU01
+    if (pAV->pFormatCtx->duration != AV_NOPTS_VALUE) {
+        pAV->duration = pAV->pFormatCtx->duration / AV_TIME_BASE_MSEC;
+    }
+    if (pAV->pFormatCtx->start_time != AV_NOPTS_VALUE) {
+        pAV->start_time = pAV->pFormatCtx->start_time / AV_TIME_BASE_MSEC;
+    }
+    if (pAV->pFormatCtx->bit_rate) {
+        pAV->bps_stream = pAV->pFormatCtx->bit_rate;
+    }
+
+    fprintf(stderr, "Streams: %d\n", pAV->pFormatCtx->nb_streams); // JAU
+
+    // Find the first audio and video stream, or the one matching vid
+    // FIXME: Libav Binary compatibility! JAU01
+    for(i=0; ( -1==pAV->aid || -1==pAV->vid ) && i<pAV->pFormatCtx->nb_streams; i++) {
+        AVStream *st = pAV->pFormatCtx->streams[i];
+        fprintf(stderr, "Stream: %d: is-video %d, is-audio %d\n", i, (AVMEDIA_TYPE_VIDEO == st->codec->codec_type), AVMEDIA_TYPE_AUDIO == st->codec->codec_type); // JAU
+        if(AVMEDIA_TYPE_VIDEO == st->codec->codec_type) {
+            if(-1==pAV->vid && (-1==vid || vid == i) ) {
+                pAV->pVStream = st;
+                pAV->vid=i;
+            }
+        } else if(AVMEDIA_TYPE_AUDIO == st->codec->codec_type) {
+            if(-1==pAV->aid && (-1==aid || aid == i) ) {
+                pAV->pAStream = st;
+                pAV->aid=i;
+            }
+        }
+    }
+
+    fprintf(stderr, "Found vid %d, aid %d\n", pAV->vid, pAV->aid); // JAU
+
+    if(0<=pAV->aid) {
+        // Get a pointer to the codec context for the audio stream
+        // FIXME: Libav Binary compatibility! JAU01
+        pAV->pACodecCtx=pAV->pAStream->codec;
+
+        // FIXME: Libav Binary compatibility! JAU01
+        if (pAV->pACodecCtx->bit_rate) {
+            pAV->bps_audio = pAV->pACodecCtx->bit_rate;
+        }
+        sp_avcodec_string(pAV->acodec, sizeof(pAV->acodec), pAV->pACodecCtx, 0);
+
+        // Find the decoder for the audio stream
+        pAV->pACodec=sp_avcodec_find_decoder(pAV->pACodecCtx->codec_id);
+        if(pAV->pACodec==NULL) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't find audio codec %d, %s", pAV->pACodecCtx->codec_id, pAV->acodec);
+            return;
+        }
+
+        // Open codec
+        if(HAS_FUNC(sp_avcodec_open2)) {
+            res = sp_avcodec_open2(pAV->pACodecCtx, pAV->pACodec, NULL);
+        } else {
+            res = sp_avcodec_open(pAV->pACodecCtx, pAV->pACodec);
+        }
+        if(res<0) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't open audio codec %d, %s", pAV->pACodecCtx->codec_id, pAV->acodec);
+            return;
+        }
+
+        // Allocate audio frames
+        // FIXME: Libav Binary compatibility! JAU01
+        pAV->aSampleRate = pAV->pACodecCtx->sample_rate;
+        pAV->aChannels = pAV->pACodecCtx->channels;
+        pAV->aFrameSize = pAV->pACodecCtx->frame_size;
+        pAV->aSampleFmt = pAV->pACodecCtx->sample_fmt;
+        pAV->pAFrame=sp_avcodec_alloc_frame();
+        if(pAV->pAFrame==NULL) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't alloc audio frame");
+            return;
+        }
+    }
+
+    if(0<=pAV->vid) {
+        // Get a pointer to the codec context for the video stream
+        // FIXME: Libav Binary compatibility! JAU01
+        pAV->pVCodecCtx=pAV->pVStream->codec;
+        #if 0
+        pAV->pVCodecCtx->get_format = my_get_format;
+        #endif
+
+        if (pAV->pVCodecCtx->bit_rate) {
+            // FIXME: Libav Binary compatibility! JAU01
+            pAV->bps_video = pAV->pVCodecCtx->bit_rate;
+        }
+        sp_avcodec_string(pAV->vcodec, sizeof(pAV->vcodec), pAV->pVCodecCtx, 0);
+
+        // Find the decoder for the video stream
+        pAV->pVCodec=sp_avcodec_find_decoder(pAV->pVCodecCtx->codec_id);
+        if(pAV->pVCodec==NULL) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't find video codec %d, %s", pAV->pVCodecCtx->codec_id, pAV->vcodec);
+            return;
+        }
+
+        // Open codec
+        if(HAS_FUNC(sp_avcodec_open2)) {
+            res = sp_avcodec_open2(pAV->pVCodecCtx, pAV->pVCodec, NULL);
+        } else {
+            res = sp_avcodec_open(pAV->pVCodecCtx, pAV->pVCodec);
+        }
+        if(res<0) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't open video codec %d, %s", pAV->pVCodecCtx->codec_id, pAV->vcodec);
+            return;
+        }
+
+        // Hack to correct wrong frame rates that seem to be generated by some codecs
+        // FIXME: Libav Binary compatibility! JAU01
+        if(pAV->pVCodecCtx->time_base.num>1000 && pAV->pVCodecCtx->time_base.den==1) {
+            pAV->pVCodecCtx->time_base.den=1000;
+        }
+        // FIXME: Libav Binary compatibility! JAU01
+        pAV->fps = my_av_q2f(pAV->pVStream->avg_frame_rate);
+            
+        // Allocate video frames
+        // FIXME: Libav Binary compatibility! JAU01
+        pAV->vPixFmt = pAV->pVCodecCtx->pix_fmt;
+        {   
+            AVPixFmtDescriptor pixDesc = sp_av_pix_fmt_descriptors[pAV->vPixFmt];
+            pAV->vBitsPerPixel = sp_av_get_bits_per_pixel(&pixDesc);
+            pAV->vBufferPlanes = my_getPlaneCount(&pixDesc);
+        }
+        pAV->pVFrame=sp_avcodec_alloc_frame();
+        if( pAV->pVFrame == NULL ) {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't alloc video frame");
+            return;
+        }
+        res = sp_avcodec_default_get_buffer(pAV->pVCodecCtx, pAV->pVFrame);
+        if(0==res) {
+            const int32_t bytesPerPixel = ( pAV->vBitsPerPixel + 7 ) / 8 ;
+            if(1 == pAV->vBufferPlanes) {
+                pAV->vBytesPerPixelPerPlane = bytesPerPixel;
+            } else {
+                pAV->vBytesPerPixelPerPlane = 1;
+            }
+            for(i=0; i<3; i++) {
+                // FIXME: Libav Binary compatibility! JAU01
+                pAV->vLinesize[i] = pAV->pVFrame->linesize[i];
+                pAV->vTexWidth[i] = pAV->vLinesize[i] / pAV->vBytesPerPixelPerPlane ;
+            }
+            sp_avcodec_default_release_buffer(pAV->pVCodecCtx, pAV->pVFrame);
+        } else {
+            JoglCommon_throwNewRuntimeException(env, "Couldn't peek video buffer dimension");
+            return;
+        }
+    }
+    pAV->vPTS=0;
+    pAV->aPTS=0;
+    _updateJavaAttributes(env, instance, pAV);
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_readNextPacket0
+  (JNIEnv *env, jobject instance, jlong ptr, jlong jProcAddrGLTexSubImage2D, jint texTarget, jint texFmt, jint texType)
+{
+    FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr));
+    PFNGLTEXSUBIMAGE2DPROC procAddrGLTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC) jProcAddrGLTexSubImage2D;
+
+    jint res = 0; // 1 - audio, 2 - video
+    AVPacket packet;
+    int frameFinished;
+
+    if(sp_av_read_frame(pAV->pFormatCtx, &packet)>=0) {
+        /**
+        if(packet.stream_index==pAV->aid) {
+            // Decode audio frame
+            if(NULL == pAV->pAFrame) {
+                sp_av_free_packet(&packet);
+                return res;
+            }
+
+            int new_packet = 1;
+            int len1;
+            int flush_complete = 0;
+            int data_size = 0;
+            while (packet.size > 0 || (!packet.data && new_packet)) {
+                new_packet = 0;
+                if (flush_complete) {
+                    break;
+                }
+                if(HAS_FUNC(sp_avcodec_decode_audio4)) {
+                    len1 = sp_avcodec_decode_audio4(pAV->pVCodecCtx, pAV->pAFrame, &frameFinished, &packet);
+                } else {
+                    len1 = sp_avcodec_decode_audio3(pAV->pVCodecCtx, int16_t *samples, int *frame_size_ptr, &frameFinished, &packet);
+                }
+                if (len1 < 0) {
+                    // if error, we skip the frame 
+                    packet.size = 0;
+                    break;
+                }
+                packet.data += len1;
+                packet.size -= len1;
+
+                if (!frameFinished) {
+                    // stop sending empty packets if the decoder is finished 
+                    if (!packet.data && pAV->pVCodecCtx->codec->capabilities & CODEC_CAP_DELAY) {
+                        flush_complete = 1;
+                    }
+                    continue;
+                }
+
+                int32_t pts = pAV->pAFrame->pkt_pts * my_av_q2i32(1000, pAV->pAStream->time_base);
+                pAV->aPTS += ( data_size * 1000 ) / (2 * pAV->pVCodecCtx->channels * pAV->pVCodecCtx->sample_rate);
+                printf("A pts %d - %d\n", pts, pAV->aPTS);
+                res = 1;
+            }
+        } else */ if(packet.stream_index==pAV->vid) {
+            // Decode video frame
+            if(NULL == pAV->pVFrame) {
+                sp_av_free_packet(&packet);
+                return res;
+            }
+            sp_avcodec_decode_video2(pAV->pVCodecCtx, pAV->pVFrame, &frameFinished, &packet);
+
+            // Did we get a video frame?
+            if(frameFinished)
+            {
+                res = 2;
+                // FIXME: Libav Binary compatibility! JAU01
+                const AVRational time_base = pAV->pVStream->time_base;
+                const int64_t pts = pAV->pVFrame->pkt_pts;
+                if(AV_NOPTS_VALUE != pts) { // discard invalid PTS ..
+                    pAV->vPTS = pts * my_av_q2i32(1000, time_base);
+
+                    #if 0
+                    printf("PTS %d = %ld * ( ( 1000 * %ld ) / %ld ) '1000 * time_base', time_base = %lf\n",
+                        pAV->vPTS, pAV->pVFrame->pkt_pts, time_base.num, time_base.den, (time_base.num/(double)time_base.den));
+                    #endif
+                }
+
+                #if 0
+                printf("tex2D codec %dx%d - frame %dx%d - width %d tex / %d linesize, pixfmt 0x%X, texType 0x%x, texTarget 0x%x\n", 
+                         pAV->pVCodecCtx->width, pAV->pVCodecCtx->height, 
+                         pAV->pVFrame->width, pAV->pVFrame->height, pAV->vTexWidth[0], pAV->pVFrame->linesize[0],
+                         texFmt, texType, texTarget);
+                #endif
+
+                // 1st plane or complete packed frame
+                // FIXME: Libav Binary compatibility! JAU01
+                procAddrGLTexSubImage2D(texTarget, 0, 
+                                        0,                 0, 
+                                        pAV->vTexWidth[0], pAV->pVCodecCtx->height, 
+                                        texFmt, texType, pAV->pVFrame->data[0]);
+
+                if(pAV->vPixFmt == PIX_FMT_YUV420P) {
+                    // U plane
+                    // FIXME: Libav Binary compatibility! JAU01
+                    procAddrGLTexSubImage2D(texTarget, 0, 
+                                            pAV->pVCodecCtx->width, 0,
+                                            pAV->vTexWidth[1],      pAV->pVCodecCtx->height/2, 
+                                            texFmt, texType, pAV->pVFrame->data[1]);
+                    // V plane
+                    // FIXME: Libav Binary compatibility! JAU01
+                    procAddrGLTexSubImage2D(texTarget, 0, 
+                                            pAV->pVCodecCtx->width, pAV->pVCodecCtx->height/2,
+                                            pAV->vTexWidth[2],      pAV->pVCodecCtx->height/2, 
+                                            texFmt, texType, pAV->pVFrame->data[2]);
+                } // FIXME: Add more planar formats !
+            }
+        }
+
+        // Free the packet that was allocated by av_read_frame
+        sp_av_free_packet(&packet);
+    }
+    return res;
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_seek0
+  (JNIEnv *env, jobject instance, jlong ptr, jint pos1)
+{
+    FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr));
+    int64_t pos0 = pAV->vPTS;
+    int64_t pts0 = pAV->pVFrame->pkt_pts;
+    int64_t pts1 = (int64_t) pos1 / my_av_q2i32(1000, pAV->pVStream->time_base);
+    int flags = 0;
+    if(pos1 < pos0) {
+        flags |= AVSEEK_FLAG_BACKWARD;
+    }
+    fprintf(stderr, "SEEK: pre  : u %d, p %d -> u %d, p %d\n", pos0, pts0, pos1, pts1);
+    sp_av_seek_frame(pAV->pFormatCtx, pAV->vid, pts1, flags);
+    pAV->vPTS = pAV->pVFrame->pkt_pts * my_av_q2i32(1000, pAV->pVStream->time_base);
+    fprintf(stderr, "SEEK: post : u %d, p %d\n", pAV->vPTS, pAV->pVFrame->pkt_pts);
+    return pAV->vPTS;
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_getVideoPTS0
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+    FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr));
+    return pAV->vPTS;
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_FFMPEGMediaPlayer_getAudioPTS0
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+    FFMPEGToolBasicAV_t *pAV = (FFMPEGToolBasicAV_t *)((void *)((intptr_t)ptr));
+    return pAV->aPTS;
+}
+
diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m
index fe896cc..66bd10f 100644
--- a/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m
+++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface-pbuffer.m
@@ -33,6 +33,8 @@
     int texHeight;
     GLuint textureID;
     GLint swapInterval;
+    GLint swapIntervalCounter;
+    struct timespec lastWaitTime;
 #ifdef HAS_CADisplayLink
     CADisplayLink* displayLink;
 #else
@@ -78,8 +80,14 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
     #ifdef DBG_PERF
         [l tick];
     #endif
-    pthread_cond_signal(&l->renderSignal);
-    SYNC_PRINT("-*-");
+    if(0 < l->swapInterval) {
+        l->swapIntervalCounter++;
+        if(l->swapIntervalCounter>=l->swapInterval) {
+            l->swapIntervalCounter = 0;
+            pthread_cond_signal(&l->renderSignal);
+            SYNC_PRINT("S");
+        }
+    }
     pthread_mutex_unlock(&l->renderLock);
     [pool release];
     return kCVReturnSuccess;
@@ -102,14 +110,25 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
     pthread_mutex_init(&renderLock, &renderLockAttr); // recursive
     pthread_cond_init(&renderSignal, NULL); // no attribute
 
-    // no animations for add/remove/swap sublayers etc 
-    [self removeAnimationForKey: kCAOnOrderIn];
-    [self removeAnimationForKey: kCAOnOrderOut];
-    [self removeAnimationForKey: kCATransition];
-
+    textureID = 0;
+    swapInterval = 1; // defaults to on (as w/ new GL profiles)
+    swapIntervalCounter = 0;
+    timespec_now(&lastWaitTime);
+    shallDraw = NO;
+    texWidth = _texWidth;
+    texHeight = _texHeight;
     pbuffer = p;
     [pbuffer retain];
 
+    {
+        CGRect lRect = CGRectMake(0, 0, texWidth, texHeight);
+        [self setFrame:lRect];
+
+        // no animations for add/remove/swap sublayers etc 
+        // doesn't work: [self removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition]
+        [self removeAllAnimations];
+    }
+
     // instantiate a deactivated displayLink
 #ifdef HAS_CADisplayLink
     displayLink = [[CVDisplayLink displayLinkWithTarget:self selector:@selector(setNeedsDisplay)] retain];
@@ -153,15 +172,10 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
     [self setAsynchronous: YES];
 
     [self setNeedsDisplayOnBoundsChange: YES]; // FIXME: learn how to recreate on size change!
+
     [self setOpaque: opaque ? YES : NO];
-    texWidth = _texWidth;
-    texHeight = _texHeight;
-    textureID = 0;
-    swapInterval = -1;
-    shallDraw = NO;
 
     CGRect lRect = [self frame];
-
     DBG_PRINT("MyNSOpenGLLayer::init %p, ctx %p, pfmt %p, pbuffer %p, opaque %d, pbuffer %dx%d -> tex %dx%d, frame: %lf/%lf %lfx%lf (refcnt %d)\n", 
         self, _ctx, _fmt, pbuffer, opaque, [pbuffer pixelsWide], [pbuffer pixelsHigh], texWidth, texHeight,
         lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height, (int)[self retainCount]);
@@ -240,10 +254,10 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
     pthread_mutex_lock(&renderLock);
     Bool res = NULL != pbuffer && YES == shallDraw;
     if(!res) {
-        SYNC_PRINT("<0>");
+        SYNC_PRINT("0");
         pthread_mutex_unlock(&renderLock);
     } else {
-        SYNC_PRINT("<");
+        SYNC_PRINT("1");
     }
     return res;
 }
@@ -332,10 +346,10 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
     [super drawInOpenGLContext: context pixelFormat: pixelFormat forLayerTime: timeInterval displayTime: timeStamp];
     shallDraw = NO;
     if(0 >= swapInterval) {
-        pthread_cond_signal(&renderSignal);
-        SYNC_PRINT("*");
+        pthread_cond_signal(&renderSignal); // just to wake up
+        SYNC_PRINT("s");
     }
-    SYNC_PRINT("1>");
+    SYNC_PRINT("$");
     pthread_mutex_unlock(&renderLock);
 }
 
@@ -348,6 +362,7 @@ static CVReturn renderMyNSOpenGLLayer(CVDisplayLinkRef displayLink,
 {
     DBG_PRINT("MyNSOpenGLLayer::setSwapInterval: %d\n", interval);
     swapInterval = interval;
+    swapIntervalCounter = 0;
     if(0 < swapInterval) {
         tc = 0;
         timespec_now(&t0);
@@ -405,7 +420,7 @@ void setNSOpenGLLayerSwapInterval(NSOpenGLLayer* layer, int interval) {
   pthread_mutex_unlock(&l->renderLock);
 }
 
-void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_ms) {
+void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_micros) {
     MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer;
     BOOL ready = NO;
     int wr = 0;
@@ -416,17 +431,23 @@ void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_ms) {
             ready = !l->shallDraw;
         }
         if(NO == ready) {
-            if(0 < to_ms) {
-                struct timespec to_abs;
-                timespec_now(&to_abs);
-                timespec_addms(&to_abs, to_ms);
+            if(0 < to_micros) {
+                #ifdef DBG_SYNC
+                    struct timespec t0, t1, td, td2;
+                    timespec_now(&t0);
+                #endif
+                struct timespec to_abs = l->lastWaitTime;
+                timespec_addmicros(&to_abs, to_micros);
+                #ifdef DBG_SYNC
+                    timespec_subtract(&td, &to_abs, &t0);
+                    fprintf(stderr, "(%ld) / ", timespec_milliseconds(&td));
+                #endif
                 wr = pthread_cond_timedwait(&l->renderSignal, &l->renderLock, &to_abs);
                 #ifdef DBG_SYNC
-                    struct timespec t1, td;
                     timespec_now(&t1);
-                    timespec_subtract(&td, &t1, &to_abs);
-                    long td_ms = timespec_milliseconds(&td);
-                    fprintf(stderr, "%ld ms", td_ms);
+                    timespec_subtract(&td, &t1, &t0);
+                    timespec_subtract(&td2, &t1, &l->lastWaitTime);
+                    fprintf(stderr, "(%ld) / (%ld) ms", timespec_milliseconds(&td), timespec_milliseconds(&td2));
                 #endif
             } else {
                 pthread_cond_wait (&l->renderSignal, &l->renderLock);
@@ -435,32 +456,25 @@ void waitUntilNSOpenGLLayerIsReady(NSOpenGLLayer* layer, long to_ms) {
         }
     } while (NO == ready && 0 == wr) ;
     SYNC_PRINT("-%d}", ready);
+    timespec_now(&l->lastWaitTime);
     pthread_mutex_unlock(&l->renderLock);
 }
 
 void setNSOpenGLLayerNeedsDisplay(NSOpenGLLayer* layer) {
-  MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer;
-  @synchronized(l) {
-      NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
-      pthread_mutex_lock(&l->renderLock);
-      SYNC_PRINT("[");
-      l->shallDraw = YES;
-      if([l getSwapInterval] > 0) {
-          // only trigger update if async mode is off (swapInterval>0)
-          if ( [NSThread isMainThread] == YES ) {
-              [l setNeedsDisplay];
-          } else {
-              // can't wait, otherwise we may deadlock AWT
-              [l performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO];
-          }
-          SYNC_PRINT("1]");
-      } else {
-          SYNC_PRINT("0]");
-      }
-      pthread_mutex_unlock(&l->renderLock);
-      // DBG_PRINT("MyNSOpenGLLayer::setNSOpenGLLayerNeedsDisplay %p\n", l);
-      [pool release];
-  }
+    MyNSOpenGLLayer* l = (MyNSOpenGLLayer*) layer;
+    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+    pthread_mutex_lock(&l->renderLock);
+    l->shallDraw = YES;
+    if ( [NSThread isMainThread] == YES ) {
+      [l setNeedsDisplay];
+    } else {
+      // can't wait, otherwise we may deadlock AWT
+      [l performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO];
+    }
+    SYNC_PRINT(".");
+    pthread_mutex_unlock(&l->renderLock);
+    // DBG_PRINT("MyNSOpenGLLayer::setNSOpenGLLayerNeedsDisplay %p\n", l);
+    [pool release];
 }
 
 void releaseNSOpenGLLayer(NSOpenGLLayer* layer) {
diff --git a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m
index b5979d5..8ac9f47 100644
--- a/src/jogl/native/macosx/MacOSXWindowSystemInterface.m
+++ b/src/jogl/native/macosx/MacOSXWindowSystemInterface.m
@@ -376,20 +376,20 @@ NSOpenGLPixelFormat* createPixelFormat(int* iattrs, int niattrs, int* ivalues) {
   // http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSOpenGLPixelFormat.html
   NSOpenGLPixelFormatAttribute attribs[256];
 
+  DBG_PRINT("createPixelFormat.0: attrs %d: ", niattrs);
   int idx = 0;
   int i;
   for (i = 0; i < niattrs && iattrs[i]>0; i++) {
     int attr = iattrs[i];
+    DBG_PRINT("%d: %d, ", attr, ivalues[i]);
     switch (attr) {
-      case NSOpenGLPFANoRecovery:
-        if (ivalues[i] != 0) {
-          attribs[idx++] = NSOpenGLPFANoRecovery;
-        }
+      case NSOpenGLPFAAccelerated:
+        // ignored - allow non accelerated profiles, or see NSOpenGLPFANoRecovery
         break;
 
-      case NSOpenGLPFAAccelerated:
+      case NSOpenGLPFANoRecovery:
         if (ivalues[i] != 0) {
-          attribs[idx++] = NSOpenGLPFAAccelerated;
+          attribs[idx++] = NSOpenGLPFANoRecovery;
         }
         break;
 
@@ -445,10 +445,8 @@ NSOpenGLPixelFormat* createPixelFormat(int* iattrs, int niattrs, int* ivalues) {
   attribs[idx++] = 0;
 
   NSOpenGLPixelFormat* fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
-  if (fmt == nil) {
-    // should we fallback to defaults or not?
-    fmt = [NSOpenGLView defaultPixelFormat];
-  }
+  // if(fmt == nil) { fallback to a [NSOpenGLView defaultPixelFormat] crashed (SIGSEGV) on 10.6.7/NV }
+  DBG_PRINT("createPixelFormat.X: pfmt %p\n", fmt);
 
   [pool release];
   return fmt;
@@ -510,16 +508,19 @@ NSOpenGLContext* createContext(NSOpenGLContext* share,
                     Bool opaque,
                     int* viewNotReady)
 {
+    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+
     getRendererInfo();
     
-    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+    DBG_PRINT("createContext.0: share %p, view %p, isBackingLayer %d, pixfmt %p, opaque %d\n",
+        share, view, (int)isBackingLayerView, fmt, opaque);
 
     if (view != NULL) {
         Bool viewReady = true;
 
         if(!isBackingLayerView) {
             if ([view lockFocusIfCanDraw] == NO) {
-                DBG_PRINT("createContext [view lockFocusIfCanDraw] failed\n");
+                DBG_PRINT("createContext.1 [view lockFocusIfCanDraw] failed\n");
                 viewReady = false;
             }
         }
@@ -529,7 +530,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share,
                 if(!isBackingLayerView) {
                     [view unlockFocus];
                 }
-                DBG_PRINT("createContext view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height);
+                DBG_PRINT("createContext.2 view.frame size %dx%d\n", (int)frame.size.width, (int)frame.size.height);
                 viewReady = false;
             }
         }
@@ -542,6 +543,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share,
             }
 
             // the view is not ready yet
+            DBG_PRINT("createContext.X: view not ready yet\n");
             [pool release];
             return NULL;
         }
@@ -562,6 +564,7 @@ NSOpenGLContext* createContext(NSOpenGLContext* share,
       }
     }
 
+    DBG_PRINT("createContext.X: ctx: %p\n", ctx);
     [pool release];
     return ctx;
 }
@@ -742,3 +745,39 @@ Bool setGammaRamp(int tableSize, float* redRamp, float* greenRamp, float* blueRa
 void resetGammaRamp() {
   CGDisplayRestoreColorSyncSettings();
 }
+
+/***
+ * The following static functions are copied out of NEWT's OSX impl. <src/newt/native/MacWindow.m>
+ * May need to push code to NativeWindow, to remove duplication.
+ */
+static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) {
+    NSArray *screens = [NSScreen screens];
+    if(screen_idx<0) screen_idx=0;
+    if(screen_idx>=[screens count]) screen_idx=0;
+    return (NSScreen *) [screens objectAtIndex: screen_idx];
+}
+static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) {
+    // Mind: typedef uint32_t CGDirectDisplayID; - however, we assume it's 64bit on 64bit ?!
+    NSDictionary * dict = [screen deviceDescription];
+    NSNumber * val = (NSNumber *) [dict objectForKey: @"NSScreenNumber"];
+    // [NSNumber integerValue] returns NSInteger which is 32 or 64 bit native size
+    return (CGDirectDisplayID) [val integerValue];
+}
+static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) 
+{
+    long value = 0;
+    CFNumberRef numRef;
+    numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); 
+    if (numRef != NULL)
+        CFNumberGetValue(numRef, kCFNumberLongType, &value);    
+    return value;
+}
+#define CGDDGetModeRefreshRate(mode) GetDictionaryLong((mode), kCGDisplayRefreshRate)
+
+int getScreenRefreshRate(int scrn_idx) {
+    NSScreen *screen = NewtScreen_getNSScreenByIndex(scrn_idx);
+    CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen);
+    CFDictionaryRef mode = CGDisplayCurrentMode(display);
+    return CGDDGetModeRefreshRate(mode);
+}
+
diff --git a/src/jogl/native/openmax/com_sun_openmax_OMXInstance.c b/src/jogl/native/openmax/com_sun_openmax_OMXInstance.c
deleted file mode 100644
index 5317c2a..0000000
--- a/src/jogl/native/openmax/com_sun_openmax_OMXInstance.c
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- *  media_video_Movie.c
- *  JFXFramework
- *
- *  Created by sun on 17/02/08.
- *  Copyright 2007 __MyCompanyName__. All rights reserved.
- *
- */
-
-// http://developer.apple.com/technotes/tn2005/tn2140.html
-// http://developer.apple.com/qa/qa2005/qa1443.html
-// http://developer.apple.com/documentation/QuickTime/Conceptual/QT7UpdateGuide/Chapter03/chapter_3_section_1.html#//apple_ref/doc/c_ref/NewMovieFromProperties
-// http://developer.apple.com/qa/qa2001/qa1149.html
-// http://developer.apple.com/qa/qa2001/qa1262.html
-
-#include "com_jogamp_openmax_OMXInstance.h"
-#include "omx_tool.h"
-#include <stdarg.h>
-
-static const char * const ClazzNameRuntimeException =
-                            "java/lang/RuntimeException";
-static jclass    runtimeExceptionClz=NULL;
-#ifdef _WIN32_WCE
-    #define STDOUT_FILE "\\Storage Card\\demos\\stdout.txt"
-    #define STDERR_FILE "\\Storage Card\\demos\\stderr.txt"
-#endif
-
-static void _initStatics(JNIEnv *env)
-{
-    jclass c;
-#ifdef _WIN32_WCE
-    _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
-    _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
-#endif
-    fprintf(stdout, "_initstatics ..\n"); fflush(stdout); // JAU
-    if (runtimeExceptionClz != NULL) {
-        return;
-    }
-
-    c = (*env)->FindClass(env, ClazzNameRuntimeException);
-    if(NULL==c) {
-        fprintf(stdout, "FatalError: can't find %s\n", ClazzNameRuntimeException);
-        (*env)->FatalError(env, ClazzNameRuntimeException);
-    }
-    runtimeExceptionClz = (jclass)(*env)->NewGlobalRef(env, c);
-    if(NULL==runtimeExceptionClz) {
-        fprintf(stdout, "FatalError: can't use %s\n", ClazzNameRuntimeException);
-        (*env)->FatalError(env, ClazzNameRuntimeException);
-    }
-}
-
-void java_throwNewRuntimeException(intptr_t jni_env, const char* format, ...)
-{
-    va_list ap;
-    char buffer[255];
-    va_start(ap, format);
-    #ifdef _WIN32
-        _vsnprintf(buffer, sizeof(buffer)-1, format, ap);
-    #else
-        vsnprintf(buffer, sizeof(buffer)-1, format, ap);
-    #endif
-    va_end(ap);
-    buffer[sizeof(buffer)-1]=0;
-    fprintf(stderr, "RuntimeException: %s\n", buffer); fflush(stderr);
-    if(jni_env!=0) {
-        (*((JNIEnv *)jni_env))->ThrowNew((JNIEnv *)jni_env, runtimeExceptionClz, buffer);
-    }
-}
-
-void OMXInstance_SaveJavaAttributes(OMXToolBasicAV_t *pOMXAV, KDboolean issueJavaCallback)
-{
-    if(NULL==pOMXAV || 0==pOMXAV->jni_env || 0==pOMXAV->jni_instance) {
-        fprintf(stderr, "OMXInstance_SaveJavaAttributes failed");
-        return;
-    } else if(issueJavaCallback==KD_TRUE) {
-        JNIEnv  * env = (JNIEnv *)pOMXAV->jni_env;
-        jobject instance = (jobject)pOMXAV->jni_instance;
-        (*env)->CallVoidMethod(env, instance, (jmethodID)pOMXAV->jni_mid_saveAttributes);
-    }
-}
-
-void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pOMXAV, KDboolean issueJavaCallback)
-{
-    if(NULL==pOMXAV || 0==pOMXAV->jni_env || 0==pOMXAV->jni_instance) {
-        fprintf(stderr, "OMXInstance_UpdateJavaAttributes failed");
-        return;
-    } else {
-        JNIEnv  * env = (JNIEnv *)pOMXAV->jni_env;
-        jobject instance = (jobject)pOMXAV->jni_instance;
-        (*env)->SetIntField(env, instance, (jfieldID)pOMXAV->jni_fid_width, (jint)pOMXAV->width);
-        (*env)->SetIntField(env, instance, (jfieldID)pOMXAV->jni_fid_height, (jint)pOMXAV->height);
-        (*env)->SetIntField(env, instance, (jfieldID)pOMXAV->jni_fid_fps, (jint)pOMXAV->framerate);
-        (*env)->SetLongField(env, instance, (jfieldID)pOMXAV->jni_fid_bps, (jlong)pOMXAV->bitrate);
-        (*env)->SetLongField(env, instance, (jfieldID)pOMXAV->jni_fid_totalFrames, (jlong)(pOMXAV->length*pOMXAV->framerate));
-        if(issueJavaCallback==KD_TRUE) {
-            (*env)->CallVoidMethod(env, instance, (jmethodID)pOMXAV->jni_mid_attributesUpdated);
-        } else {
-            if(strlen(pOMXAV->videoCodec)>0) {
-                (*env)->SetObjectField(env, instance, (jfieldID)pOMXAV->jni_fid_vcodec, (*env)->NewStringUTF(env, pOMXAV->videoCodec));
-            }
-            if(strlen(pOMXAV->audioCodec)>0) {
-                (*env)->SetObjectField(env, instance, (jfieldID)pOMXAV->jni_fid_acodec, (*env)->NewStringUTF(env, pOMXAV->audioCodec));
-            }
-        }
-    }
-}
-
-JNIEXPORT jlong JNICALL Java_com_jogamp_openmax_OMXInstance__1createInstance
-  (JNIEnv *env, jobject instance)
-{
-    OMXToolBasicAV_t * pOMXAV;
-
-    _initStatics(env);
-
-    pOMXAV->jni_env=(intptr_t)env;
-    pOMXAV->jni_instance=(intptr_t)instance;
-
-    pOMXAV = OMXToolBasicAV_CreateInstance((intptr_t)env, (intptr_t)instance);
-    if(NULL!=pOMXAV) {
-        jclass cls = (*env)->GetObjectClass(env, instance);
-        pOMXAV->jni_mid_saveAttributes = (intptr_t) (*env)->GetMethodID(env, cls, "saveAttributes", "()V");
-        pOMXAV->jni_mid_attributesUpdated = (intptr_t) (*env)->GetMethodID(env, cls, "attributesUpdated", "()V");
-        pOMXAV->jni_fid_width = (intptr_t) (*env)->GetFieldID(env, cls, "width",  "I");
-        pOMXAV->jni_fid_height = (intptr_t) (*env)->GetFieldID(env, cls, "height",  "I");
-        pOMXAV->jni_fid_fps = (intptr_t) (*env)->GetFieldID(env, cls, "fps",  "I");
-        pOMXAV->jni_fid_bps = (intptr_t) (*env)->GetFieldID(env, cls, "bps",  "J");
-        pOMXAV->jni_fid_totalFrames = (intptr_t) (*env)->GetFieldID(env, cls, "totalFrames",  "J");
-        pOMXAV->jni_fid_acodec = (intptr_t) (*env)->GetFieldID(env, cls, "acodec",  "Ljava/lang/String;");
-        pOMXAV->jni_fid_vcodec = (intptr_t) (*env)->GetFieldID(env, cls, "vcodec",  "Ljava/lang/String;");
-    }
-
-    return (jlong) (intptr_t) (void *)pOMXAV;
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1setStream
-  (JNIEnv *env, jobject instance, jlong ptr, jint vBufferNum, jstring jpath)
-{
-    jboolean iscopy;
-    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-
-    fprintf(stdout, "setStream 1 ..\n"); fflush(stdout); // JAU
-    if (pOMXAV != NULL) {
-        const char *filePath = (*env)->GetStringUTFChars(env, jpath, &iscopy);
-        fprintf(stdout, "setStream 2 %s..\n", filePath); fflush(stdout); // JAU
-        pOMXAV->jni_env=(intptr_t)env;
-        pOMXAV->jni_instance=(intptr_t)instance;
-        OMXToolBasicAV_SetStream(pOMXAV, vBufferNum, filePath);
-        (*env)->ReleaseStringChars(env, jpath, (const jchar *)filePath);
-    }
-    fprintf(stdout, "setStream 3 ..\n"); fflush(stdout); // JAU
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1setStreamEGLImageTexture2D
-  (JNIEnv *env, jobject instance, jlong ptr, jint i, jint tex, jlong image, jlong sync)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  if (pOMXAV != NULL) {
-    OMXToolBasicAV_SetStreamEGLImageTexture2D( pOMXAV, i, (GLuint) tex, 
-                                         (EGLImageKHR)(intptr_t)image,
-                                         (EGLSyncKHR)(intptr_t)sync);
-  }
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1activateStream
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-
-    if (pOMXAV != NULL) {
-        OMXToolBasicAV_ActivateStream(pOMXAV);
-    }
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1attachVideoRenderer
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  OMXToolBasicAV_AttachVideoRenderer(pOMXAV);
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1detachVideoRenderer
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  OMXToolBasicAV_DetachVideoRenderer(pOMXAV);
-}
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1setPlaySpeed
-  (JNIEnv *env, jobject instance, jlong ptr, jfloat scale)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  OMXToolBasicAV_SetPlaySpeed(pOMXAV, scale);
-}
-
-JNIEXPORT jfloat JNICALL Java_com_jogamp_openmax_OMXInstance__1play
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  OMXToolBasicAV_PlayStart(pOMXAV);
-  return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
-}
-
-JNIEXPORT jfloat JNICALL Java_com_jogamp_openmax_OMXInstance__1pause
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  OMXToolBasicAV_PlayPause(pOMXAV);
-  return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
-}
-
-JNIEXPORT jfloat JNICALL Java_com_jogamp_openmax_OMXInstance__1stop
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-    OMXToolBasicAV_PlayStop(pOMXAV);
-    return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
-}
-
-JNIEXPORT jfloat JNICALL Java_com_jogamp_openmax_OMXInstance__1seek
-  (JNIEnv *env, jobject instance, jlong ptr, jfloat pos)
-{
-    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-    OMXToolBasicAV_PlaySeek(pOMXAV, pos);
-    return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
-}
-
-JNIEXPORT jint JNICALL Java_com_jogamp_openmax_OMXInstance__1getNextTextureID
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  jint textureID = 0xffffffff;
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  if (pOMXAV != NULL) {
-      textureID = OMXToolBasicAV_GetNextTextureID(pOMXAV);
-  }
-  return textureID;
-}
-
-JNIEXPORT jfloat JNICALL Java_com_jogamp_openmax_OMXInstance__1getCurrentPosition
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-    return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
-}
-
-
-JNIEXPORT void JNICALL Java_com_jogamp_openmax_OMXInstance__1destroyInstance
-  (JNIEnv *env, jobject instance, jlong ptr)
-{
-  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
-  if (pOMXAV != NULL) {
-    OMXToolBasicAV_DestroyInstance(pOMXAV);
-  }
-}
-
-
diff --git a/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c b/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c
new file mode 100644
index 0000000..964ac64
--- /dev/null
+++ b/src/jogl/native/openmax/jogamp_opengl_util_av_impl_OMXGLMediaPlayer.c
@@ -0,0 +1,208 @@
+/*
+ *  media_video_Movie.c
+ *  JFXFramework
+ *
+ *  Created by sun on 17/02/08.
+ *  Copyright 2007 __MyCompanyName__. All rights reserved.
+ *
+ */
+
+// http://developer.apple.com/technotes/tn2005/tn2140.html
+// http://developer.apple.com/qa/qa2005/qa1443.html
+// http://developer.apple.com/documentation/QuickTime/Conceptual/QT7UpdateGuide/Chapter03/chapter_3_section_1.html#//apple_ref/doc/c_ref/NewMovieFromProperties
+// http://developer.apple.com/qa/qa2001/qa1149.html
+// http://developer.apple.com/qa/qa2001/qa1262.html
+
+#include "jogamp_opengl_util_av_impl_OMXGLMediaPlayer.h"
+#include "JoglCommon.h"
+#include "omx_tool.h"
+#include <stdarg.h>
+
+static const char * const ClazzNameOMXGLMediaPlayer = "jogamp/opengl/util/av/impl/OMXGLMediaPlayer";
+
+static jclass omxGLMediaPlayerClazz = NULL;
+static jmethodID jni_mid_updateAttributes = NULL;
+
+#ifdef _WIN32_WCE
+    #define STDOUT_FILE "\\Storage Card\\demos\\stdout.txt"
+    #define STDERR_FILE "\\Storage Card\\demos\\stderr.txt"
+#endif
+
+JNIEXPORT jboolean JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer_initIDs0
+  (JNIEnv *env, jclass clazz)
+{
+#ifdef _WIN32_WCE
+    _wfreopen(TEXT(STDOUT_FILE),L"w",stdout);
+    _wfreopen(TEXT(STDERR_FILE),L"w",stderr);
+#endif
+    JoglCommon_init(env);
+
+    jclass c;
+    if (omxGLMediaPlayerClazz != NULL) {
+        return;
+    }
+
+    c = (*env)->FindClass(env, ClazzNameOMXGLMediaPlayer);
+    if(NULL==c) {
+        JoglCommon_FatalError(env, "JOGL OMX: can't find %s", ClazzNameOMXGLMediaPlayer);
+    }
+    omxGLMediaPlayerClazz = (jclass)(*env)->NewGlobalRef(env, c);
+    (*env)->DeleteLocalRef(env, c);
+    if(NULL==omxGLMediaPlayerClazz) {
+        JoglCommon_FatalError(env, "JOGL OMX: can't use %s", ClazzNameOMXGLMediaPlayer);
+    }
+
+    jni_mid_updateAttributes = (*env)->GetMethodID(env, omxGLMediaPlayerClazz, "updateAttributes", "(IIIIIFIILjava/lang/String;Ljava/lang/String;)V");
+
+    if(jni_mid_updateAttributes == NULL) {
+        return JNI_FALSE;
+    }
+    return JNI_TRUE;
+}
+
+void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pAV)
+{
+    if(NULL==pAV || 0==pAV->jni_instance) {
+        fprintf(stderr, "OMXInstance_UpdateJavaAttributes failed");
+        return;
+    }
+    int shallBeDetached = 0;
+    JNIEnv  * env = JoglCommon_GetJNIEnv (&shallBeDetached); 
+    if(NULL!=env) {
+        (*env)->CallVoidMethod(env, (jobject)pAV->jni_instance, jni_mid_updateAttributes,
+                               pAV->width, pAV->height, 
+                               pAV->bitrate, 0, 0, 
+                               pAV->framerate, (uint32_t)(pAV->length*pAV->framerate), pAV->length,
+                               (*env)->NewStringUTF(env, pAV->videoCodec),
+                               (*env)->NewStringUTF(env, pAV->audioCodec) );
+        JoglCommon_ReleaseJNIEnv (shallBeDetached);
+    }
+}
+
+JNIEXPORT jlong JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1createInstance
+  (JNIEnv *env, jobject instance)
+{
+    OMXToolBasicAV_t * pOMXAV;
+
+    pOMXAV = OMXToolBasicAV_CreateInstance((EGLDisplay)(intptr_t)env);
+    pOMXAV->jni_instance=(intptr_t)instance;
+    return (jlong) (intptr_t) pOMXAV;
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1setStream
+  (JNIEnv *env, jobject instance, jlong ptr, jint vBufferNum, jstring jpath)
+{
+    jboolean iscopy;
+    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+
+    fprintf(stdout, "setStream 1 ..\n"); fflush(stdout); // JAU
+    if (pOMXAV != NULL) {
+        const char *filePath = (*env)->GetStringUTFChars(env, jpath, &iscopy);
+        fprintf(stdout, "setStream 2 %s..\n", filePath); fflush(stdout); // JAU
+        pOMXAV->jni_instance=(intptr_t)instance;
+        OMXToolBasicAV_SetStream(pOMXAV, vBufferNum, filePath);
+        (*env)->ReleaseStringChars(env, jpath, (const jchar *)filePath);
+    }
+    fprintf(stdout, "setStream 3 ..\n"); fflush(stdout); // JAU
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1setStreamEGLImageTexture2D
+  (JNIEnv *env, jobject instance, jlong ptr, jint i, jint tex, jlong image, jlong sync)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  if (pOMXAV != NULL) {
+    OMXToolBasicAV_SetStreamEGLImageTexture2D( pOMXAV, i, (GLuint) tex, 
+                                         (EGLImageKHR)(intptr_t)image,
+                                         (EGLSyncKHR)(intptr_t)sync);
+  }
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1activateStream
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+
+    if (pOMXAV != NULL) {
+        OMXToolBasicAV_ActivateStream(pOMXAV);
+    }
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1attachVideoRenderer
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  OMXToolBasicAV_AttachVideoRenderer(pOMXAV);
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1detachVideoRenderer
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  OMXToolBasicAV_DetachVideoRenderer(pOMXAV);
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1setPlaySpeed
+  (JNIEnv *env, jobject instance, jlong ptr, jfloat scale)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  OMXToolBasicAV_SetPlaySpeed(pOMXAV, scale);
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1play
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  OMXToolBasicAV_PlayStart(pOMXAV);
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1pause
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  OMXToolBasicAV_PlayPause(pOMXAV);
+}
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1stop
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+    OMXToolBasicAV_PlayStop(pOMXAV);
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1seek
+  (JNIEnv *env, jobject instance, jlong ptr, jint pos)
+{
+    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+    OMXToolBasicAV_PlaySeek(pOMXAV, pos);
+    return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1getNextTextureID
+  (JNIEnv *env, jobject instance, jlong ptr, jboolean blocking)
+{
+  jint textureID = 0xffffffff;
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  if (pOMXAV != NULL) {
+      textureID = OMXToolBasicAV_GetNextTextureID(pOMXAV, blocking ? 1 : 0);
+  }
+  return textureID;
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1getCurrentPosition
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+    OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+    return OMXToolBasicAV_GetCurrentPosition(pOMXAV);
+}
+
+
+JNIEXPORT void JNICALL Java_jogamp_opengl_util_av_impl_OMXGLMediaPlayer__1destroyInstance
+  (JNIEnv *env, jobject instance, jlong ptr)
+{
+  OMXToolBasicAV_t *pOMXAV = (OMXToolBasicAV_t *)((void *)((intptr_t)ptr));
+  if (pOMXAV != NULL) {
+    OMXToolBasicAV_DestroyInstance(pOMXAV);
+  }
+}
+
+
diff --git a/src/jogl/native/openmax/omx_tool.c b/src/jogl/native/openmax/omx_tool.c
index 57fa8ad..16c43f6 100644
--- a/src/jogl/native/openmax/omx_tool.c
+++ b/src/jogl/native/openmax/omx_tool.c
@@ -28,35 +28,15 @@
 #define NOTSET_U32 ((OMX_U32)0xDEDEDEDE)
 #define INIT_PARAM(_X_)  (memset(&(_X_), NOTSET_U8, sizeof(_X_)), ((_X_).nSize = sizeof (_X_)), (_X_).nVersion = vOMX)
 
-void OMXInstance_SaveJavaAttributes(OMXToolBasicAV_t *pOMXAV, KDboolean issueJavaCallback);
-void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pOMXAV, KDboolean issueJavaCallback);
+void OMXInstance_UpdateJavaAttributes(OMXToolBasicAV_t *pOMXAV);
 
-#if !defined(SELF_TEST)
-void java_throwNewRuntimeException(intptr_t jni_env, const char* format, ...);
-#else
-#include <stdarg.h>
-void java_throwNewRuntimeException(intptr_t jni_env, const char* format, ...) {
-    va_list ap;
-    char buffer[255];
-    va_start(ap, format);
-    #ifdef _WIN32
-        _vsnprintf(buffer, sizeof(buffer)-1, format, ap);
-    #else
-        vsnprintf(buffer, sizeof(buffer)-1, format, ap);
-    #endif
-    va_end(ap);
-    buffer[sizeof(buffer)-1]=0;
-    DBG_PRINT( "RuntimeException: %s\n", buffer);
-    exit(1);
-}
-#endif
 static void DestroyInstanceUnlock(OMXToolBasicAV_t * pOMXAV);
 
 #define OMXSAFEVOID(x) \
 do { \
     OMX_ERRORTYPE err = (x); \
     if (err != OMX_ErrorNone) { \
-        java_throwNewRuntimeException((NULL!=pOMXAV)?pOMXAV->jni_env:0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
+        JoglCommon_throwNewRuntimeException(0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
         if(NULL!=pOMXAV) { \
             DestroyInstanceUnlock(pOMXAV); \
         } \
@@ -68,7 +48,7 @@ do { \
 do { \
     OMX_ERRORTYPE err = (x); \
     if (err != OMX_ErrorNone) { \
-        java_throwNewRuntimeException((NULL!=pOMXAV)?pOMXAV->jni_env:0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
+        JoglCommon_throwNewRuntimeException(0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
         if(NULL!=pOMXAV) { \
             DestroyInstanceUnlock(pOMXAV); \
         } \
@@ -80,7 +60,7 @@ do { \
 do { \
     OMX_ERRORTYPE err = (x); \
     if (err != OMX_ErrorNone) { \
-        java_throwNewRuntimeException((NULL!=pOMXAV)?pOMXAV->jni_env:0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
+        JoglCommon_throwNewRuntimeException(0, "FAILED at %s:%d, Error: 0x%x\n", __FILE__, __LINE__, err); \
         if(NULL!=pOMXAV) { \
             DestroyInstanceUnlock(pOMXAV); \
         } \
@@ -466,7 +446,7 @@ static void DestroyInstanceUnlock(OMXToolBasicAV_t * pOMXAV)
     DBG_PRINT( "Destroy p2\n");
     if(0!=(res1=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateIdle, KD_TRUE)))
     {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Destroy - Wait for Idle Failed (%d)", res1);
+        JoglCommon_throwNewRuntimeException(0, "Destroy - Wait for Idle Failed (%d)", res1);
     }
 
     DBG_PRINT( "Destroy p3\n");
@@ -479,7 +459,7 @@ static void DestroyInstanceUnlock(OMXToolBasicAV_t * pOMXAV)
     if(0!=(res2=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateLoaded, KD_TRUE)))
     {
         if(!res1) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Destroy - Wait for Loaded Failed (%d)", res2);
+            JoglCommon_throwNewRuntimeException(0, "Destroy - Wait for Loaded Failed (%d)", res2);
         }
     }
 
@@ -627,14 +607,14 @@ static int StartClock(OMXToolBasicAV_t * pOMXAV, KDboolean start, KDfloat32 time
     return (OMX_ErrorNotReady == eError)?-1:0;
 }
 
-static KDfloat32 GetClockPosition(OMXToolBasicAV_t * pOMXAV)
+static KDint64 GetClockPosition(OMXToolBasicAV_t * pOMXAV)
 {
     OMX_TIME_CONFIG_TIMESTAMPTYPE stamp;
     INIT_PARAM(stamp);
     stamp.nPortIndex = 0;
 
     OMX_GetConfig(pOMXAV->comp[OMXAV_H_CLOCK], OMX_IndexConfigTimeCurrentMediaTime, &stamp);
-    return (KDfloat32) (stamp.nTimestamp * (1.0f/(1000.0f*1000.0f)));
+    return (KDint64) ( stamp.nTimestamp / 1000L );
 }
 
 static KDfloat32 GetClockScale(OMXToolBasicAV_t * pOMXAV)
@@ -656,13 +636,13 @@ static KDint SetClockScale(OMXToolBasicAV_t * pOMXAV, KDfloat32 scale)
     return 0;
 }
 
-static int SetMediaPosition(OMXToolBasicAV_t * pOMXAV, KDfloat32 time) {
+static int SetMediaPosition(OMXToolBasicAV_t * pOMXAV, KDint64 time) {
     OMX_ERRORTYPE eError = OMX_ErrorNone;
     OMX_TIME_CONFIG_TIMESTAMPTYPE timestamp;
     int loop=STATE_TIMEOUT_LOOP;
     INIT_PARAM(timestamp);
     timestamp.nPortIndex = 0;
-    timestamp.nTimestamp = (OMX_TICKS) (time * 1000.0 * 1000.0);
+    timestamp.nTimestamp = (OMX_TICKS) (time * 1000L);
 
     eError = OMX_SetConfig(pOMXAV->comp[OMXAV_H_READER], OMX_IndexConfigTimePosition, &timestamp);
     while (loop>0 && OMX_ErrorNotReady == eError)
@@ -726,19 +706,20 @@ static OMX_ERRORTYPE UpdateStreamInfo(OMXToolBasicAV_t * pOMXAV, KDboolean issue
     }
 
     DBG_PRINT( "Update StreamInfo p1\n" );
-    OMXInstance_SaveJavaAttributes(pOMXAV, issueCallback);
 
     pOMXAV->width = oPortDef.format.video.nFrameWidth;
     pOMXAV->height = oPortDef.format.video.nFrameHeight;
     /* pOMXAV->stride = oPortDef.format.video.nStride;
     pOMXAV->sliceHeight = oPortDef.format.video.nSliceHeight; */
-    pOMXAV->framerate = oPortDef.format.video.xFramerate;
+    pOMXAV->framerate = (float) oPortDef.format.video.xFramerate;
     pOMXAV->bitrate = oPortDef.format.video.nBitrate;
-    DBG_PRINT( "Update StreamInfo p2 %dx%d, fps %d, bps %d\n", pOMXAV->width, pOMXAV->height, pOMXAV->framerate, pOMXAV->bitrate );
+    DBG_PRINT( "Update StreamInfo p2 %dx%d, fps %f, bps %d\n", pOMXAV->width, pOMXAV->height, pOMXAV->framerate, pOMXAV->bitrate );
     pOMXAV->length = GetMediaLength(pOMXAV);
     pOMXAV->speed = GetClockScale(pOMXAV);
 
-    OMXInstance_UpdateJavaAttributes(pOMXAV, issueCallback);
+    if(issueCallback) {
+        OMXInstance_UpdateJavaAttributes(pOMXAV);
+    }
 
     return err;
 }
@@ -755,7 +736,7 @@ static int AttachAudioRenderer(OMXToolBasicAV_t * pOMXAV)
         // FIXME: proper audio buffering .. 
         OMXSAFE(OMX_GetHandle(&pOMXAV->comp[OMXAV_H_ABUFFERING], "OMX.Nvidia.audio.visualization", pOMXAV, &pOMXAV->callbacks));
         if(0!=(res=SyncOnState(pOMXAV->comp[OMXAV_H_ABUFFERING], OMX_StateLoaded))) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Loading AudioBuffering Failed (%d)", res);
+            JoglCommon_throwNewRuntimeException(0, "Loading AudioBuffering Failed (%d)", res);
             return res;
         }
         /**
@@ -777,7 +758,7 @@ static int AttachAudioRenderer(OMXToolBasicAV_t * pOMXAV)
 
     // mandatory before SetupTunnel
     if(0!=(res=SyncOnState(pOMXAV->comp[OMXAV_H_ARENDERER], OMX_StateLoaded))) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Loading AudioRenderer Failed (%d)", res);
+        JoglCommon_throwNewRuntimeException(0, "Loading AudioRenderer Failed (%d)", res);
         return res;
     }
 
@@ -828,7 +809,7 @@ static int AttachVideoRenderer(OMXToolBasicAV_t * pOMXAV)
 {
     int i, res=0;
     if(KD_NULL!=pOMXAV->comp[OMXAV_H_VSCHEDULER]) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Detach Video first");
+        JoglCommon_throwNewRuntimeException(0, "Detach Video first");
         return -1;
     }
     OMXSAFE(OMX_GetHandle(&pOMXAV->comp[OMXAV_H_VSCHEDULER], "OMX.Nvidia.video.scheduler", pOMXAV, &pOMXAV->callbacks));
@@ -836,7 +817,7 @@ static int AttachVideoRenderer(OMXToolBasicAV_t * pOMXAV)
 
     // mandatory before SetupTunnel
     if(0!=(res=SyncOnState(pOMXAV->comp[OMXAV_H_VSCHEDULER], OMX_StateLoaded))) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Loading VideoScheduler Failed (%d)", res);
+        JoglCommon_throwNewRuntimeException(0, "Loading VideoScheduler Failed (%d)", res);
         return res;
     }
     // mandatory before EGLUseImage
@@ -861,7 +842,7 @@ static int AttachVideoRenderer(OMXToolBasicAV_t * pOMXAV)
         DBG_PRINT( "UseEGLImg %p #%d t:%d i:%p s:%p p1\n", pOMXAV, i, pBuf->tex, pBuf->image, pBuf->sync);
 
         if(NULL==pBuf->image) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "AttachVideoRenderer: User didn't set buffer %d/%d\n", i, pOMXAV->vBufferNum);
+            JoglCommon_throwNewRuntimeException(0, "AttachVideoRenderer: User didn't set buffer %d/%d\n", i, pOMXAV->vBufferNum);
             return -1;
         } else  {
             // tell decoder output port that it will be using EGLImage
@@ -886,7 +867,7 @@ static int DetachVideoRenderer(OMXToolBasicAV_t * pOMXAV)
     if(NULL==pOMXAV) return -1;
 
     if(KD_NULL==pOMXAV->comp[OMXAV_H_VSCHEDULER]) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Attach Video first");
+        JoglCommon_throwNewRuntimeException(0, "Attach Video first");
         return -1;
     }
     DBG_PRINT( "DetachVideoRenderer p0\n");
@@ -968,11 +949,11 @@ void OMXToolBasicAV_SetStream(OMXToolBasicAV_t * pOMXAV, int vBufferNum, const K
 
     // FIXME: verify player state .. ie stop !
     if(pOMXAV->status!=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Player instance in use\n");
+        JoglCommon_throwNewRuntimeException(0, "Player instance in use\n");
         return;
     }
     if(vBufferNum>EGLIMAGE_MAX_BUFFERS) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "buffer number %d > MAX(%d)\n", vBufferNum, EGLIMAGE_MAX_BUFFERS);
+        JoglCommon_throwNewRuntimeException(0, "buffer number %d > MAX(%d)\n", vBufferNum, EGLIMAGE_MAX_BUFFERS);
         return;
     }
 
@@ -987,7 +968,7 @@ void OMXToolBasicAV_SetStream(OMXToolBasicAV_t * pOMXAV, int vBufferNum, const K
 
     eError = AddFile(pOMXAV, stream);
     if(eError!=OMX_ErrorNone) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Couldn't open or handle stream: %s\n", stream);
+        JoglCommon_throwNewRuntimeException(0, "Couldn't open or handle stream: %s\n", stream);
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1040,7 +1021,7 @@ void OMXToolBasicAV_SetStream(OMXToolBasicAV_t * pOMXAV, int vBufferNum, const K
 
         if (pOMXAV->audioPort == -1 && pOMXAV->videoPort == -1)
         {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Neither audioport or videoport could be played back!\n");
+            JoglCommon_throwNewRuntimeException(0, "Neither audioport or videoport could be played back!\n");
             kdThreadMutexUnlock(pOMXAV->mutex);
             return;
         }
@@ -1071,12 +1052,12 @@ void OMXToolBasicAV_SetStream(OMXToolBasicAV_t * pOMXAV, int vBufferNum, const K
 void OMXToolBasicAV_SetStreamEGLImageTexture2D(OMXToolBasicAV_t * pOMXAV, KDint i, GLuint tex, EGLImageKHR image, EGLSyncKHR sync)
 {
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     DBG_PRINT( "SetStreamEGLImg %p #%d/%d t:%d i:%p s:%p..\n", pOMXAV, i, pOMXAV->vBufferNum, tex, image, sync);
     if(i<0||i>=pOMXAV->vBufferNum) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Buffer index out of range: %d\n", i);
+        JoglCommon_throwNewRuntimeException(0, "Buffer index out of range: %d\n", i);
         return;
     }
 
@@ -1094,7 +1075,7 @@ void OMXToolBasicAV_SetStreamEGLImageTexture2D(OMXToolBasicAV_t * pOMXAV, KDint
 void OMXToolBasicAV_ActivateStream(OMXToolBasicAV_t * pOMXAV) {
     int res;
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     DBG_PRINT( "ActivateStream 1\n");
@@ -1115,7 +1096,7 @@ void OMXToolBasicAV_ActivateStream(OMXToolBasicAV_t * pOMXAV) {
     // mandatory: before SetupTunnel (->Activate), wait until all devices are ready ..
     //            arender/vrender must wait as well ..
     if(0!=(res=OMXToolBasicAV_WaitForState(pOMXAV, OMX_StateLoaded))) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Loaded Failed (%d)", res);
+        JoglCommon_throwNewRuntimeException(0, "Loaded Failed (%d)", res);
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1161,7 +1142,7 @@ void OMXToolBasicAV_ActivateStream(OMXToolBasicAV_t * pOMXAV) {
     //
     if(0!=(res=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateIdle, KD_TRUE)))
     {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Wait for Idle Failed (%d)", res);
+        JoglCommon_throwNewRuntimeException(0, "Wait for Idle Failed (%d)", res);
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1172,11 +1153,11 @@ void OMXToolBasicAV_ActivateStream(OMXToolBasicAV_t * pOMXAV) {
 
 void OMXToolBasicAV_DetachVideoRenderer(OMXToolBasicAV_t * pOMXAV) {
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     kdThreadMutexLock(pOMXAV->mutex);
@@ -1188,11 +1169,11 @@ void OMXToolBasicAV_DetachVideoRenderer(OMXToolBasicAV_t * pOMXAV) {
 
 void OMXToolBasicAV_AttachVideoRenderer(OMXToolBasicAV_t * pOMXAV) {
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     kdThreadMutexLock(pOMXAV->mutex);
@@ -1205,11 +1186,11 @@ void OMXToolBasicAV_AttachVideoRenderer(OMXToolBasicAV_t * pOMXAV) {
 void OMXToolBasicAV_SetPlaySpeed(OMXToolBasicAV_t * pOMXAV, KDfloat32 scale)
 {
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     kdThreadMutexLock(pOMXAV->mutex);
@@ -1226,11 +1207,11 @@ void OMXToolBasicAV_PlayStart(OMXToolBasicAV_t * pOMXAV)
 {
     int res;
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     if(pOMXAV->status==OMXAV_PLAYING) {
@@ -1244,14 +1225,14 @@ void OMXToolBasicAV_PlayStart(OMXToolBasicAV_t * pOMXAV)
 
     DBG_PRINT( "Play 3.1\n");
     if(0!=(res=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateExecuting, KD_TRUE))) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Play Execute Failed (%d)", res);
+        JoglCommon_throwNewRuntimeException(0, "Play Execute Failed (%d)", res);
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
     if(pOMXAV->status==OMXAV_STOPPED || pOMXAV->status==OMXAV_FIN) {
         DBG_PRINT( "Play 3.2\n");
         if(StartClock(pOMXAV, KD_TRUE, 0.0)) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Play StartClock Failed");
+            JoglCommon_throwNewRuntimeException(0, "Play StartClock Failed");
             kdThreadMutexUnlock(pOMXAV->mutex);
             return;
         }
@@ -1275,13 +1256,13 @@ static int PlayStop(OMXToolBasicAV_t * pOMXAV)
 
     if(OMXToolBasicAV_CheckState(pOMXAV, OMX_StateLoaded)) {
         if(StartClock(pOMXAV, KD_FALSE, 0.0)) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Stop StopClock Failed");
+            JoglCommon_throwNewRuntimeException(0, "Stop StopClock Failed");
             kdThreadMutexUnlock(pOMXAV->mutex);
             return -1;
         }
         if(OMXToolBasicAV_CheckState(pOMXAV, OMX_StateIdle)) {
             if(0!=(res=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateIdle, KD_TRUE))) {
-                java_throwNewRuntimeException(pOMXAV->jni_env, "Stop Idle Failed (%d)", res);
+                JoglCommon_throwNewRuntimeException(0, "Stop Idle Failed (%d)", res);
                 kdThreadMutexUnlock(pOMXAV->mutex);
                 return res;
             }
@@ -1294,11 +1275,11 @@ static int PlayStop(OMXToolBasicAV_t * pOMXAV)
 void OMXToolBasicAV_PlayStop(OMXToolBasicAV_t * pOMXAV)
 {
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     kdThreadMutexLock(pOMXAV->mutex);
@@ -1312,11 +1293,11 @@ void OMXToolBasicAV_PlayPause(OMXToolBasicAV_t * pOMXAV)
 {
     int res;
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     if(pOMXAV->status==OMXAV_PAUSED || pOMXAV->status!=OMXAV_PLAYING) {
@@ -1334,16 +1315,16 @@ void OMXToolBasicAV_PlayPause(OMXToolBasicAV_t * pOMXAV)
     kdThreadMutexUnlock(pOMXAV->mutex);
 }
 
-void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
+void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDint64 time)
 {
     int res;
 
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return;
     }
     kdThreadMutexLock(pOMXAV->mutex);
@@ -1359,7 +1340,7 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     //    state transition to OMX_StatePause.
     if(pOMXAV->status!=OMXAV_PAUSED) {
         if(0!=(res=OMXToolBasicAV_RequestState(pOMXAV, OMX_StatePause, KD_TRUE))) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Seek Pause Failed (%d)", res);
+            JoglCommon_throwNewRuntimeException(0, "Seek Pause Failed (%d)", res);
             kdThreadMutexUnlock(pOMXAV->mutex);
             return;
         }
@@ -1369,7 +1350,7 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     //    on OMX_TIME_CONFIG_CLOCKSTATETYPE requesting a transition to
     //    OMX_TIME_ClockStateStopped.
     if(StartClock(pOMXAV, KD_FALSE, 0.0)) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Seek StopClock Failed");
+        JoglCommon_throwNewRuntimeException(0, "Seek StopClock Failed");
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1377,14 +1358,14 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     // 3. Seek to the desired location through the use of OMX_SetConfig on
     //    OMX_IndexConfigTimePosition requesting the desired timestamp.
     if(SetMediaPosition(pOMXAV, time)) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Seek position Failed");
+        JoglCommon_throwNewRuntimeException(0, "Seek position Failed");
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
 
     // 4. Flush all components.
     if(SendCommand(pOMXAV, OMX_CommandFlush, OMX_ALL, 0)) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Seek Flush Failed");
+        JoglCommon_throwNewRuntimeException(0, "Seek Flush Failed");
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1394,7 +1375,7 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     //    OMX_TIME_ClockStateRunning or
     //    OMX_TIME_ClockStateWaitingForStartTime.
     if(StartClock(pOMXAV, KD_TRUE, time)) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "Seek StartClock Failed");
+        JoglCommon_throwNewRuntimeException(0, "Seek StartClock Failed");
         kdThreadMutexUnlock(pOMXAV->mutex);
         return;
     }
@@ -1403,7 +1384,7 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     //    state transition to OMX_StateExecuting.
     if(pOMXAV->status==OMXAV_PLAYING) {
         if(0!=(res=OMXToolBasicAV_RequestState(pOMXAV, OMX_StateExecuting, KD_TRUE))) {
-            java_throwNewRuntimeException(pOMXAV->jni_env, "Seek Execute Failed (%d)", res);
+            JoglCommon_throwNewRuntimeException(0, "Seek Execute Failed (%d)", res);
             kdThreadMutexUnlock(pOMXAV->mutex);
             return;
         }
@@ -1411,9 +1392,9 @@ void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time)
     kdThreadMutexUnlock(pOMXAV->mutex);
 }
 
-GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV) {
+GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV, int blocking) {
     GLuint texID = 0;
-    int ret = pOMXAV->glPos;
+    int idx = pOMXAV->glPos;
     kdThreadMutexLock(pOMXAV->mutex);
 
     if(pOMXAV->status==OMXAV_PLAYING) {
@@ -1438,9 +1419,10 @@ GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV) {
                 pOMXAV->omxPos = next;
                 next = (pOMXAV->omxPos + 1) % pOMXAV->vBufferNum;
                 pOMXAV->filled++;
-            }
-            else
-            {
+                if(!blocking) {
+                    break;
+                }
+            } else {
                 DBG_PRINT2( "GetNextTexture p2.3\n");
                 break;
             }
@@ -1462,11 +1444,11 @@ GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV) {
             pOMXAV->available--;
             pOMXAV->filled--;
             pOMXAV->glPos = (pOMXAV->glPos + 1) % pOMXAV->vBufferNum;
-            ret = pOMXAV->glPos;
+            idx = pOMXAV->glPos;
         }
     }
 
-    texID = pOMXAV->available ? pOMXAV->buffers[ret].tex : 0;
+    texID = pOMXAV->available ? pOMXAV->buffers[idx].tex : 0;
     DBG_PRINT2( "GetNextTexture B avail %d, filled %d, pos o:%d g:%d t:%d\n", 
                 pOMXAV->available, pOMXAV->filled, pOMXAV->omxPos, pOMXAV->glPos, texID);
 
@@ -1474,14 +1456,14 @@ GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV) {
     return texID;
 }
 
-KDfloat32 OMXToolBasicAV_GetCurrentPosition(OMXToolBasicAV_t * pOMXAV) {
-    KDfloat32 res = -1.0f;
+KDint64 OMXToolBasicAV_GetCurrentPosition(OMXToolBasicAV_t * pOMXAV) {
+    KDint64 res = 0L;
     if(NULL==pOMXAV) {
-        java_throwNewRuntimeException(0, "OMX instance null\n");
+        JoglCommon_throwNewRuntimeException(0, "OMX instance null\n");
         return res;
     }
     if(pOMXAV->status<=OMXAV_INIT) {
-        java_throwNewRuntimeException(pOMXAV->jni_env, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
+        JoglCommon_throwNewRuntimeException(0, "OMX invalid status: %d <= INIT\n", pOMXAV->status);
         return res;
     }
     kdThreadMutexLock(pOMXAV->mutex);
diff --git a/src/jogl/native/openmax/omx_tool.h b/src/jogl/native/openmax/omx_tool.h
index d566507..414befc 100644
--- a/src/jogl/native/openmax/omx_tool.h
+++ b/src/jogl/native/openmax/omx_tool.h
@@ -73,16 +73,16 @@ typedef struct {
     OMX_HANDLETYPE endComponent;
     OMX_CALLBACKTYPE callbacks;
 
-    KDchar audioCodec[256];
-    KDchar audioCodecComponent[256];
-    KDchar videoCodec[256];
-    KDchar videoCodecComponent[256];
+    KDchar audioCodec[64];
+    KDchar audioCodecComponent[64];
+    KDchar videoCodec[64];
+    KDchar videoCodecComponent[64];
     int audioPort;
     int videoPort;
     KDuint32 width;
     KDuint32 height;
     KDuint32 bitrate; // per seconds
-    KDuint32 framerate; // per seconds
+    KDfloat32 framerate; // per seconds
     KDfloat32 length; // seconds
     KDfloat32 speed; // current clock scale
     KDfloat32 play_speed; // current play clock scale
@@ -99,17 +99,7 @@ typedef struct {
 
     int status;
 
-    intptr_t jni_env;
     intptr_t jni_instance;
-    intptr_t jni_mid_saveAttributes;
-    intptr_t jni_mid_attributesUpdated;
-    intptr_t jni_fid_width;
-    intptr_t jni_fid_height;
-    intptr_t jni_fid_fps;
-    intptr_t jni_fid_bps;
-    intptr_t jni_fid_totalFrames;
-    intptr_t jni_fid_acodec;
-    intptr_t jni_fid_vcodec;
 } OMXToolBasicAV_t ;
 
 //
@@ -138,10 +128,10 @@ void OMXToolBasicAV_SetPlaySpeed(OMXToolBasicAV_t * pOMXAV, KDfloat32 scale);
 void OMXToolBasicAV_PlayStart(OMXToolBasicAV_t * pOMXAV); // #5
 void OMXToolBasicAV_PlayPause(OMXToolBasicAV_t * pOMXAV);
 void OMXToolBasicAV_PlayStop(OMXToolBasicAV_t * pOMXAV);
-void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDfloat32 time);
-GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV);
+void OMXToolBasicAV_PlaySeek(OMXToolBasicAV_t * pOMXAV, KDint64 time);
+GLuint OMXToolBasicAV_GetNextTextureID(OMXToolBasicAV_t * pOMXAV, int blocking);
 
-KDfloat32 OMXToolBasicAV_GetCurrentPosition(OMXToolBasicAV_t * pOMXAV);
+KDint64 OMXToolBasicAV_GetCurrentPosition(OMXToolBasicAV_t * pOMXAV);
 
 void OMXToolBasicAV_DestroyInstance(OMXToolBasicAV_t * pOMXAV);
 
diff --git a/src/jogl/native/timespec.c b/src/jogl/native/timespec.c
index 74c1a69..50f0ca8 100644
--- a/src/jogl/native/timespec.c
+++ b/src/jogl/native/timespec.c
@@ -24,6 +24,20 @@ void timespec_addms(struct timespec *ts, long ms)
     ts->tv_nsec=ts->tv_nsec%1000000000;
 }
 
+void timespec_addmicros(struct timespec *ts, long micro)
+{
+    int sec=micro/1000000;
+    micro=micro - sec*1000000;
+
+    // perform the addition
+    ts->tv_nsec+=micro*1000;
+
+    // adjust the time
+    ts->tv_sec+=ts->tv_nsec/1000000000 + sec;
+    ts->tv_nsec=ts->tv_nsec%1000000000;
+
+}
+
 void timespec_addns(struct timespec *ts, long ns)
 {
     int sec=ns/1000000000;
diff --git a/src/jogl/native/timespec.h b/src/jogl/native/timespec.h
index 671eb47..f900bfa 100644
--- a/src/jogl/native/timespec.h
+++ b/src/jogl/native/timespec.h
@@ -5,6 +5,7 @@
 
 void timespec_now(struct timespec *ts);
 void timespec_addms(struct timespec *ts, long ms);
+void timespec_addmicros(struct timespec *ts, long micro);
 void timespec_addns(struct timespec *ts, long ns);
 
 /** returns 0: a==b, >0: a>b, <0: a<b */
diff --git a/src/nativewindow/classes/jogamp/nativewindow/MutableGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java
similarity index 98%
rename from src/nativewindow/classes/jogamp/nativewindow/MutableGraphicsConfiguration.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java
index ee3ab73..2d5af86 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/MutableGraphicsConfiguration.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/MutableGraphicsConfiguration.java
@@ -25,7 +25,7 @@
  * authors and should not be interpreted as representing official policies, either expressed
  * or implied, of JogAmp Community.
  */
-package jogamp.nativewindow;
+package com.jogamp.nativewindow;
 
 import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.CapabilitiesImmutable;
diff --git a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java
similarity index 83%
rename from src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java
index 59aa73b..f2993ab 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/WrappedSurface.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/WrappedSurface.java
@@ -26,7 +26,7 @@
  * or implied, of JogAmp Community.
  */
 
-package jogamp.nativewindow;
+package com.jogamp.nativewindow;
 
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
 import javax.media.nativewindow.ProxySurface;
@@ -49,22 +49,26 @@ public class WrappedSurface extends ProxySurface implements SurfaceChangeable {
     surfaceHandle = 0;
   }
 
-  public long getSurfaceHandle() {
+  final public long getSurfaceHandle() {
     return surfaceHandle;
   }
 
-  public void setSurfaceHandle(long surfaceHandle) {
+  final public void setSurfaceHandle(long surfaceHandle) {
     this.surfaceHandle=surfaceHandle;
   }
 
-  protected int lockSurfaceImpl() {
+  final protected int lockSurfaceImpl() {
       return LOCK_SUCCESS;
   }
 
-  protected void unlockSurfaceImpl() {
+  final protected void unlockSurfaceImpl() {
   }
 
   public String toString() {
-    return "WrappedSurface[config " + getPrivateGraphicsConfiguration() + ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + ", size " + getWidth() + "x" + getHeight() + "]";
+    return "WrappedSurface[config " + getPrivateGraphicsConfiguration()+ 
+           ", displayHandle 0x" + Long.toHexString(getDisplayHandle()) + 
+           ", surfaceHandle 0x" + Long.toHexString(getSurfaceHandle()) + 
+           ", size " + getWidth() + "x" + getHeight() +
+           ", surfaceLock "+surfaceLock+"]";
   }
 }
diff --git a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java
similarity index 99%
rename from src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsConfiguration.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java
index 45a3db8..61d5e5c 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsConfiguration.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsConfiguration.java
@@ -38,7 +38,7 @@
  * and developed by Kenneth Bradley Russell and Christopher John Kline.
  */
 
-package javax.media.nativewindow.awt;
+package com.jogamp.nativewindow.awt;
 
 import javax.media.nativewindow.*;
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java
similarity index 98%
rename from src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsDevice.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java
index 8ebe376..635e6d2 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsDevice.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsDevice.java
@@ -38,7 +38,7 @@
  * and developed by Kenneth Bradley Russell and Christopher John Kline.
  */
 
-package javax.media.nativewindow.awt;
+package com.jogamp.nativewindow.awt;
 
 import javax.media.nativewindow.*;
 import java.awt.GraphicsDevice;
diff --git a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java
similarity index 98%
rename from src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsScreen.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java
index 2978d78..f4ee06e 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTGraphicsScreen.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTGraphicsScreen.java
@@ -38,12 +38,14 @@
  * and developed by Kenneth Bradley Russell and Christopher John Kline.
  */
 
-package javax.media.nativewindow.awt;
+package com.jogamp.nativewindow.awt;
 
 import java.awt.GraphicsDevice;
 import java.awt.GraphicsEnvironment;
 import javax.media.nativewindow.*;
 
+
+
 /** A wrapper for an AWT GraphicsDevice (screen) allowing it to be
     handled in a toolkit-independent manner. */
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTWindowClosingProtocol.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java
similarity index 88%
rename from src/nativewindow/classes/javax/media/nativewindow/awt/AWTWindowClosingProtocol.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java
index e7db942..d78b4ac 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/awt/AWTWindowClosingProtocol.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/AWTWindowClosingProtocol.java
@@ -26,7 +26,7 @@
  * or implied, of JogAmp Community.
  */
 
-package javax.media.nativewindow.awt;
+package com.jogamp.nativewindow.awt;
 
 import java.awt.Component;
 import java.awt.Window;
@@ -34,6 +34,7 @@ import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 import java.awt.event.WindowListener;
 import javax.media.nativewindow.WindowClosingProtocol;
+
 import jogamp.nativewindow.awt.AWTMisc;
 
 public class AWTWindowClosingProtocol implements WindowClosingProtocol {
@@ -42,7 +43,7 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol {
   private Runnable closingOperation;
   private volatile boolean closingListenerSet = false;
   private Object closingListenerLock = new Object();
-  private int defaultCloseOperation = DISPOSE_ON_CLOSE;
+  private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE;
   private boolean defaultCloseOperationSetByUser = false;
 
   public AWTWindowClosingProtocol(Component comp, Runnable closingOperation) {
@@ -53,9 +54,9 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol {
   class WindowClosingAdapter extends WindowAdapter {
     @Override
     public void windowClosing(WindowEvent e) {
-      int op = AWTWindowClosingProtocol.this.getDefaultCloseOperation();
+      final WindowClosingMode op = AWTWindowClosingProtocol.this.getDefaultCloseOperation();
 
-      if( DISPOSE_ON_CLOSE == op ) {
+      if( WindowClosingMode.DISPOSE_ON_CLOSE == op ) {
           // we have to issue this call right away,
           // otherwise the window gets destroyed
           closingOperation.run();
@@ -110,27 +111,23 @@ public class AWTWindowClosingProtocol implements WindowClosingProtocol {
 
   /**
    *
-   * @return the user set close operation if set by {@link #setDefaultCloseOperation(int) setDefaultCloseOperation(int)},
+   * @return the user set close operation if set by {@link #setDefaultCloseOperation(WindowClosingMode) setDefaultCloseOperation(int)},
    *         otherwise return the AWT/Swing close operation value translated to
    *         a {@link WindowClosingProtocol} value .
    */
-  public final int getDefaultCloseOperation() {
-      int op = -1;
+  public final WindowClosingMode getDefaultCloseOperation() {
       synchronized(closingListenerLock) {
         if(defaultCloseOperationSetByUser) {
-          op = defaultCloseOperation;
+          return defaultCloseOperation;
         }
       }
-      if(0 <= op) {
-          return op;
-      }
       // User didn't determine the behavior, use underlying AWT behavior
       return AWTMisc.getNWClosingOperation(comp);
   }
 
-  public final int setDefaultCloseOperation(int op) {
+  public final WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
       synchronized(closingListenerLock) {
-          int _op = defaultCloseOperation;
+          final WindowClosingMode _op = defaultCloseOperation;
           defaultCloseOperation = op;
           defaultCloseOperationSetByUser = true;
           return _op;
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
similarity index 92%
rename from src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTWindow.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
index 6d28603..02dd746 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTWindow.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
@@ -35,7 +35,7 @@
  * facility.
  */
 
-package jogamp.nativewindow.jawt;
+package com.jogamp.nativewindow.awt;
 
 import com.jogamp.common.util.locks.LockFactory;
 import com.jogamp.common.util.locks.RecursiveLock;
@@ -51,7 +51,6 @@ import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.OffscreenLayerOption;
 import javax.media.nativewindow.OffscreenLayerSurface;
 import javax.media.nativewindow.SurfaceUpdatedListener;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
 import javax.media.nativewindow.util.Insets;
 import javax.media.nativewindow.util.InsetsImmutable;
 import javax.media.nativewindow.util.Point;
@@ -59,6 +58,9 @@ import javax.media.nativewindow.util.Rectangle;
 import javax.media.nativewindow.util.RectangleImmutable;
 
 import jogamp.nativewindow.SurfaceUpdatedHelper;
+import jogamp.nativewindow.jawt.JAWT;
+import jogamp.nativewindow.jawt.JAWTUtil;
+import jogamp.nativewindow.jawt.JAWT_Rectangle;
 
 public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, OffscreenLayerOption {
   protected static final boolean DEBUG = JAWTUtil.DEBUG;
@@ -70,6 +72,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
   protected Component component;
   private AWTGraphicsConfiguration config; // control access due to delegation
   private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper();
+  private RecursiveLock surfaceLock = LockFactory.createRecursiveLock();
 
   // lifetime: valid after lock but may change with each 1st lock, purges after invalidate
   private boolean isApplet;
@@ -79,6 +82,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
   protected Rectangle bounds;
   protected Insets insets;
   
+  private long drawable_old;
+  
   /**
    * Constructed by {@link jogamp.nativewindow.NativeWindowFactoryImpl#getNativeWindow(Object, AbstractGraphicsConfiguration)}
    * via this platform's specialization (X11, OSX, Windows, ..).
@@ -120,6 +125,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
     jawt = null;
     isOffscreenLayerSurface = false;
     drawable= 0;
+    drawable_old = 0;
     bounds = new Rectangle();
     insets = new Insets();
   }
@@ -230,8 +236,6 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
   // NativeSurface
   //
 
-  private RecursiveLock surfaceLock = LockFactory.createRecursiveLock();
-
   private void determineIfApplet() {
     Component c = component;
     while(!isApplet && null != c) {
@@ -252,6 +256,17 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
   protected abstract JAWT fetchJAWTImpl() throws NativeWindowException;
   protected abstract int lockSurfaceImpl() throws NativeWindowException;
 
+  protected void dumpJAWTInfo() {
+      if(null != jawt) {
+          System.err.println("JAWT version: 0x"+Integer.toHexString(jawt.getCachedVersion())+
+                             ", CA_LAYER: "+ JAWTUtil.isJAWTUsingOffscreenLayer(jawt)+
+                             ", isLayeredSurface "+isOffscreenLayerSurfaceEnabled()+", bounds "+bounds+", insets "+insets);
+      } else {
+          System.err.println("JAWT n/a, bounds "+bounds+", insets "+insets);
+      }
+      // Thread.dumpStack();
+  }
+    
   public final int lockSurface() throws NativeWindowException {
     surfaceLock.lock();
     int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ?
@@ -265,6 +280,13 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
                 jawt = fetchJAWTImpl();
                 isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt);
                 res = lockSurfaceImpl();
+                if(LOCK_SUCCESS == res && drawable_old != drawable) {
+                    res = LOCK_SURFACE_CHANGED;
+                    if(DEBUG) {            
+                        System.err.println("JAWTWindow: surface change 0x"+Long.toHexString(drawable_old)+" -> 0x"+Long.toHexString(drawable));
+                        // Thread.dumpStack();
+                    }
+                }
             } finally {
                 if (LOCK_SURFACE_NOT_READY >= res) {
                     adevice.unlock();
@@ -283,6 +305,7 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
 
   public final void unlockSurface() {
     surfaceLock.validateLocked();
+    drawable_old = drawable;
 
     if (surfaceLock.getHoldCount() == 1) {
         final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice();
@@ -459,7 +482,8 @@ public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface,
     }
     sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+
               ",\n\tconfig "+getPrivateGraphicsConfiguration()+
-              ",\n\tawtComponent "+getAWTComponent()+"]");
+              ",\n\tawtComponent "+getAWTComponent()+
+              ",\n\tsurfaceLock "+surfaceLock+"]");
 
     return sb.toString();
   }
diff --git a/src/nativewindow/classes/javax/media/nativewindow/egl/EGLGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java
similarity index 98%
rename from src/nativewindow/classes/javax/media/nativewindow/egl/EGLGraphicsDevice.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java
index 2dfd9f0..4ee3361 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/egl/EGLGraphicsDevice.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/egl/EGLGraphicsDevice.java
@@ -30,7 +30,7 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.egl;
+package com.jogamp.nativewindow.egl;
 
 import javax.media.nativewindow.*;
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/macosx/MacOSXGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java
similarity index 98%
rename from src/nativewindow/classes/javax/media/nativewindow/macosx/MacOSXGraphicsDevice.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java
index 02c6375..0dc788c 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/macosx/MacOSXGraphicsDevice.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/macosx/MacOSXGraphicsDevice.java
@@ -30,7 +30,7 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.macosx;
+package com.jogamp.nativewindow.macosx;
 
 import javax.media.nativewindow.*;
 
diff --git a/src/nativewindow/classes/jogamp/nativewindow/swt/SWTAccessor.java b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java
similarity index 98%
rename from src/nativewindow/classes/jogamp/nativewindow/swt/SWTAccessor.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java
index aab1556..f430961 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/swt/SWTAccessor.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/swt/SWTAccessor.java
@@ -25,7 +25,7 @@
  * authors and should not be interpreted as representing official policies, either expressed
  * or implied, of JogAmp Community.
  */
-package jogamp.nativewindow.swt;
+package com.jogamp.nativewindow.swt;
 
 import com.jogamp.common.os.Platform;
 import java.lang.reflect.Field;
@@ -37,10 +37,10 @@ import org.eclipse.swt.widgets.Control;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.NativeWindowFactory;
-import javax.media.nativewindow.windows.WindowsGraphicsDevice;
-import javax.media.nativewindow.x11.X11GraphicsDevice;
 import com.jogamp.common.util.ReflectionUtil;
-import javax.media.nativewindow.macosx.MacOSXGraphicsDevice;
+import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice;
+import com.jogamp.nativewindow.windows.WindowsGraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
 
 import jogamp.nativewindow.macosx.OSXUtil;
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/windows/WindowsGraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java
similarity index 98%
rename from src/nativewindow/classes/javax/media/nativewindow/windows/WindowsGraphicsDevice.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java
index 5d0129e..5cabdf1 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/windows/WindowsGraphicsDevice.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/windows/WindowsGraphicsDevice.java
@@ -30,7 +30,7 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.windows;
+package com.jogamp.nativewindow.windows;
 
 import javax.media.nativewindow.*;
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsConfiguration.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java
similarity index 89%
rename from src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsConfiguration.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java
index 7443933..0d2914c 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsConfiguration.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsConfiguration.java
@@ -31,11 +31,12 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.x11;
+package com.jogamp.nativewindow.x11;
 
 import javax.media.nativewindow.CapabilitiesImmutable;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
+
 import jogamp.nativewindow.x11.XVisualInfo;
 
 /** Encapsulates a graphics configuration, or OpenGL pixel format, on
@@ -59,21 +60,21 @@ public class X11GraphicsConfiguration extends MutableGraphicsConfiguration imple
       return super.clone();
     }
 
-    public XVisualInfo getXVisualInfo() {
+    final public XVisualInfo getXVisualInfo() {
         return info;
     }
 
-    protected void setXVisualInfo(XVisualInfo info) {
+    final protected void setXVisualInfo(XVisualInfo info) {
         this.info = info;
     }
 
-    public long getVisualID() {
-        return (null!=info)?info.getVisualid():0;
+    final public int getXVisualID() {
+        return (null!=info)?(int)info.getVisualid():0;
     }
     
     @Override
     public String toString() {
-        return getClass().getSimpleName()+"["+getScreen()+", visualID 0x" + Long.toHexString(getVisualID()) +
+        return getClass().getSimpleName()+"["+getScreen()+", visualID 0x" + Long.toHexString(getXVisualID()) +
                                        ",\n\tchosen    " + capabilitiesChosen+
                                        ",\n\trequested " + capabilitiesRequested+ 
                                        "]";
diff --git a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsDevice.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java
similarity index 99%
rename from src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsDevice.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java
index 73c8cfd..308756b 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsDevice.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsDevice.java
@@ -31,11 +31,12 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.x11;
+package com.jogamp.nativewindow.x11;
 
 import jogamp.nativewindow.Debug;
 import jogamp.nativewindow.x11.X11Lib;
 import jogamp.nativewindow.x11.X11Util;
+
 import javax.media.nativewindow.DefaultGraphicsDevice;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.NativeWindowFactory;
diff --git a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java
similarity index 96%
rename from src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java
rename to src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java
index 6473b9f..94013ec 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/x11/X11GraphicsScreen.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/x11/X11GraphicsScreen.java
@@ -31,7 +31,7 @@
  * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  */
 
-package javax.media.nativewindow.x11;
+package com.jogamp.nativewindow.x11;
 
 import javax.media.nativewindow.*;
 
@@ -65,8 +65,7 @@ public class X11GraphicsScreen extends DefaultGraphicsScreen implements Cloneabl
 
     private static int fetchScreen(X11GraphicsDevice device, int screen) {
         // It still could be an AWT hold handle ..
-        long display = device.getHandle();
-        if(X11Lib.XineramaEnabled(display)) {
+        if(X11Util.XineramaIsEnabled(device.getHandle())) {
             screen = 0; // Xinerama -> 1 screen
         }
         return screen;
diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java
index 1930bdd..ebdaf2f 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsConfiguration.java
@@ -43,7 +43,7 @@ package javax.media.nativewindow;
 /** A marker interface describing a graphics configuration, visual, or
     pixel format in a toolkit-independent manner. */
 
-public interface AbstractGraphicsConfiguration extends Cloneable {
+public interface AbstractGraphicsConfiguration extends VisualIDHolder, Cloneable {
     /**
      * Return the screen this graphics configuration is valid for
      */
diff --git a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java
index fa25c21..1dd01a2 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/AbstractGraphicsDevice.java
@@ -114,8 +114,8 @@ public interface AbstractGraphicsDevice extends Cloneable {
      * <p>
      * The default implementation is a <code>NOP</code>, just setting the handle to <code>null</code>.
      * </p>
-     * The specific implementing, ie {@link javax.media.nativewindow.x11.X11GraphicsDevice},
-     * shall have a enable/disable like {@link javax.media.nativewindow.x11.X11GraphicsDevice#setCloseDisplay(boolean, boolean)},<br>
+     * The specific implementing, ie {@link com.jogamp.nativewindow.x11.X11GraphicsDevice},
+     * shall have a enable/disable like {@link com.jogamp.nativewindow.x11.X11GraphicsDevice#setCloseDisplay(boolean, boolean)},<br>
      * which shall be invoked at creation time to determine ownership/role of freeing the resource.<br>
      *
      * @return true if the handle was not <code>null</code>, otherwise false.
diff --git a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java
index 368847e..b422f50 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/Capabilities.java
@@ -45,6 +45,8 @@ package javax.media.nativewindow;
     contains the minimal number of routines which allow configuration
     on all supported window systems. */
 public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparable {
+  protected final static String na_str = "----" ;
+
   private int     redBits        = 8;
   private int     greenBits      = 8;
   private int     blueBits       = 8;
@@ -138,6 +140,17 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl
     return 0; // they are equal: RGBA
   }
 
+  @Override
+  public int getVisualID(VIDType type) throws NativeWindowException {
+      switch(type) {
+          case INTRINSIC:
+          case NATIVE:
+              return VisualIDHolder.VID_UNDEFINED;
+          default:
+              throw new NativeWindowException("Invalid type <"+type+">");
+      }      
+  }
+    
   /** Returns the number of bits requested for the color buffer's red
       component. On some systems only the color depth, which is the
       sum of the red, green, and blue bits, is considered. */
@@ -301,9 +314,9 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl
       A value of -1 is interpreted as any value. */
   public void setTransparentAlphaValue(int transValueAlpha) { transparentValueAlpha=transValueAlpha; }
 
-  public StringBuffer toString(StringBuffer sink) {
+  public StringBuilder toString(StringBuilder sink) {
     if(null == sink) {
-        sink = new StringBuffer();
+        sink = new StringBuilder();
     }
     if(onscreen) {
         sink.append("on-scr");
@@ -323,10 +336,11 @@ public class Capabilities implements CapabilitiesImmutable, Cloneable, Comparabl
   /** Returns a textual representation of this Capabilities
       object. */ 
   public String toString() {
-    StringBuffer msg = new StringBuffer();
+    StringBuilder msg = new StringBuilder();
     msg.append("Caps[");
     toString(msg);
     msg.append("]");
     return msg.toString();
   }
+
 }
diff --git a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java
index eccdf77..3d7362c 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/CapabilitiesImmutable.java
@@ -36,7 +36,7 @@ import com.jogamp.common.type.WriteCloneable;
  * 
  * @see javax.media.nativewindow.Capabilities
  */
-public interface CapabilitiesImmutable extends WriteCloneable {
+public interface CapabilitiesImmutable extends VisualIDHolder, WriteCloneable {
 
     /**
      * Returns the number of bits requested for the color buffer's red
@@ -110,7 +110,7 @@ public interface CapabilitiesImmutable extends WriteCloneable {
     int hashCode();
 
     /** Return a textual representation of this object. Use the given StringBuffer [optional]. */
-    StringBuffer toString(StringBuffer sink);
+    StringBuilder toString(StringBuilder sink);
 
     /** Returns a textual representation of this object. */
     @Override
diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java
index 6709344..48c4d31 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultCapabilitiesChooser.java
@@ -40,7 +40,6 @@
 
 package javax.media.nativewindow;
 
-import java.security.AccessController;
 import java.util.List;
 
 import jogamp.nativewindow.Debug;
@@ -67,7 +66,7 @@ import jogamp.nativewindow.Debug;
 */
 
 public class DefaultCapabilitiesChooser implements CapabilitiesChooser {
-  private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true, AccessController.getContext());
+  private static final boolean DEBUG = Debug.isPropertyDefined("nativewindow.debug.CapabilitiesChooser", true); 
 
   public int chooseCapabilities(final CapabilitiesImmutable desired,
                                 final List /*<CapabilitiesImmutable>*/ available,
diff --git a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java
index 3eb7a6c..a33c379 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/DefaultGraphicsConfiguration.java
@@ -32,7 +32,11 @@
 
 package javax.media.nativewindow;
 
+import jogamp.nativewindow.Debug;
+
 public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphicsConfiguration {
+    protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration");
+    
     private AbstractGraphicsScreen screen;
     protected CapabilitiesImmutable capabilitiesChosen;
     protected CapabilitiesImmutable capabilitiesRequested;
@@ -40,13 +44,16 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics
     public DefaultGraphicsConfiguration(AbstractGraphicsScreen screen, 
                                         CapabilitiesImmutable capsChosen, CapabilitiesImmutable capsRequested) {
         if(null == screen) {
-            throw new NativeWindowException("Null screen");
+            throw new IllegalArgumentException("Null screen");
         }
         if(null == capsChosen) {
-            throw new NativeWindowException("Null chosen caps");
+            throw new IllegalArgumentException("Null chosen caps");
         }
         if(null == capsRequested) {
-            throw new NativeWindowException("Null requested caps");
+            throw new IllegalArgumentException("Null requested caps");
+        }
+        if( ! ( capsChosen instanceof VisualIDHolder ) ) {
+            throw new IllegalArgumentException("Chosen caps is not implementing NativeVisualID");
         }
         this.screen = screen;
         this.capabilitiesChosen = capsChosen;
@@ -62,15 +69,15 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics
         }
     }
 
-    public AbstractGraphicsScreen getScreen() {
+    final public AbstractGraphicsScreen getScreen() {
         return screen;
     }
 
-    public CapabilitiesImmutable getChosenCapabilities() {
+    final public CapabilitiesImmutable getChosenCapabilities() {
         return capabilitiesChosen;
     }
 
-    public CapabilitiesImmutable getRequestedCapabilities() {
+    final public CapabilitiesImmutable getRequestedCapabilities() {
         return capabilitiesRequested;
     }
 
@@ -78,6 +85,11 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics
         return this;
     }
 
+    @Override
+    final public int getVisualID(VIDType type) throws NativeWindowException {
+        return capabilitiesChosen.getVisualID(type);
+    }
+            
     /**
      * Set the capabilities to a new value.
      *
@@ -98,7 +110,7 @@ public class DefaultGraphicsConfiguration implements Cloneable, AbstractGraphics
      *
      * A copy of the passed object is being used.
      */
-    protected void setScreen(DefaultGraphicsScreen screen) {
+    final protected void setScreen(DefaultGraphicsScreen screen) {
         this.screen = (AbstractGraphicsScreen) screen.clone();
     }
 
diff --git a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java
index 2596444..2610f2c 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/GraphicsConfigurationFactory.java
@@ -57,38 +57,65 @@ import java.util.Map;
  */
 
 public abstract class GraphicsConfigurationFactory {
-    protected static final boolean DEBUG = Debug.debug("GraphicsConfiguration");
+    protected static final boolean DEBUG;
 
-    private static Map<Class<?>, GraphicsConfigurationFactory> registeredFactories =
-        Collections.synchronizedMap(new HashMap<Class<?>, GraphicsConfigurationFactory>());
+    private static Map<Class<?>, GraphicsConfigurationFactory> registeredFactories;
     private static Class<?> abstractGraphicsDeviceClass;
-
+    static boolean initialized = false;
+    
     static {
-        abstractGraphicsDeviceClass = javax.media.nativewindow.AbstractGraphicsDevice.class;
-        
-        // Register the default no-op factory for arbitrary
-        // AbstractGraphicsDevice implementations, including
-        // AWTGraphicsDevice instances -- the OpenGL binding will take
-        // care of handling AWTGraphicsDevices on X11 platforms (as
-        // well as X11GraphicsDevices in non-AWT situations)
-        registerFactory(abstractGraphicsDeviceClass, new DefaultGraphicsConfigurationFactoryImpl());
+        DEBUG = Debug.debug("GraphicsConfiguration");
+        if(DEBUG) {
+            System.err.println(Thread.currentThread().getName()+" - Info: GraphicsConfigurationFactory.<init>");
+            // Thread.dumpStack();
+        }
+        abstractGraphicsDeviceClass = javax.media.nativewindow.AbstractGraphicsDevice.class;        
+    }
         
-        if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) {
-            try {
-                ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", 
-                                                "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader());                
-            } catch (Exception e) {
-                throw new RuntimeException(e);
+    public static synchronized void initSingleton() {
+        if(!initialized) {
+            initialized = true;
+
+            if(DEBUG) {
+                System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.initSingleton()");
             }
-            if(NativeWindowFactory.isAWTAvailable()) {
+            registeredFactories = Collections.synchronizedMap(new HashMap<Class<?>, GraphicsConfigurationFactory>());
+            
+            // Register the default no-op factory for arbitrary
+            // AbstractGraphicsDevice implementations, including
+            // AWTGraphicsDevice instances -- the OpenGL binding will take
+            // care of handling AWTGraphicsDevices on X11 platforms (as
+            // well as X11GraphicsDevices in non-AWT situations)
+            registerFactory(abstractGraphicsDeviceClass, new DefaultGraphicsConfigurationFactoryImpl());
+            
+            if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(true))) {
                 try {
-                    ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", 
+                    ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.X11GraphicsConfigurationFactory", 
                                                     "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader());                
-                } catch (Exception e) { /* n/a */ }
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+                if(NativeWindowFactory.isAWTAvailable()) {
+                    try {
+                        ReflectionUtil.callStaticMethod("jogamp.nativewindow.x11.awt.X11AWTGraphicsConfigurationFactory", 
+                                                        "registerFactory", null, null, GraphicsConfigurationFactory.class.getClassLoader());                
+                    } catch (Exception e) { /* n/a */ }
+                }
             }
         }
     }
-
+    
+    public static synchronized void shutdown() {
+        if(initialized) {
+            initialized = false;
+            if(DEBUG) {
+                System.err.println(Thread.currentThread().getName()+" - GraphicsConfigurationFactory.shutdown()");
+            }
+            registeredFactories.clear();
+            registeredFactories = null;
+        }
+    }
+    
     protected static String getThreadName() {
         return Thread.currentThread().getName();
     }
@@ -154,18 +181,30 @@ public abstract class GraphicsConfigurationFactory {
      * called by end users, only implementors of new
      * GraphicsConfigurationFactory subclasses.
      *
+     * @return the previous registered factory, or null if none
      * @throws IllegalArgumentException if the given class does not implement AbstractGraphicsDevice
      */
-    protected static void registerFactory(Class<?> abstractGraphicsDeviceImplementor, GraphicsConfigurationFactory factory)
+    protected static GraphicsConfigurationFactory registerFactory(Class<?> abstractGraphicsDeviceImplementor, GraphicsConfigurationFactory factory)
         throws IllegalArgumentException
     {
         if (!(abstractGraphicsDeviceClass.isAssignableFrom(abstractGraphicsDeviceImplementor))) {
             throw new IllegalArgumentException("Given class must implement AbstractGraphicsDevice");
         }
-        if(DEBUG) {
-            System.err.println("GraphicsConfigurationFactory.registerFactory() "+abstractGraphicsDeviceImplementor+" -> "+factory);
+        final GraphicsConfigurationFactory prevFactory;
+        if(null == factory) {
+            prevFactory = registeredFactories.remove(abstractGraphicsDeviceImplementor);
+            if(DEBUG) {
+                System.err.println("GraphicsConfigurationFactory.registerFactory() remove "+abstractGraphicsDeviceImplementor+
+                                   ", deleting: "+prevFactory);
+            }
+        } else {
+            prevFactory = registeredFactories.put(abstractGraphicsDeviceImplementor, factory);
+            if(DEBUG) {
+                System.err.println("GraphicsConfigurationFactory.registerFactory() put "+abstractGraphicsDeviceImplementor+" -> "+factory+
+                                   ", overridding: "+prevFactory);
+            }
         }
-        registeredFactories.put(abstractGraphicsDeviceImplementor, factory);
+        return prevFactory;
     }
 
     /**
@@ -193,12 +232,12 @@ public abstract class GraphicsConfigurationFactory {
      * returned graphics configuration must be specified in the
      * documentation binding this particular API to the underlying
      * window toolkit. The Reference Implementation accepts {@link
-     * javax.media.nativewindow.awt.AWTGraphicsDevice AWTGraphicsDevice} objects and returns {@link
-     * javax.media.nativewindow.awt.AWTGraphicsConfiguration AWTGraphicsConfiguration} objects. On
+     * com.jogamp.nativewindow.awt.AWTGraphicsDevice AWTGraphicsDevice} objects and returns {@link
+     * com.jogamp.nativewindow.awt.AWTGraphicsConfiguration AWTGraphicsConfiguration} objects. On
      * X11 platforms where the AWT is not in use, it also accepts
-     * {@link javax.media.nativewindow.x11.X11GraphicsDevice
+     * {@link com.jogamp.nativewindow.x11.X11GraphicsDevice
      * X11GraphicsDevice} objects and returns {@link
-     * javax.media.nativewindow.x11.X11GraphicsConfiguration
+     * com.jogamp.nativewindow.x11.X11GraphicsConfiguration
      * X11GraphicsConfiguration} objects.</P>
      *
      * @param capsChosen     the intermediate chosen capabilities to be refined by this implementation, may be equal to capsRequested
diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java
index e255dc0..b7829cb 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/NativeSurface.java
@@ -50,23 +50,35 @@ public interface NativeSurface extends SurfaceUpdatedListener {
   public static final int LOCK_SUCCESS = 3;
 
   /**
-   * Lock the surface of this native window<P>
-   *
-   * The surface handle, see {@link #lockSurface()}, <br>
-   * shall be valid after a successfull call,
-   * ie return a value other than {@link #LOCK_SURFACE_NOT_READY}.<P>
-   *
+   * Lock the surface of this native window.
+   * <p>
+   * The surface handle shall be valid after a successfull call,
+   * ie return a value other than {@link #LOCK_SURFACE_UNLOCKED} and {@link #LOCK_SURFACE_NOT_READY},
+   * which is 
+   * <pre> 
+   *    boolean ok = lockSurface() > LOCK_SURFACE_NOT_READY; 
+   * </pre> 
+   * </p>
+   * <p>
+   * The caller may need to take care of the result {@link #LOCK_SURFACE_CHANGED},
+   * where the surface handle is valid but has changed.
+   * </p>
+   * <p>
    * This call is blocking until the surface has been locked
-   * or a timeout is reached. The latter will throw a runtime exception. <P>
-   *
-   * This call allows recursion from the same thread.<P>
-   *
+   * or a timeout is reached. The latter will throw a runtime exception.
+   * </p>
+   * <p>
+   * This call allows recursion from the same thread.
+   * </p>
+   * <p>
    * The implementation may want to aquire the 
    * application level {@link com.jogamp.common.util.locks.RecursiveLock}
-   * first before proceeding with a native surface lock. <P>
-   *
+   * first before proceeding with a native surface lock.
+   * </p>
+   * <p>
    * The implementation shall also invoke {@link AbstractGraphicsDevice#lock()}
-   * for the initial lock (recursive count zero).<P>
+   * for the initial lock (recursive count zero).
+   * </p>
    *
    * @return {@link #LOCK_SUCCESS}, {@link #LOCK_SURFACE_CHANGED} or {@link #LOCK_SURFACE_NOT_READY}.
    *
diff --git a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java
index c69b18b..b85ad47 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/NativeWindowFactory.java
@@ -35,7 +35,6 @@ package javax.media.nativewindow;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
-import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.Collections;
@@ -91,11 +90,8 @@ public abstract class NativeWindowFactory {
     private static final String OSXUtilClassName = "jogamp.nativewindow.macosx.OSXUtil";
     private static final String GDIClassName = "jogamp.nativewindow.windows.GDIUtil";
     
-    private static Class<?>  jawtUtilClass;
-    private static Method jawtUtilGetJAWTToolkitMethod;
-    private static Method jawtUtilInitMethod;
+    private static ToolkitLock jawtUtilJAWTToolkitLock;
     
-    public static final String AWTComponentClassName = "java.awt.Component" ;
     public static final String X11JAWTToolkitLockClassName = "jogamp.nativewindow.jawt.x11.X11JAWTToolkitLock" ;
     public static final String X11ToolkitLockClassName = "jogamp.nativewindow.x11.X11ToolkitLock" ;
     
@@ -135,8 +131,8 @@ public abstract class NativeWindowFactory {
         Platform.initSingleton();
         DEBUG = Debug.debug("NativeWindow");
         if(DEBUG) {
-            Throwable td = new Throwable(Thread.currentThread().getName()+" - Info: NativeWindowFactory.<init>");
-            td.printStackTrace();
+            System.err.println(Thread.currentThread().getName()+" - Info: NativeWindowFactory.<init>");
+            // Thread.dumpStack();
         }
     }
 
@@ -193,9 +189,8 @@ public abstract class NativeWindowFactory {
             final ClassLoader cl = NativeWindowFactory.class.getClassLoader();
 
             // Gather the windowing OS first
-            AccessControlContext acc = AccessController.getContext();
             nativeWindowingTypePure = _getNativeWindowingType();
-            String tmp = Debug.getProperty("nativewindow.ws.name", true, acc);
+            String tmp = Debug.getProperty("nativewindow.ws.name", true);
             if(null==tmp || tmp.length()==0) {
                 nativeWindowingTypeCustom = nativeWindowingTypePure;
             } else {
@@ -208,33 +203,49 @@ public abstract class NativeWindowFactory {
             }            
             isAWTAvailable = false; // may be set to true below
 
-            if( !Debug.getBooleanProperty("java.awt.headless", true, acc) &&
-                ReflectionUtil.isClassAvailable(AWTComponentClassName, cl) &&
-                ReflectionUtil.isClassAvailable("javax.media.nativewindow.awt.AWTGraphicsDevice", cl) ) {
-
-                AccessController.doPrivileged(new PrivilegedAction<Object>() {
-                    public Object run() {
+            if( Platform.AWT_AVAILABLE &&
+                ReflectionUtil.isClassAvailable("com.jogamp.nativewindow.awt.AWTGraphicsDevice", cl) ) {
+                
+                Method[] jawtUtilMethods = AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
+                    public Method[] run() {
                         try {
-                            jawtUtilClass = Class.forName(JAWTUtilClassName, true, NativeWindowFactory.class.getClassLoader());
-                            jawtUtilInitMethod = jawtUtilClass.getDeclaredMethod("initSingleton", (Class[])null);
+                            Class<?> _jawtUtilClass = Class.forName(JAWTUtilClassName, true, NativeWindowFactory.class.getClassLoader());
+                            Method jawtUtilIsHeadlessMethod = _jawtUtilClass.getDeclaredMethod("isHeadlessMode", (Class[])null);
+                            jawtUtilIsHeadlessMethod.setAccessible(true);
+                            Method jawtUtilInitMethod = _jawtUtilClass.getDeclaredMethod("initSingleton", (Class[])null);
                             jawtUtilInitMethod.setAccessible(true);
-                            jawtUtilGetJAWTToolkitMethod = jawtUtilClass.getDeclaredMethod("getJAWTToolkitLock", new Class[]{});
-                            jawtUtilGetJAWTToolkitMethod.setAccessible(true);
+                            Method jawtUtilGetJAWTToolkitLockMethod = _jawtUtilClass.getDeclaredMethod("getJAWTToolkitLock", new Class[]{});
+                            jawtUtilGetJAWTToolkitLockMethod.setAccessible(true);
+                            return new Method[] { jawtUtilInitMethod, jawtUtilIsHeadlessMethod, jawtUtilGetJAWTToolkitLockMethod }; 
                         } catch (Exception e) {
-                            // Either not a Sun JDK or the interfaces have changed since 1.4.2 / 1.5
+                            if(DEBUG) {
+                                e.printStackTrace();
+                            }
                         }
                         return null;
                     }
                 });
-                if(null != jawtUtilClass && null != jawtUtilGetJAWTToolkitMethod && null != jawtUtilInitMethod) {
+                if(null != jawtUtilMethods) {
+                    final Method jawtUtilInitMethod = jawtUtilMethods[0];
+                    final Method jawtUtilIsHeadlessMethod = jawtUtilMethods[1];
+                    final Method jawtUtilGetJAWTToolkitLockMethod = jawtUtilMethods[2];
+                    
                     ReflectionUtil.callMethod(null, jawtUtilInitMethod);
 
-                    Object resO = ReflectionUtil.callStaticMethod(JAWTUtilClassName, "isHeadlessMode", null, null, cl );
+                    Object resO = ReflectionUtil.callMethod(null, jawtUtilIsHeadlessMethod);
                     if(resO instanceof Boolean) {
                         // AWT is only available in case all above classes are available
                         // and AWT is not int headless mode
                         isAWTAvailable = ((Boolean)resO).equals(Boolean.FALSE);
+                    } else {
+                        throw new RuntimeException("JAWTUtil.isHeadlessMode() didn't return a Boolean");
                     }
+                    resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitLockMethod);            
+                    if(resO instanceof ToolkitLock) {
+                        jawtUtilJAWTToolkitLock = (ToolkitLock) resO;
+                    } else {
+                        throw new RuntimeException("JAWTUtil.getJAWTToolkitLock() didn't return a ToolkitLock");
+                    }                    
                 }
             }
             if(!firstUIActionOnProcess) {
@@ -251,7 +262,7 @@ public abstract class NativeWindowFactory {
         
             if ( isAWTAvailable ) {
                 // register either our default factory or (if exist) the X11/AWT one -> AWT Component
-                registerFactory(ReflectionUtil.getClass(AWTComponentClassName, false, cl), factory);
+                registerFactory(ReflectionUtil.getClass(ReflectionUtil.AWTNames.ComponentClass, false, cl), factory);
             }
 
             if( TYPE_X11 == nativeWindowingTypePure ) {
@@ -263,12 +274,14 @@ public abstract class NativeWindowFactory {
                     x11JAWTToolkitLockConstructor = ReflectionUtil.getConstructor(x11JAWTToolkitLockClass, new Class[] { long.class } );
                 }
             }
- 
+            
             if(DEBUG) {
                 System.err.println("NativeWindowFactory firstUIActionOnProcess "+firstUIActionOnProcess);
                 System.err.println("NativeWindowFactory requiresToolkitLock "+requiresToolkitLock);
                 System.err.println("NativeWindowFactory isAWTAvailable "+isAWTAvailable+", defaultFactory "+factory);
             }
+            
+            GraphicsConfigurationFactory.initSingleton();
         }
     }
 
@@ -280,6 +293,7 @@ public abstract class NativeWindowFactory {
             }
             registeredFactories.clear();
             registeredFactories = null;
+            GraphicsConfigurationFactory.shutdown();
             // X11Util.shutdown(..) already called via GLDrawableFactory.shutdown() ..
             if(DEBUG) {
                 System.err.println(Thread.currentThread().getName()+" - NativeWindowFactory.shutdown() END");                
@@ -348,10 +362,10 @@ public abstract class NativeWindowFactory {
      *   <ul>
      *     <li>If <b>AWT-type</b> and <b>native-X11-type</b> and <b>AWT-available</b></li>
      *       <ul>
-     *         <li> return {@link jogamp.nativewindow.jawt.JAWTToolkitLock} </li>
+     *         <li> return {@link #getAWTToolkitLock()} </li>
      *       </ul>
      *   </ul>
-     *   <li> Otherwise return {@link jogamp.nativewindow.NullToolkitLock} </li>
+     *   <li> Otherwise return {@link #getNullToolkitLock()} </li>
      * </ul>
      */
     public static ToolkitLock getDefaultToolkitLock(String type) {
@@ -363,18 +377,9 @@ public abstract class NativeWindowFactory {
         return NativeWindowFactoryImpl.getNullToolkitLock();
     }
 
-    private static ToolkitLock getAWTToolkitLock() {
-        Object resO = ReflectionUtil.callMethod(null, jawtUtilGetJAWTToolkitMethod);
-
-        if(DEBUG) {
-            System.err.println("NativeWindowFactory.getAWTToolkitLock()");
-            Thread.dumpStack();
-        }            
-        if(resO instanceof ToolkitLock) {
-            return (ToolkitLock) resO;
-        } else {
-            throw new RuntimeException("JAWTUtil.getJAWTToolkitLock() didn't return a ToolkitLock");
-        }
+    /** Returns the AWT Toolkit (JAWT based) if {@link #isAWTAvailable}, otherwise null. */ 
+    public static ToolkitLock getAWTToolkitLock() {
+        return jawtUtilJAWTToolkitLock;
     }
 
     public static ToolkitLock getNullToolkitLock() {
@@ -444,7 +449,7 @@ public abstract class NativeWindowFactory {
         try {
             if(DEBUG) {
                 System.err.println("NativeWindowFactory.createX11AWTToolkitLock(0x"+Long.toHexString(deviceHandle)+")");
-                Thread.dumpStack();
+                // Thread.dumpStack();
             }            
             return (ToolkitLock) x11JAWTToolkitLockConstructor.newInstance(new Object[]{new Long(deviceHandle)});
         } catch (Exception ex) {
diff --git a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java
index 9100bea..6a36bb1 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/ProxySurface.java
@@ -28,15 +28,20 @@
 
 package javax.media.nativewindow;
 
+
+import jogamp.nativewindow.Debug;
 import jogamp.nativewindow.SurfaceUpdatedHelper;
 
 import com.jogamp.common.util.locks.LockFactory;
 import com.jogamp.common.util.locks.RecursiveLock;
 
 public abstract class ProxySurface implements NativeSurface {
+    public static final boolean DEBUG = Debug.debug("ProxySurface");
+    
     private SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper();
     private AbstractGraphicsConfiguration config; // control access due to delegation
     protected RecursiveLock surfaceLock = LockFactory.createRecursiveLock();
+    private long surfaceHandle_old;
     protected long displayHandle;
     protected int height;
     protected int scrnIndex;
@@ -46,6 +51,7 @@ public abstract class ProxySurface implements NativeSurface {
         invalidate();
         config = cfg;
         displayHandle=cfg.getNativeGraphicsConfiguration().getScreen().getDevice().getHandle();
+        surfaceHandle_old = 0;
     }
 
     void invalidate() {
@@ -115,6 +121,13 @@ public abstract class ProxySurface implements NativeSurface {
                 adevice.lock();
                 try {
                     res = lockSurfaceImpl();
+                    if(LOCK_SUCCESS == res && surfaceHandle_old != getSurfaceHandle()) {
+                        res = LOCK_SURFACE_CHANGED;
+                        if(DEBUG) {            
+                            System.err.println("ProxySurface: surface change 0x"+Long.toHexString(surfaceHandle_old)+" -> 0x"+Long.toHexString(getSurfaceHandle()));
+                            // Thread.dumpStack();
+                        }
+                    }                    
                 } finally {
                     if (LOCK_SURFACE_NOT_READY >= res) {
                         adevice.unlock();
@@ -131,6 +144,7 @@ public abstract class ProxySurface implements NativeSurface {
 
     public final void unlockSurface() {
         surfaceLock.validateLocked();
+        surfaceHandle_old = getSurfaceHandle();
 
         if (surfaceLock.getHoldCount() == 1) {
             final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice();
diff --git a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java
index 982ce46..30f9660 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/ToolkitLock.java
@@ -29,7 +29,6 @@
 package javax.media.nativewindow;
 
 import jogamp.nativewindow.Debug;
-import java.security.AccessController;
 
 /**
  * Marker for a singleton global recursive blocking lock implementation,
@@ -38,7 +37,7 @@ import java.security.AccessController;
  * One use case is the AWT locking on X11, see {@link jogamp.nativewindow.jawt.JAWTToolkitLock}.
  */
 public interface ToolkitLock {
-    public static final boolean TRACE_LOCK = Debug.isPropertyDefined("nativewindow.debug.ToolkitLock.TraceLock", true, AccessController.getContext());
+    public static final boolean TRACE_LOCK = Debug.isPropertyDefined("nativewindow.debug.ToolkitLock.TraceLock", true);
 
     public void lock();
     public void unlock();
diff --git a/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java
new file mode 100644
index 0000000..4f3d3ff
--- /dev/null
+++ b/src/nativewindow/classes/javax/media/nativewindow/VisualIDHolder.java
@@ -0,0 +1,135 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ *
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ *
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package javax.media.nativewindow;
+
+import java.util.Comparator;
+
+/**
+ * Visual ID holder interface.
+ * <p>
+ * Allows queries of different types of native visual IDs,
+ * see {@link #getVisualID(int)}.
+ * </p>
+ */
+public interface VisualIDHolder {
+    
+    public enum VIDType {
+        // Generic Values
+        INTRINSIC(0), NATIVE(1),
+        // EGL Values
+        EGL_CONFIG(10),
+        // X11 Values
+        X11_XVISUAL(20), X11_FBCONFIG(21),
+        // Windows Values
+        WIN32_PFD(30); 
+        
+        public final int id;
+
+        VIDType(int id){
+            this.id = id;
+        }
+    }    
+    
+    /**
+     * Returns the native visual ID of the given <code>type</code>
+     * if supported, or {@link #VID_UNDEFINED} if not supported.
+     * <p> 
+     * Depending on the native windowing system, <code>type</code> is handled as follows:
+     * <ul>
+     *   <li>X11 throws NativeWindowException on <code>EGL_CONFIG</code>, <code>WIN32_PFD</code>
+     *     <ul>
+     *       <li><code>INTRINSIC</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>NATIVE</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>X11_XVISUAL</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>X11_FBCONFIG</code>: <code>VID_UNDEFINED</code></li>
+     *     </ul></li>
+     *   <li>X11/GL throws NativeWindowException on <code>EGL_CONFIG</code>, <code>WIN32_PFD</code>
+     *     <ul>
+     *       <li><code>INTRINSIC</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>NATIVE</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>X11_XVISUAL</code>: <i>X11 XVisual ID</i></li>
+     *       <li><code>X11_FBCONFIG</code>: <i>X11 FBConfig ID</i> or <code>VID_UNDEFINED</code></li>
+     *     </ul></li>
+     *   <li>Windows/GL throws NativeWindowException on <code>EGL_CONFIG</code>, <code>X11_XVISUAL</code>, <code>X11_FBCONFIG</code> 
+     *     <ul>
+     *       <li><code>INTRINSIC</code>: <i>Win32 PIXELFORMATDESCRIPTOR ID</i></li>
+     *       <li><code>NATIVE</code>: <i>Win32 PIXELFORMATDESCRIPTOR ID</i></li>
+     *       <li><code>WIN32_PFD</code>: <i>Win32 PIXELFORMATDESCRIPTOR ID</i></li>
+     *     </ul></li>
+     *   <li>EGL/GL throws NativeWindowException on <code>X11_XVISUAL</code>, <code>X11_FBCONFIG</code>, <code>WIN32_PFD</code>
+     *     <ul>
+     *       <li><code>INTRINSIC</code>: <i>EGL Config ID</i></li>
+     *       <li><code>NATIVE</code>: <i>EGL NativeVisual ID</i> (<i>X11 XVisual ID</i>, <i>Win32 PIXELFORMATDESCRIPTOR ID</i>, ...)</li>
+     *       <li><code>EGL_CONFIG</code>: <i>EGL Config ID</i></li>
+     *     </ul></li>
+     * </ul>
+     * </p>
+     * Note: <code>INTRINSIC</code> and <code>NATIVE</code> are always handled,
+     *       but may result in {@link #VID_UNDEFINED}. The latter is true if 
+     *       the native value are actually undefined or the corresponding object is not 
+     *       mapped to a native visual object.
+     *       
+     * @throws NativeWindowException if <code>type</code> is neither
+     *         <code>INTRINSIC</code> nor <code>NATIVE</code>
+     *         and does not match the native implementation. 
+     */
+    int getVisualID(VIDType type) throws NativeWindowException ;
+    
+    /** 
+     * {@link #getVisualID(VIDType)} result indicating an undefined value,
+     * which could be cause by an unsupported query.
+     * <p>
+     * We assume the const value <code>0</code> doesn't reflect a valid native visual ID
+     * and is interpreted as <i>no value</i> on all platforms.
+     * This is currently true for Android, X11 and Windows.
+     * </p> 
+     */
+    static final int VID_UNDEFINED = 0;
+    
+    /** Comparing {@link VIDType#NATIVE} */
+    public static class VIDComparator implements Comparator<VisualIDHolder> {
+        private VIDType type;
+        
+        public VIDComparator(VIDType type) {
+            this.type = type;
+        }
+        
+        public int compare(VisualIDHolder vid1, VisualIDHolder vid2) {
+            final int id1 = vid1.getVisualID(type);
+            final int id2 = vid2.getVisualID(type);
+
+            if(id1 > id2) {
+                return 1;
+            } else if(id1 < id2) {
+                return -1;
+            }
+            return 0;
+        }
+    }    
+}
diff --git a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java
index 949aee7..884c916 100644
--- a/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java
+++ b/src/nativewindow/classes/javax/media/nativewindow/WindowClosingProtocol.java
@@ -32,35 +32,38 @@ package javax.media.nativewindow;
  * Protocol for handling window closing events.
  * <p>
  * The implementation shall obey either the user value set by this interface,<br>
- * an underlying toolkit set user value or it's default, eg. {@link #DO_NOTHING_ON_CLOSE DO_NOTHING_ON_CLOSE} within an AWT environment.<br>
+ * an underlying toolkit set user value or it's default, eg. {@link WindowClosingMode#DO_NOTHING_ON_CLOSE DO_NOTHING_ON_CLOSE} within an AWT environment.<br>
  * If none of the above determines the operation,
- * this protocol default behavior {@link #DISPOSE_ON_CLOSE DISPOSE_ON_CLOSE} shall be used.</p>
+ * this protocol default behavior {@link WindowClosingMode#DISPOSE_ON_CLOSE DISPOSE_ON_CLOSE} shall be used.</p>
  */
 public interface WindowClosingProtocol {
-    /**
-     * Dispose resources on native window close operation.<br>
-     * This is the default behavior in case no underlying toolkit defines otherwise.
-     */
-    int DISPOSE_ON_CLOSE = 1;
+    public enum WindowClosingMode {
+        /**
+         * Do nothing on native window close operation.<br>
+         * This is the default behavior within an AWT environment.
+         */
+        DO_NOTHING_ON_CLOSE,
+        
+        /**
+         * Dispose resources on native window close operation.<br>
+         * This is the default behavior in case no underlying toolkit defines otherwise.
+         */
+        DISPOSE_ON_CLOSE;
+    }
 
-    /**
-     * Do nothing on native window close operation.<br>
-     * This is the default behavior within an AWT environment.
-     */
-    int DO_NOTHING_ON_CLOSE = 0;
 
     /**
      * @return the current close operation value
-     * @see #DISPOSE_ON_CLOSE
-     * @see #DO_NOTHING_ON_CLOSE
+     * @see WindowClosingMode#DISPOSE_ON_CLOSE
+     * @see WindowClosingMode#DO_NOTHING_ON_CLOSE
      */
-    int getDefaultCloseOperation();
+    WindowClosingMode getDefaultCloseOperation();
 
     /**
      * @param op the new close operation value
      * @return the previous close operation value
-     * @see #DISPOSE_ON_CLOSE
-     * @see #DO_NOTHING_ON_CLOSE
+     * @see WindowClosingMode#DISPOSE_ON_CLOSE
+     * @see WindowClosingMode#DO_NOTHING_ON_CLOSE
      */
-    int setDefaultCloseOperation(int op);
+    WindowClosingMode setDefaultCloseOperation(WindowClosingMode op);
 }
diff --git a/src/nativewindow/classes/jogamp/nativewindow/Debug.java b/src/nativewindow/classes/jogamp/nativewindow/Debug.java
index f1cd209..e07fd1b 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/Debug.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/Debug.java
@@ -39,18 +39,18 @@
 
 package jogamp.nativewindow;
 
-import java.security.*;
+import com.jogamp.common.util.PropertyAccess;
 
 /** Helper routines for logging and debugging. */
 
-public class Debug {
+public class Debug extends PropertyAccess {
   // Some common properties
-  private static boolean verbose;
-  private static boolean debugAll;
-  private static AccessControlContext localACC;
+  private static final boolean verbose;
+  private static final boolean debugAll;
   
   static {
-    localACC=AccessController.getContext();
+    PropertyAccess.addTrustedPrefix("nativewindow.", Debug.class);
+
     verbose = isPropertyDefined("nativewindow.verbose", true);
     debugAll = isPropertyDefined("nativewindow.debug", true);
     if (verbose) {
@@ -61,71 +61,18 @@ public class Debug {
     }
   }
 
-  static int getIntProperty(final String property, final boolean jnlpAlias) {
-      return getIntProperty(property, jnlpAlias, localACC);
-  }
-
-  public static int getIntProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    int i=0;
-    try {
-        Integer iv = Integer.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-        i = iv.intValue();
-    } catch (NumberFormatException nfe) {}
-    return i;
-  }
-
-  static boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
-    return getBooleanProperty(property, jnlpAlias, localACC);
+  public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
+    return PropertyAccess.isPropertyDefined(property, jnlpAlias, null);
   }
-
-  public static boolean getBooleanProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    Boolean b = Boolean.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-    return b.booleanValue();
+    
+  public static String getProperty(final String property, final boolean jnlpAlias) {
+    return PropertyAccess.getProperty(property, jnlpAlias, null);
   }
-
-  static boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
-    return isPropertyDefined(property, jnlpAlias, localACC);
+    
+  public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
+      return PropertyAccess.getBooleanProperty(property, jnlpAlias, null);
   }
-
-  public static boolean isPropertyDefined(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    return (Debug.getProperty(property, jnlpAlias, acc) != null) ? true : false;
-  }
-
-  static String getProperty(final String property, final boolean jnlpAlias) {
-    return getProperty(property, jnlpAlias, localACC);
-  }
-
-  public static String getProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    String s=null;
-    if(null!=acc && acc.equals(localACC)) {
-        s = (String) AccessController.doPrivileged(new PrivilegedAction() {
-            public Object run() {
-              String val=null;
-              try {
-                  val = System.getProperty(property);
-              } catch (Exception e) {}
-              if(null==val && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-                  try {
-                      val = System.getProperty(jnlp_prefix + property);
-                  } catch (Exception e) {}
-              }
-              return val;
-            }
-          });
-    } else {
-        try {
-            s = System.getProperty(property);
-        } catch (Exception e) {}
-        if(null==s && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-            try {
-                s = System.getProperty(jnlp_prefix + property);
-            } catch (Exception e) {}
-        }
-    }
-    return s;
-  }
-  public static final String jnlp_prefix = "jnlp." ;
-
+    
   public static boolean verbose() {
     return verbose;
   }
diff --git a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java
index 4cf8f44..be41ad7 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/NWJNILibLoader.java
@@ -38,18 +38,17 @@ import com.jogamp.common.util.cache.TempJarCache;
 
 public class NWJNILibLoader extends JNILibLoaderBase {
   
-  public static void loadNativeWindow(final String ossuffix) {
-    AccessController.doPrivileged(new PrivilegedAction<Object>() {
-      public Object run() {
+  public static boolean loadNativeWindow(final String ossuffix) {
+    return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+      public Boolean run() {
         Platform.initSingleton();
         final String libName = "nativewindow_"+ossuffix ;
         if(TempJarCache.isInitialized() && null == TempJarCache.findLibrary(libName)) {
             addNativeJarLibs(NWJNILibLoader.class, "jogl-all", new String[] { "nativewindow" } );
         }
-        loadLibrary(libName, false);
-        return null;
+        return new Boolean(loadLibrary(libName, false));
       }
-    });
+    }).booleanValue();
   }
 
 }
diff --git a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java
index 223078e..9e18439 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/NativeWindowFactoryImpl.java
@@ -41,6 +41,7 @@ import javax.media.nativewindow.ToolkitLock;
 
 import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.ReflectionUtil;
+import com.jogamp.common.util.ReflectionUtil.AWTNames;
 
 public class NativeWindowFactoryImpl extends NativeWindowFactory {
     private static final ToolkitLock nullToolkitLock = new NullToolkitLock();
@@ -61,13 +62,13 @@ public class NativeWindowFactoryImpl extends NativeWindowFactory {
             throw new IllegalArgumentException("AbstractGraphicsConfiguration is null with a non NativeWindow object");
         }
 
-        if (NativeWindowFactory.isAWTAvailable() && ReflectionUtil.instanceOf(winObj, AWTComponentClassName)) {
+        if (NativeWindowFactory.isAWTAvailable() && ReflectionUtil.instanceOf(winObj, AWTNames.ComponentClass)) {
             return getAWTNativeWindow(winObj, config);
         }
 
         throw new IllegalArgumentException("Target window object type " +
                                            winObj.getClass().getName() + " is unsupported; expected " +
-                                           "javax.media.nativewindow.NativeWindow or "+AWTComponentClassName);
+                                           "javax.media.nativewindow.NativeWindow or "+AWTNames.ComponentClass);
     }
     
     private Constructor<?> nativeWindowConstructor = null;
diff --git a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java
index 834d8a7..d77cd75 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/awt/AWTMisc.java
@@ -75,22 +75,22 @@ public class AWTMisc {
         MenuSelectionManager.defaultManager().clearSelectedPath();
     }
 
-    public static int AWT2NWClosingOperation(int awtClosingOperation) {
+    public static WindowClosingProtocol.WindowClosingMode AWT2NWClosingOperation(int awtClosingOperation) {
         switch (awtClosingOperation) {
             case WindowConstants.DISPOSE_ON_CLOSE:
             case WindowConstants.EXIT_ON_CLOSE:
-                return WindowClosingProtocol.DISPOSE_ON_CLOSE;
+                return WindowClosingProtocol.WindowClosingMode.DISPOSE_ON_CLOSE;
             case WindowConstants.DO_NOTHING_ON_CLOSE:
             case WindowConstants.HIDE_ON_CLOSE:
-                return WindowClosingProtocol.DO_NOTHING_ON_CLOSE;
+                return WindowClosingProtocol.WindowClosingMode.DO_NOTHING_ON_CLOSE;
             default:
                 throw new NativeWindowException("Unhandled AWT Closing Operation: " + awtClosingOperation);
         }
     }
 
-    public static int getNWClosingOperation(Component c) {
-        JFrame jf = getJFrame(c);
-        int op = (null != jf) ? jf.getDefaultCloseOperation() : WindowConstants.DO_NOTHING_ON_CLOSE ;
+    public static WindowClosingProtocol.WindowClosingMode getNWClosingOperation(Component c) {
+        final JFrame jf = getJFrame(c);
+        final int op = (null != jf) ? jf.getDefaultCloseOperation() : WindowConstants.DO_NOTHING_ON_CLOSE ;
         return AWT2NWClosingOperation(op);
     }
 }
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTToolkitLock.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTToolkitLock.java
deleted file mode 100644
index 37e34c0..0000000
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTToolkitLock.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Copyright 2010 JogAmp Community. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- *
- *    1. Redistributions of source code must retain the above copyright notice, this list of
- *       conditions and the following disclaimer.
- *
- *    2. Redistributions in binary form must reproduce the above copyright notice, this list
- *       of conditions and the following disclaimer in the documentation and/or other materials
- *       provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * The views and conclusions contained in the software and documentation are those of the
- * authors and should not be interpreted as representing official policies, either expressed
- * or implied, of JogAmp Community.
- */
-package jogamp.nativewindow.jawt;
-
-import javax.media.nativewindow.ToolkitLock;
-
-/**
- * Implementing a singleton global recursive {@link javax.media.nativewindow.ToolkitLock}
- * utilizing JAWT's AWT lock via {@link JAWTUtil#lockToolkit()}.
- * <br>
- * This strategy should only be used if AWT is using the underlying native windowing toolkit
- * in a not intrinsic thread safe manner, e.g. under X11 where no XInitThreads() call
- * is issued before any other X11 usage. This is the current situation for e.g. Webstart or Applets.
- */
-public class JAWTToolkitLock implements ToolkitLock {
-
-    /** Singleton via {@link JAWTUtil#getJAWTToolkitLock()} */
-    protected JAWTToolkitLock() {}
-
-    public final void lock() {
-        if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.lock()"); }
-        JAWTUtil.lockToolkit();
-    }
-
-    public final void unlock() {
-        if(TRACE_LOCK) { System.err.println("JAWTToolkitLock.unlock()"); }
-        JAWTUtil.unlockToolkit();
-    }
-}
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java
index 21e9a3e..8098bdb 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/JAWTUtil.java
@@ -48,14 +48,25 @@ import java.util.ArrayList;
 import java.util.Map;
 
 import javax.media.nativewindow.NativeWindowException;
+import javax.media.nativewindow.ToolkitLock;
 
 import jogamp.nativewindow.Debug;
 
 import com.jogamp.common.os.Platform;
+import com.jogamp.common.util.VersionNumber;
 
 public class JAWTUtil {
-  protected static final boolean DEBUG = Debug.debug("JAWT");
+  public static final boolean DEBUG = Debug.debug("JAWT");
 
+  /** OSX JAWT version option to use CALayer */
+  public static final int JAWT_MACOSX_USE_CALAYER = 0x80000000;
+  
+  /** OSX JAWT CALayer availability on Mac OS X >= 10.6 Update 4 (recommended) */
+  public static final VersionNumber JAWT_MacOSXCALayerMinVersion = new VersionNumber(10,6,4);
+  
+  /** OSX JAWT CALayer required with Java >= 1.7.0 (implies OS X >= 10.7  */
+  public static final VersionNumber JAWT_MacOSXCALayerRequiredForJavaVersion = new VersionNumber(1,7,0);
+  
   // See whether we're running in headless mode
   private static final boolean headlessMode;
   private static final JAWT jawtLockObject;
@@ -68,7 +79,7 @@ public class JAWTUtil {
   private static final Method  sunToolkitAWTUnlockMethod;
   private static final boolean hasSunToolkitAWTLock;
 
-  private static final JAWTToolkitLock jawtToolkitLock;
+  private static final ToolkitLock jawtToolkitLock;
 
   private static class PrivilegedDataBlob1 {
     PrivilegedDataBlob1() {
@@ -80,12 +91,19 @@ public class JAWTUtil {
   }
   
   /**
-   * Returns true if this platform's JAWT implementation supports 
-   * or uses offscreen layer.
+   * Returns true if this platform's JAWT implementation supports offscreen layer.
    */
   public static boolean isOffscreenLayerSupported() {
        return Platform.OS_TYPE == Platform.OSType.MACOS &&
-              Platform.OS_VERSION_NUMBER.compareTo(JAWT.JAWT_MacOSXCALayerMinVersion) >= 0;      
+              Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0;      
+  }
+ 
+  /**
+   * Returns true if this platform's JAWT implementation requires using offscreen layer.
+   */
+  public static boolean isOffscreenLayerRequired() {
+       return Platform.OS_TYPE == Platform.OSType.MACOS &&
+              Platform.JAVA_VERSION_NUMBER.compareTo(JAWT_MacOSXCALayerRequiredForJavaVersion)>=0;
   }
  
   /**
@@ -93,20 +111,56 @@ public class JAWTUtil {
    * @return
    */
   public static JAWT getJAWT(boolean useOffscreenLayerIfAvailable) {
-    int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4;
-    if(useOffscreenLayerIfAvailable) {
-        switch(Platform.OS_TYPE) {
-            case MACOS:
-                if(Platform.OS_VERSION_NUMBER.compareTo(JAWT.JAWT_MacOSXCALayerMinVersion) >= 0) {
-                    jawt_version_flags |= JAWT.JAWT_MACOSX_USE_CALAYER;
-                }
+    final int jawt_version_flags = JAWTFactory.JAWT_VERSION_1_4;    
+    JAWT jawt = JAWT.create();
+    
+    // default queries
+    boolean tryOffscreenLayer = false;
+    boolean tryOnscreenLayer = true;
+    int jawt_version_flags_offscreen = jawt_version_flags;
+    
+    if(isOffscreenLayerRequired()) {
+        if(Platform.OS_TYPE == Platform.OSType.MACOS) {
+            if(Platform.OS_VERSION_NUMBER.compareTo(JAWTUtil.JAWT_MacOSXCALayerMinVersion) >= 0) {
+                jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER;
+                tryOffscreenLayer = true;
+                tryOnscreenLayer = false;            
+            } else {
+                throw new RuntimeException("OSX: Invalid version of Java ("+Platform.JAVA_VERSION_NUMBER+") / OS X ("+Platform.OS_VERSION_NUMBER+")");
+            }
+        } else {
+            throw new InternalError("offscreen required, but n/a for: "+Platform.OS_TYPE);
+        }
+    } else if(useOffscreenLayerIfAvailable && isOffscreenLayerSupported()) {
+        if(Platform.OS_TYPE == Platform.OSType.MACOS) {
+            jawt_version_flags_offscreen |= JAWTUtil.JAWT_MACOSX_USE_CALAYER;
+            tryOffscreenLayer = true;
+        } else {
+            throw new InternalError("offscreen requested and supported, but n/a for: "+Platform.OS_TYPE);
         }
     }
-    return JAWT.getJAWT(jawt_version_flags);
+    
+    StringBuilder errsb = new StringBuilder();
+    if(tryOffscreenLayer) {
+        errsb.append("Offscreen 0x").append(Integer.toHexString(jawt_version_flags_offscreen));
+        if( JAWT.getJAWT(jawt, jawt_version_flags_offscreen) ) {
+            return jawt;
+        }
+    }
+    if(tryOnscreenLayer) {
+        if(tryOffscreenLayer) {
+            errsb.append(", ");
+        }
+        errsb.append("Onscreen 0x").append(Integer.toHexString(jawt_version_flags));
+        if( JAWT.getJAWT(jawt, jawt_version_flags) ) {
+            return jawt;
+        }        
+    }
+    throw new RuntimeException("Unable to initialize JAWT, trials: "+errsb.toString());
   }
   
   public static boolean isJAWTUsingOffscreenLayer(JAWT jawt) {
-      return 0 != ( jawt.getCachedVersion() & JAWT.JAWT_MACOSX_USE_CALAYER );
+      return 0 != ( jawt.getCachedVersion() & JAWTUtil.JAWT_MACOSX_USE_CALAYER );
   }
   
   static {
@@ -115,7 +169,9 @@ public class JAWTUtil {
         // Thread.dumpStack();
     }
     JAWTJNILibLoader.initSingleton();
-    JAWTJNILibLoader.loadNativeWindow("awt");
+    if(!JAWTJNILibLoader.loadNativeWindow("awt")) {
+        throw new NativeWindowException("NativeWindow AWT native library load error.");
+    }
 
     headlessMode = GraphicsEnvironment.isHeadless();
     boolean ok = false;
@@ -166,7 +222,14 @@ public class JAWTUtil {
     hasSunToolkitAWTLock = _hasSunToolkitAWTLock;
     // hasSunToolkitAWTLock = false;
 
-    jawtToolkitLock = new JAWTToolkitLock();
+    jawtToolkitLock = new ToolkitLock() {
+          public final void lock() {
+              JAWTUtil.lockToolkit();
+          }    
+          public final void unlock() {
+              JAWTUtil.unlockToolkit();
+          }
+      };  
 
     // trigger native AWT toolkit / properties initialization
     Map<?,?> desktophints = null;
@@ -260,19 +323,22 @@ public class JAWTUtil {
   }
 
   public static void lockToolkit() throws NativeWindowException {
+    if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.lock()"); }
     if(!headlessMode && !isJava2DQueueFlusherThread()) {
         awtLock();
     }
   }
 
   public static void unlockToolkit() {
+    if(ToolkitLock.TRACE_LOCK) { System.err.println("JAWTUtil-ToolkitLock.unlock()"); }
     if(!headlessMode && !isJava2DQueueFlusherThread()) {
         awtUnlock();
     }
   }
 
-  public static JAWTToolkitLock getJAWTToolkitLock() {
+  public static ToolkitLock getJAWTToolkitLock() {
     return jawtToolkitLock;
   }
+  
 }
 
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java
index ab2986f..0ca5cd2 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/macosx/MacOSXJAWTWindow.java
@@ -51,13 +51,15 @@ import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.SurfaceChangeable;
 import javax.media.nativewindow.util.Point;
 
-import jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.MutableGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.JAWTWindow;
+
 import jogamp.nativewindow.jawt.JAWT;
 import jogamp.nativewindow.jawt.JAWTFactory;
 import jogamp.nativewindow.jawt.JAWTUtil;
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurface;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurfaceInfo;
+import jogamp.nativewindow.jawt.macosx.JAWT_MacOSXDrawingSurfaceInfo;
 import jogamp.nativewindow.macosx.OSXUtil;
 
 public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
@@ -71,6 +73,10 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
   protected void invalidateNative() {
       surfaceHandle=0;
       if(isOffscreenLayerSurfaceEnabled()) {
+          if(0 != rootSurfaceLayerHandle) {
+              OSXUtil.DestroyCALayer(rootSurfaceLayerHandle);
+              rootSurfaceLayerHandle = 0;
+          }
           if(0 != drawable) {
               OSXUtil.DestroyNSWindow(drawable);
               drawable = 0;
@@ -208,7 +214,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
               unlockSurfaceImpl();
               throw new NativeWindowException("Could not create root CALayer: "+this);                
             }
-            if(!AttachJAWTSurfaceLayer(dsi, rootSurfaceLayerHandle)) {
+            if(!AttachJAWTSurfaceLayer0(dsi.getBuffer(), rootSurfaceLayerHandle)) {
               OSXUtil.DestroyCALayer(rootSurfaceLayerHandle);
               rootSurfaceLayerHandle = 0;
               OSXUtil.DestroyNSWindow(drawable);
@@ -239,14 +245,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
 
   private void dumpInfo() {
       System.err.println("MaxOSXJAWTWindow: 0x"+Integer.toHexString(this.hashCode())+" - thread: "+Thread.currentThread().getName());
-      if(null != getJAWT()) {
-          System.err.println("JAWT version: 0x"+Integer.toHexString(getJAWT().getCachedVersion())+
-                             ", CA_LAYER: "+ JAWTUtil.isJAWTUsingOffscreenLayer(getJAWT())+
-                             ", isLayeredSurface "+isOffscreenLayerSurfaceEnabled()+", bounds "+bounds+", insets "+insets);
-      } else {
-          System.err.println("JAWT n/a, bounds "+bounds+", insets "+insets);          
-      }
-      // Thread.dumpStack();
+      dumpJAWTInfo();
   }
   
   /**
@@ -268,14 +267,8 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
   }  
   protected Point getLocationOnScreenNativeImpl(final int x0, final int y0) { return null; }
 
-  private static boolean AttachJAWTSurfaceLayer(JAWT_DrawingSurfaceInfo dsi, long caLayer) {
-    if(0==caLayer) {
-        throw new IllegalArgumentException("caLayer 0x"+Long.toHexString(caLayer));
-    }
-    return AttachJAWTSurfaceLayer0(dsi.getBuffer(), caLayer);
-  }
-    
   private static native boolean AttachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer);
+  // private static native boolean DetachJAWTSurfaceLayer0(Buffer jawtDrawingSurfaceInfoBuffer, long caLayer);
   
   // Variables for lockSurface/unlockSurface
   private JAWT_DrawingSurface ds;
@@ -284,7 +277,7 @@ public class MacOSXJAWTWindow extends JAWTWindow implements SurfaceChangeable {
   
   private JAWT_MacOSXDrawingSurfaceInfo macosxdsi;
   
-  private long rootSurfaceLayerHandle = 0; // is autoreleased, once it is attached to the JAWT_SurfaceLayer
+  private long rootSurfaceLayerHandle = 0; // attached to the JAWT_SurfaceLayer
   
   private long surfaceHandle = 0;
   private int sscWidth, sscHeight;
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java
index bf5c18e..74dabb6 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/Win32SunJDKReflection.java
@@ -48,7 +48,9 @@ import java.security.AccessController;
 import java.security.PrivilegedAction;
 
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
+
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+
 
 /** This class encapsulates the reflection routines necessary to peek
     inside a few data structures in the AWT implementation on X11 for
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java
index 43d4469..5d1d437 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/windows/WindowsJAWTWindow.java
@@ -45,10 +45,11 @@ import javax.media.nativewindow.NativeWindow;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.util.Point;
 
+import com.jogamp.nativewindow.awt.JAWTWindow;
+
 import jogamp.nativewindow.jawt.JAWT;
 import jogamp.nativewindow.jawt.JAWTFactory;
 import jogamp.nativewindow.jawt.JAWTUtil;
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurface;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurfaceInfo;
 import jogamp.nativewindow.windows.GDIUtil;
@@ -117,6 +118,7 @@ public class WindowsJAWTWindow extends JAWTWindow {
   }
 
   protected void unlockSurfaceImpl() throws NativeWindowException {
+    drawable = 0; // invalid HDC
     if(null!=ds) {
         if (null!=dsi) {
             ds.FreeDrawingSurfaceInfo(dsi);
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java
index 35dc234..736718d 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11JAWTWindow.java
@@ -42,10 +42,11 @@ import javax.media.nativewindow.NativeWindow;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.util.Point;
 
+import com.jogamp.nativewindow.awt.JAWTWindow;
+
 import jogamp.nativewindow.jawt.JAWT;
 import jogamp.nativewindow.jawt.JAWTFactory;
 import jogamp.nativewindow.jawt.JAWTUtil;
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurface;
 import jogamp.nativewindow.jawt.JAWT_DrawingSurfaceInfo;
 import jogamp.nativewindow.x11.X11Lib;
diff --git a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java
index 08d4714..27e0a5e 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/jawt/x11/X11SunJDKReflection.java
@@ -48,7 +48,9 @@ import java.security.AccessController;
 import java.security.PrivilegedAction;
 
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
+
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+
 
 /** This class encapsulates the reflection routines necessary to peek
     inside a few data structures in the AWT implementation on X11 for
diff --git a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java
index 5b1e4b0..3ca76a8 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/macosx/OSXUtil.java
@@ -39,7 +39,9 @@ public class OSXUtil {
     
     public static synchronized void initSingleton(boolean firstX11ActionOnProcess) {
       if(!isInit) {
-          NWJNILibLoader.loadNativeWindow("macosx");
+          if(!NWJNILibLoader.loadNativeWindow("macosx")) {
+              throw new NativeWindowException("NativeWindow MacOSX native library load error.");
+          }
           
           if( !initIDs0() ) {
               throw new NativeWindowException("MacOSX: Could not initialized native stub");
diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java
index 090ece5..bc02ac5 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDISurface.java
@@ -30,9 +30,9 @@ package jogamp.nativewindow.windows;
 
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
 import javax.media.nativewindow.NativeWindowException;
-
 import javax.media.nativewindow.ProxySurface;
 
+
 /**
  * GDI Surface implementation which wraps an existing window handle
  * allowing the use of HDC via lockSurface()/unlockSurface() protocol.
@@ -56,7 +56,7 @@ public class GDISurface extends ProxySurface {
     surfaceHandle=0;
   }
 
-  protected int lockSurfaceImpl() {
+  final protected int lockSurfaceImpl() {
     if (0 != surfaceHandle) {
         throw new InternalError("surface not released");
     }
@@ -70,7 +70,7 @@ public class GDISurface extends ProxySurface {
     return (0 != surfaceHandle) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY;
   }
 
-  protected void unlockSurfaceImpl() {
+  final protected void unlockSurfaceImpl() {
     if (0 == surfaceHandle) {
         throw new InternalError("surface not acquired: "+this+", thread: "+Thread.currentThread().getName());
     }
@@ -80,16 +80,17 @@ public class GDISurface extends ProxySurface {
     surfaceHandle=0;
   }
 
-  public long getSurfaceHandle() {
+  final public long getSurfaceHandle() {
     return surfaceHandle;
   }
 
-  public String toString() {
+  final public String toString() {
     return "GDISurface[config "+getPrivateGraphicsConfiguration()+
                 ", displayHandle 0x"+Long.toHexString(getDisplayHandle())+
                 ", windowHandle 0x"+Long.toHexString(windowHandle)+
                 ", surfaceHandle 0x"+Long.toHexString(getSurfaceHandle())+
-                ", size "+getWidth()+"x"+getHeight()+"]";
+                ", size "+getWidth()+"x"+getHeight()+
+                ", surfaceLock "+surfaceLock+"]";
   }
 
 }
diff --git a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java
index be531d9..d17a189 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/windows/GDIUtil.java
@@ -46,7 +46,9 @@ public class GDIUtil {
             synchronized(X11Util.class) {
                 if(!isInit) {
                     isInit = true;
-                    NWJNILibLoader.loadNativeWindow("win32");
+                    if(!NWJNILibLoader.loadNativeWindow("win32")) {
+                        throw new NativeWindowException("NativeWindow Windows native library load error.");
+                    }
 
                     if( !initIDs0() ) {
                         throw new NativeWindowException("GDI: Could not initialized native stub");
diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java
new file mode 100644
index 0000000..0e69c73
--- /dev/null
+++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Capabilities.java
@@ -0,0 +1,87 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ *
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ *
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package jogamp.nativewindow.x11;
+
+import javax.media.nativewindow.Capabilities;
+import javax.media.nativewindow.NativeWindowException;
+import javax.media.nativewindow.VisualIDHolder;
+
+public class X11Capabilities extends Capabilities {
+  final private XVisualInfo xVisualInfo; // maybe null if !onscreen
+
+  public X11Capabilities(XVisualInfo xVisualInfo) {
+      super();
+      this.xVisualInfo = xVisualInfo;
+  }
+
+  public Object cloneMutable() {
+    return clone();
+  }
+
+  public Object clone() {
+    try {
+      return super.clone();
+    } catch (RuntimeException e) {
+      throw new NativeWindowException(e);
+    }
+  }
+
+  final public XVisualInfo getXVisualInfo() { return xVisualInfo; }
+  final public int getXVisualID() { return (null!=xVisualInfo) ? (int) xVisualInfo.getVisualid() : VisualIDHolder.VID_UNDEFINED; }
+  final public boolean hasXVisualInfo() { return null!=xVisualInfo; }
+
+  @Override
+  final public int getVisualID(VIDType type) throws NativeWindowException {
+      switch(type) {
+          case INTRINSIC:
+          case NATIVE:
+              // fall through intended
+          case X11_XVISUAL:
+              return getXVisualID();
+          case X11_FBCONFIG:
+              return VisualIDHolder.VID_UNDEFINED;
+          default:
+              throw new NativeWindowException("Invalid type <"+type+">");
+      }      
+  }
+  
+  public StringBuilder toString(StringBuilder sink) {
+    if(null == sink) {
+        sink = new StringBuilder();
+    }
+    sink.append("x11 vid ");
+    if(hasXVisualInfo()) {
+        sink.append("0x").append(Long.toHexString(xVisualInfo.getVisualid()));
+    } else {
+        sink.append(na_str);
+    }
+    sink.append(": ");
+    return super.toString(sink);
+  }
+}
\ No newline at end of file
diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java
index 2684162..070f872 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11GraphicsConfigurationFactory.java
@@ -39,12 +39,13 @@ import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
 import javax.media.nativewindow.NativeWindowException;
-import javax.media.nativewindow.x11.X11GraphicsConfiguration;
-import javax.media.nativewindow.x11.X11GraphicsScreen;
+
+import com.jogamp.nativewindow.x11.X11GraphicsConfiguration;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactory {
     public static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.x11.X11GraphicsDevice.class, new X11GraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.x11.X11GraphicsDevice.class, new X11GraphicsConfigurationFactory());
     }    
     private X11GraphicsConfigurationFactory() {
     }
@@ -56,7 +57,12 @@ public class X11GraphicsConfigurationFactory extends GraphicsConfigurationFactor
         if(!(screen instanceof X11GraphicsScreen)) {
             throw new NativeWindowException("Only valid X11GraphicsScreen are allowed");
         }
-        return new X11GraphicsConfiguration((X11GraphicsScreen)screen,  capsChosen, capsRequested, getXVisualInfo(screen, capsChosen));
+        final X11Capabilities x11CapsChosen = new X11Capabilities(getXVisualInfo(screen, capsChosen)); 
+        AbstractGraphicsConfiguration res = new X11GraphicsConfiguration((X11GraphicsScreen)screen,  x11CapsChosen, capsRequested, x11CapsChosen.getXVisualInfo());
+        if(DEBUG) {
+            System.err.println("X11GraphicsConfigurationFactory.chooseGraphicsConfigurationImpl("+screen+","+capsChosen+"): "+res);
+        }
+        return res;
     }
 
     public static XVisualInfo getXVisualInfo(AbstractGraphicsScreen screen, long visualID)
diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java
index 560130d..c42bcf8 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/x11/X11Util.java
@@ -33,7 +33,6 @@
 
 package jogamp.nativewindow.x11;
 
-import java.security.AccessController;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -83,7 +82,7 @@ public class X11Util {
     public static final boolean HAS_XLOCKDISPLAY_BUG = true;
     
     private static final boolean DEBUG = Debug.debug("X11Util");
-    private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.getBooleanProperty("nativewindow.debug.X11Util.TraceDisplayLifecycle", true, AccessController.getContext());
+    private static final boolean TRACE_DISPLAY_LIFECYCLE = Debug.getBooleanProperty("nativewindow.debug.X11Util.TraceDisplayLifecycle", true);
 
     private static String nullDisplayName = null;
     private static boolean isX11LockAvailable = false;
@@ -101,7 +100,9 @@ public class X11Util {
             synchronized(X11Util.class) {
                 if(!isInit) {
                     isInit = true;
-                    NWJNILibLoader.loadNativeWindow("x11");
+                    if(!NWJNILibLoader.loadNativeWindow("x11")) {
+                        throw new NativeWindowException("NativeWindow X11 native library load error.");
+                    }
         
                     final boolean callXInitThreads = XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess;
                     final boolean isXInitThreadsOK = initialize0( XINITTHREADS_ALWAYS_ENABLED || firstX11ActionOnProcess );
@@ -483,6 +484,38 @@ public class X11Util {
         }
     }
 
+    static volatile boolean XineramaFetched = false;
+    static long XineramaLibHandle = 0;
+    static long XineramaQueryFunc = 0;
+    
+    public static boolean XineramaIsEnabled(long display) {
+        if(0==display) {
+            throw new IllegalArgumentException("Display NULL");
+        }
+        if(!XineramaFetched) { // volatile: ok
+            synchronized(X11Util.class) {
+                if( !XineramaFetched ) {
+                    XineramaLibHandle = X11Lib.XineramaGetLibHandle();
+                    if(0 != XineramaLibHandle) {
+                        XineramaQueryFunc = X11Lib.XineramaGetQueryFunc(XineramaLibHandle);
+                    }
+                    XineramaFetched = true;
+                }
+            }
+        }
+        if(0!=XineramaQueryFunc) {
+            final boolean res = X11Lib.XineramaIsEnabled(XineramaQueryFunc, display);
+            if(DEBUG) {
+                System.err.println("XineramaIsEnabled: "+res);
+            }
+            return res;
+        } else if(DEBUG) {
+            System.err.println("XineramaIsEnabled: Couldn't bind to Xinerama - lib 0x"+Long.toHexString(XineramaLibHandle)+
+                               "query 0x"+Long.toHexString(XineramaQueryFunc));
+        }
+        return false;
+    }
+    
     private static native boolean initialize0(boolean firstUIActionOnProcess);
     private static native void shutdown0();
     private static native void setX11ErrorHandler0(boolean onoff, boolean quiet);
diff --git a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java
index efaf472..b6bf63d 100644
--- a/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java
+++ b/src/nativewindow/classes/jogamp/nativewindow/x11/awt/X11AWTGraphicsConfigurationFactory.java
@@ -42,15 +42,17 @@ import javax.media.nativewindow.AbstractGraphicsScreen;
 import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.nativewindow.ToolkitLock;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
-import javax.media.nativewindow.x11.X11GraphicsConfiguration;
-import javax.media.nativewindow.x11.X11GraphicsDevice;
-import javax.media.nativewindow.x11.X11GraphicsScreen;
+import javax.media.nativewindow.VisualIDHolder.VIDType;
+
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 
 import jogamp.nativewindow.jawt.x11.X11SunJDKReflection;
 import jogamp.nativewindow.x11.X11Lib;
@@ -59,7 +61,7 @@ import jogamp.nativewindow.x11.X11Util;
 public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFactory {
     
     public static void registerFactory() {
-        GraphicsConfigurationFactory.registerFactory(javax.media.nativewindow.awt.AWTGraphicsDevice.class, new X11AWTGraphicsConfigurationFactory());
+        GraphicsConfigurationFactory.registerFactory(com.jogamp.nativewindow.awt.AWTGraphicsDevice.class, new X11AWTGraphicsConfigurationFactory());
     }    
     private X11AWTGraphicsConfigurationFactory() {
     }
@@ -87,13 +89,14 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
         
         final GraphicsDevice device = ((AWTGraphicsDevice)awtScreen.getDevice()).getGraphicsDevice();
 
-        long displayHandle = X11SunJDKReflection.graphicsDeviceGetDisplay(device);
+        final long displayHandleAWT = X11SunJDKReflection.graphicsDeviceGetDisplay(device);
+        final long displayHandle;
         boolean owner = false;
-        if(0==displayHandle) {
+        if(0==displayHandleAWT) {
             displayHandle = X11Util.openDisplay(null);
             owner = true;
             if(DEBUG) {
-                System.err.println(Thread.currentThread().getName() + " - X11AWTGraphicsConfigurationFactory: create local X11 display");
+                System.err.println(getThreadName()+" - X11AWTGraphicsConfigurationFactory: Null AWT dpy, create local X11 display: "+toHexString(displayHandle));
             }
         } else {
             /**
@@ -102,12 +105,12 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
              * some work, but some behave erratic. 
              * I.e. hangs in XQueryExtension(..) via X11GraphicsScreen.
              */
-            final String displayName = X11Lib.XDisplayString(displayHandle);
-            if(DEBUG) {
-                System.err.println(Thread.currentThread().getName() + " - X11AWTGraphicsConfigurationFactory: create X11 display @ "+displayName+" / 0x"+Long.toHexString(displayHandle));
-            }
+            final String displayName = X11Lib.XDisplayString(displayHandleAWT);
             displayHandle = X11Util.openDisplay(displayName);
             owner = true;
+            if(DEBUG) {
+                System.err.println(getThreadName()+" - X11AWTGraphicsConfigurationFactory: AWT dpy "+displayName+" / "+toHexString(displayHandleAWT)+", create X11 display "+toHexString(displayHandle));
+            }
         }
         final ToolkitLock lock = owner ? 
                 NativeWindowFactory.getDefaultToolkitLock(NativeWindowFactory.TYPE_AWT) : // own non-shared X11 display connection, no X11 lock
@@ -119,12 +122,13 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
         }
         
         final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(x11Device);
-        X11GraphicsConfiguration x11Config = (X11GraphicsConfiguration) factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen);
-        if (x11Config == null) {
+        AbstractGraphicsConfiguration aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen);
+        if (aConfig == null) {
             throw new NativeWindowException("Unable to choose a GraphicsConfiguration (1): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen);
         }
         if(DEBUG) {
-            System.err.println("X11AWTGraphicsConfigurationFactory: chosen x11Config: "+x11Config);
+            System.err.println("X11AWTGraphicsConfigurationFactory: chosen config: "+aConfig);
+            // Thread.dumpStack();
         }
         
         //
@@ -136,17 +140,19 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
         // ie. returned by GLCanvas's getGraphicsConfiguration() befor call by super.addNotify().
         //        
         final GraphicsConfiguration[] configs = device.getConfigurations();
-        long visualID = x11Config.getVisualID();
-        for (int i = 0; i < configs.length; i++) {
-            GraphicsConfiguration gc = configs[i];
-            if (gc != null) {
-                if (X11SunJDKReflection.graphicsConfigurationGetVisualID(gc) == visualID) {
-                    if(DEBUG) {
-                        System.err.println("Found matching AWT visual: 0x"+Long.toHexString(visualID) +" -> "+x11Config);
+        int visualID = aConfig.getVisualID(VIDType.NATIVE);
+        if(VisualIDHolder.VID_UNDEFINED != visualID) {
+            for (int i = 0; i < configs.length; i++) {
+                GraphicsConfiguration gc = configs[i];
+                if (gc != null) {
+                    if (X11SunJDKReflection.graphicsConfigurationGetVisualID(gc) == visualID) {
+                        if(DEBUG) {
+                            System.err.println("Found matching AWT visual: 0x"+Integer.toHexString(visualID) +" -> "+aConfig);
+                        }
+                        return new AWTGraphicsConfiguration(awtScreen,
+                                                            aConfig.getChosenCapabilities(), aConfig.getRequestedCapabilities(),
+                                                            gc, aConfig);
                     }
-                    return new AWTGraphicsConfiguration(awtScreen,
-                                                        x11Config.getChosenCapabilities(), x11Config.getRequestedCapabilities(),
-                                                        gc, x11Config);
                 }
             }
         }
@@ -154,20 +160,22 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
         // try again using an AWT Colormodel compatible configuration
         GraphicsConfiguration gc = device.getDefaultConfiguration();
         capsChosen = AWTGraphicsConfiguration.setupCapabilitiesRGBABits(capsChosen, gc);
-        x11Config = (X11GraphicsConfiguration) factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen);
-        if (x11Config == null) {
+        aConfig = factory.chooseGraphicsConfiguration(capsChosen, capsRequested, chooser, x11Screen);
+        if (aConfig == null) {
             throw new NativeWindowException("Unable to choose a GraphicsConfiguration (2): "+capsChosen+",\n\t"+chooser+"\n\t"+x11Screen);
         }
-        visualID = x11Config.getVisualID();
-        for (int i = 0; i < configs.length; i++) {
-            gc = configs[i];
-            if (X11SunJDKReflection.graphicsConfigurationGetVisualID(gc) == visualID) {
-                if(DEBUG) {
-                    System.err.println("Found matching default AWT visual: 0x"+Long.toHexString(visualID) +" -> "+x11Config);
+        visualID = aConfig.getVisualID(VIDType.NATIVE);
+        if(VisualIDHolder.VID_UNDEFINED != visualID) {
+            for (int i = 0; i < configs.length; i++) {
+                gc = configs[i];
+                if (X11SunJDKReflection.graphicsConfigurationGetVisualID(gc) == visualID) {
+                    if(DEBUG) {
+                        System.err.println("Found matching default AWT visual: 0x"+Integer.toHexString(visualID) +" -> "+aConfig);
+                    }
+                    return new AWTGraphicsConfiguration(awtScreen,
+                                                        aConfig.getChosenCapabilities(), aConfig.getRequestedCapabilities(),
+                                                        gc, aConfig);
                 }
-                return new AWTGraphicsConfiguration(awtScreen,
-                                                    x11Config.getChosenCapabilities(), x11Config.getRequestedCapabilities(),
-                                                    gc, x11Config);
             }
         }
 
@@ -175,11 +183,11 @@ public class X11AWTGraphicsConfigurationFactory extends GraphicsConfigurationFac
         // X11GraphicsConfig or something went wrong in the steps above;
         // Let's take the default configuration as used on Windows and MacOSX then ..
         if(DEBUG) {
-            System.err.println("!!! Using default configuration");
+            System.err.println("Using default configuration");
         }
 
         gc = device.getDefaultConfiguration();
-        return new AWTGraphicsConfiguration(awtScreen, x11Config.getChosenCapabilities(), x11Config.getRequestedCapabilities(), gc, x11Config);
+        return new AWTGraphicsConfiguration(awtScreen, aConfig.getChosenCapabilities(), aConfig.getRequestedCapabilities(), gc, aConfig);
     }
 }
 
diff --git a/src/nativewindow/native/macosx/OSXmisc.m b/src/nativewindow/native/macosx/OSXmisc.m
index d64973b..38ffde9 100644
--- a/src/nativewindow/native/macosx/OSXmisc.m
+++ b/src/nativewindow/native/macosx/OSXmisc.m
@@ -232,13 +232,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0
 {
     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
 
-    // CALayer* layer = [[CALayer alloc] init];
-    CALayer* layer = [CALayer layer];
-
-    // no animations for add/remove/swap sublayers etc 
-    [layer removeAnimationForKey: kCAOnOrderIn];
-    [layer removeAnimationForKey: kCAOnOrderOut];
-    [layer removeAnimationForKey: kCATransition];
+    CALayer* layer = [[CALayer alloc] init];
+    DBG_PRINT("CALayer::CreateCALayer.0: %p (refcnt %d)\n", layer, (int)[layer retainCount]);
 
     // initial dummy size !
     CGRect lRect = [layer frame];
@@ -247,7 +242,11 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_CreateCALayer0
     lRect.size.width = 32;
     lRect.size.height = 32;
     [layer setFrame: lRect];
-    DBG_PRINT("CALayer::CreateCALayer0: %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height);
+    // no animations for add/remove/swap sublayers etc 
+    // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition]
+    [layer removeAllAnimations];
+    DBG_PRINT("CALayer::CreateCALayer.1: %p %lf/%lf %lfx%lf\n", layer, lRect.origin.x, lRect.origin.y, lRect.size.width, lRect.size.height);
+    DBG_PRINT("CALayer::CreateCALayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]);
 
     [pool release];
 
@@ -269,7 +268,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0
     CGRect lRectRoot = [rootLayer frame];
     DBG_PRINT("CALayer::AddCASublayer0.0: Origin %p frame0: %lf/%lf %lfx%lf\n", 
         rootLayer, lRectRoot.origin.x, lRectRoot.origin.y, lRectRoot.size.width, lRectRoot.size.height);
-    if(lRectRoot.origin.x<0 || lRectRoot.origin.y<0) {
+    if(lRectRoot.origin.x!=0 || lRectRoot.origin.y!=0) {
         lRectRoot.origin.x = 0;
         lRectRoot.origin.y = 0;
         [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
@@ -285,6 +284,11 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_AddCASublayer0
         // simple 1:1 layout !
         [subLayer setFrame:lRectRoot];
         [rootLayer addSublayer:subLayer];
+
+        // no animations for add/remove/swap sublayers etc 
+        // doesn't work: [layer removeAnimationForKey: kCAOnOrderIn, kCAOnOrderOut, kCATransition]
+        [rootLayer removeAllAnimations];
+        [subLayer removeAllAnimations];
     }];
     DBG_PRINT("CALayer::AddCASublayer0.X: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]);
     JNF_COCOA_EXIT(env);
@@ -308,7 +312,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_RemoveCASublayer0
     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
         [subLayer removeFromSuperlayer];
     }];
-    DBG_PRINT("CALayer::RemoveCASublayer0.X: %p . %p (refcnt %d)\n", rootLayer, subLayer, (int)[subLayer retainCount]);
+    DBG_PRINT("CALayer::RemoveCASublayer0.X: %p . %p\n", rootLayer, subLayer);
     JNF_COCOA_EXIT(env);
 }
 
@@ -327,7 +331,7 @@ JNIEXPORT void JNICALL Java_jogamp_nativewindow_macosx_OSXUtil_DestroyCALayer0
     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
         [layer release]; // performs release!
     }];
-    DBG_PRINT("CALayer::DestroyCALayer0.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]);
+    DBG_PRINT("CALayer::DestroyCALayer0.X: %p\n", layer);
     JNF_COCOA_EXIT(env);
 }
 
@@ -433,10 +437,43 @@ JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow
     CALayer* layer = (CALayer*) (intptr_t) caLayer;
     [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
         id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo;
-        DBG_PRINT("CALayer::attachJAWTSurfaceLayer: %p -> %p\n", surfaceLayers.layer, layer);
-        surfaceLayers.layer = [layer autorelease];
+        DBG_PRINT("CALayer::attachJAWTSurfaceLayer: %p -> %p (refcnt %d)\n", surfaceLayers.layer, layer, (int)[layer retainCount]);
+        surfaceLayers.layer = layer; // already incr. retain count
+        DBG_PRINT("CALayer::attachJAWTSurfaceLayer.X: %p (refcnt %d)\n", layer, (int)[layer retainCount]);
     }];
     JNF_COCOA_EXIT(env);
     return JNI_TRUE;
 }
 
+/*
+ * Class:     Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow
+ * Method:    DetachJAWTSurfaceLayer
+ * Signature: (JJ)Z
+JNIEXPORT jboolean JNICALL Java_jogamp_nativewindow_jawt_macosx_MacOSXJAWTWindow_DetachJAWTSurfaceLayer0
+  (JNIEnv *env, jclass unused, jobject jawtDrawingSurfaceInfoBuffer, jlong caLayer)
+{
+    JNF_COCOA_ENTER(env);
+    JAWT_DrawingSurfaceInfo* dsi = (JAWT_DrawingSurfaceInfo*) (*env)->GetDirectBufferAddress(env, jawtDrawingSurfaceInfoBuffer);
+    if (NULL == dsi) {
+        NativewindowCommon_throwNewRuntimeException(env, "Argument \"jawtDrawingSurfaceInfoBuffer\" was not a direct buffer");
+        return JNI_FALSE;
+    }
+    CALayer* layer = (CALayer*) (intptr_t) caLayer;
+    {
+        id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo;
+        if(layer != surfaceLayers.layer) {
+            NativewindowCommon_throwNewRuntimeException(env, "Attached layer %p doesn't match given layer %p\n", surfaceLayers.layer, layer);
+            return JNI_FALSE;
+        }
+    }
+    // [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
+        id <JAWT_SurfaceLayers> surfaceLayers = (id <JAWT_SurfaceLayers>)dsi->platformInfo;
+        DBG_PRINT("CALayer::detachJAWTSurfaceLayer: (%p) %p -> NULL\n", layer, surfaceLayers.layer);
+        surfaceLayers.layer = NULL;
+        [layer release];
+    // }];
+    JNF_COCOA_EXIT(env);
+    return JNI_TRUE;
+}
+ */
+
diff --git a/src/nativewindow/native/windows/GDImisc.c b/src/nativewindow/native/win32/GDImisc.c
similarity index 100%
rename from src/nativewindow/native/windows/GDImisc.c
rename to src/nativewindow/native/win32/GDImisc.c
diff --git a/src/nativewindow/native/windows/WindowsDWM.c b/src/nativewindow/native/win32/WindowsDWM.c
similarity index 100%
rename from src/nativewindow/native/windows/WindowsDWM.c
rename to src/nativewindow/native/win32/WindowsDWM.c
diff --git a/src/nativewindow/native/windows/WindowsDWM.h b/src/nativewindow/native/win32/WindowsDWM.h
similarity index 100%
rename from src/nativewindow/native/windows/WindowsDWM.h
rename to src/nativewindow/native/win32/WindowsDWM.h
diff --git a/src/nativewindow/native/x11/XineramaHelper.c b/src/nativewindow/native/x11/XineramaHelper.c
index 62c02c8..ffd66a1 100644
--- a/src/nativewindow/native/x11/XineramaHelper.c
+++ b/src/nativewindow/native/x11/XineramaHelper.c
@@ -1,122 +1,152 @@
-/*
- * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
- * Copyright (c) 2010 JogAmp Community. All rights reserved.
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
  * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
  * 
- * - Redistribution of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
  * 
- * - Redistribution in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  * 
- * Neither the name of Sun Microsystems, Inc. or the names of
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 
- * This software is provided "AS IS," without a warranty of any kind. ALL
- * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
- * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
- * MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
- * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
- * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
- * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
- * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
- * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
- * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
- * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
  */
 
-/* This file contains a helper routine to be called by Java code to
-   determine whether the Xinerama extension is in use and therefore to
-   treat the multiple AWT screens as one large screen. */
+#include <XineramaHelper.h>
 
-#include <gluegen_stdint.h>
-#include <X11/Xlib.h>
 #include <stdio.h>
+#include <dlfcn.h>
+
+// #define DEBUG 1
+
+static const char* XinExtName = "XINERAMA";
 
 #ifdef __sun_obsolete
 
-typedef Status XineramaGetInfoFunc(Display* display, int screen_number,
+static const char* XineramaLibNames[] = { "libXext.so", NULL } ;
+static const char* XineramaGetInfoName = "XineramaGetInfo";
+
+typedef Status (* PFNXineramaGetInfoPROC) (Display* display, int screen_number,
          XRectangle* framebuffer_rects, unsigned char* framebuffer_hints,
          int* num_framebuffers);
-typedef Status XineramaGetCenterHintFunc(Display* display, int screen_number,
-                                         int* x, int* y);
-
-XineramaGetCenterHintFunc* XineramaSolarisCenterFunc = NULL;
-#include <dlfcn.h>
 
 #else
 
-#include <X11/extensions/Xinerama.h>
+static const char* XineramaLibNames[]= { "libXinerama.so.1", "libXinerama.so", NULL };
+static const char* XineramaIsActiveName = "XineramaIsActive";
 
-#endif
+typedef Bool (* PFNXineramaIsActivePROC) (Display *display);
 
-Bool XineramaEnabled(Display* display) {
-#ifdef __sun_obsolete
+#endif
 
-#define MAXFRAMEBUFFERS 16
-  char* XinExtName = "XINERAMA";
-  int32_t major_opcode, first_event, first_error;
-  Bool gotXinExt = False;
-  void* libHandle = 0;
-  unsigned char fbhints[MAXFRAMEBUFFERS];
-  XRectangle fbrects[MAXFRAMEBUFFERS];
-  int locNumScr = 0;
-  Bool usingXinerama = False;
+static Bool XineramaIsEnabledPlatform(void *xineramaQueryFunc, Display* display) {
+    Bool res = False;
+    #ifdef __sun_obsolete
+      #define MAXFRAMEBUFFERS 16
+      unsigned char fbhints[MAXFRAMEBUFFERS];
+      XRectangle fbrects[MAXFRAMEBUFFERS];
+      int locNumScr = 0;
+
+      if(NULL!=xineramaQueryFunc && NULL!=display) {
+          PFNXineramaGetInfoPROC XineramaSolarisPROC = (PFNXineramaGetInfoPROC)xineramaQueryFunc;
+          res = XineramaSolarisPROC(display, 0, &fbrects[0], &fbhints[0], &locNumScr) != 0;
+      }
+    #else
+      if(NULL!=xineramaQueryFunc && NULL!=display) {
+          PFNXineramaIsActivePROC XineramaIsActivePROC = (PFNXineramaIsActivePROC) xineramaQueryFunc;
+          res = XineramaIsActivePROC(display);
+      }
+    #endif
+    return res;
+}
 
-  char* XineramaLibName= "libXext.so";
-  char* XineramaGetInfoName = "XineramaGetInfo";
-  char* XineramaGetCenterHintName = "XineramaGetCenterHint";
-  XineramaGetInfoFunc* XineramaSolarisFunc = NULL;
+void* XineramaGetLibHandle() {
+  void* xineramaLibHandle = NULL;
+  int i;
 
-  gotXinExt = XQueryExtension(display, XinExtName, &major_opcode,
-                              &first_event, &first_error);
+  for(i=0; NULL==xineramaLibHandle && NULL!=XineramaLibNames[i]; i++) {
+    xineramaLibHandle = dlopen(XineramaLibNames[i], RTLD_LAZY | RTLD_GLOBAL);
+  }
 
-  if (gotXinExt) {
-    /* load library, load and run XineramaGetInfo */
-    libHandle = dlopen(XineramaLibName, RTLD_LAZY | RTLD_GLOBAL);
-    if (libHandle != 0) {
-      XineramaSolarisFunc = (XineramaGetInfoFunc*)dlsym(libHandle, XineramaGetInfoName);
-      XineramaSolarisCenterFunc =
-        (XineramaGetCenterHintFunc*)dlsym(libHandle,
-                                          XineramaGetCenterHintName);
-      if (XineramaSolarisFunc != NULL) {
-        if ((*XineramaSolarisFunc)(display, 0, &fbrects[0],
-                                   &fbhints[0], &locNumScr) != 0) {
-
-          usingXinerama = True;
-        }
-      }
-      dlclose(libHandle);
+  #ifdef DEBUG
+    if(NULL!=xineramaLibHandle) {
+      fprintf(stderr, "XineramaGetLibHandle: using lib %s -> %p\n", XineramaLibNames[i-1], xineramaLibHandle);
+    } else {
+      fprintf(stderr, "XineramaGetLibHandle: no native lib available\n");
     }
+  #endif
+
+  return xineramaLibHandle;
+}
+
+Bool XineramaReleaseLibHandle(void* xineramaLibHandle) {
+  #ifdef DEBUG
+    fprintf(stderr, "XineramaReleaseLibHandle: release lib %p\n", xineramaLibHandle);
+  #endif
+  if(NULL==xineramaLibHandle) {
+    return False;
   }
-  return usingXinerama;
-  
-#else
+  return 0 == dlclose(xineramaLibHandle) ? True : False;
+}
+
+void* XineramaGetQueryFunc(void *xineramaLibHandle) {
+    void * funcptr = NULL;
 
-  static const char* XinExtName = "XINERAMA";
+    if(NULL==xineramaLibHandle) {
+      return NULL;
+    }
+
+    #ifdef __sun_obsolete
+      #ifdef DEBUG
+        fprintf(stderr, "XineramaGetQueryFunc: trying func %p -> %s\n", xineramaLibHandle, XineramaGetInfoName);
+      #endif
+      funcptr = dlsym(xineramaLibHandle, XineramaGetInfoName);
+    #else
+      #ifdef DEBUG
+        fprintf(stderr, "XineramaGetQueryFunc: trying func %p -> %s\n", xineramaLibHandle, XineramaIsActiveName);
+      #endif
+      funcptr = dlsym(xineramaLibHandle, XineramaIsActiveName);
+    #endif
+    #ifdef DEBUG
+      fprintf(stderr, "XineramaGetQueryFunc: got func %p\n", funcptr);
+    #endif
+    return funcptr;
+}
+
+Bool XineramaIsEnabled(void *xineramaQueryFunc, Display* display) {
   int32_t major_opcode, first_event, first_error;
   Bool gotXinExt = False;
-  Bool isXinActive = False;
+  Bool res = False;
 
-  // fprintf(stderr, "XineramaEnabled: p0\n"); fflush(stderr);
+  if(NULL==xineramaQueryFunc || NULL==display) {
+    return False;
+  }
 
   gotXinExt = XQueryExtension(display, XinExtName, &major_opcode,
                               &first_event, &first_error);
-  // fprintf(stderr, "XineramaEnabled: p1 gotXinExt %d\n",gotXinExt); fflush(stderr);
 
-  if (gotXinExt) {
-    isXinActive = XineramaIsActive(display);
-  }
-  // fprintf(stderr, "XineramaEnabled: p2 XineramaIsActive %d\n", isXinActive); fflush(stderr);
+  #ifdef DEBUG
+    fprintf(stderr, "XineramaIsEnabled: has Xinerama Ext: ext %d, query-func %p\n", gotXinExt, xineramaQueryFunc);
+  #endif
 
-  return isXinActive;
+  if(gotXinExt) {
+    res = XineramaIsEnabledPlatform(xineramaQueryFunc, display);
+  }
 
-#endif
+  return res;
 }
 
diff --git a/src/jogl/classes/jogamp/graph/font/FontConstructor.java b/src/nativewindow/native/x11/XineramaHelper.h
similarity index 81%
copy from src/jogl/classes/jogamp/graph/font/FontConstructor.java
copy to src/nativewindow/native/x11/XineramaHelper.h
index 721b207..42b6a03 100644
--- a/src/jogl/classes/jogamp/graph/font/FontConstructor.java
+++ b/src/nativewindow/native/x11/XineramaHelper.h
@@ -3,14 +3,14 @@
  *
  * Redistribution and use in source and binary forms, with or without modification, are
  * permitted provided that the following conditions are met:
- *
+ * 
  *    1. Redistributions of source code must retain the above copyright notice, this list of
  *       conditions and the following disclaimer.
- *
+ * 
  *    2. Redistributions in binary form must reproduce the above copyright notice, this list
  *       of conditions and the following disclaimer in the documentation and/or other materials
  *       provided with the distribution.
- *
+ * 
  * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
@@ -20,20 +20,21 @@
  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 
  * The views and conclusions contained in the software and documentation are those of the
  * authors and should not be interpreted as representing official policies, either expressed
  * or implied, of JogAmp Community.
  */
-package jogamp.graph.font;
+ 
+#ifndef XineramaHelper_h
+#define XineramaHelper_h
 
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
+#include <gluegen_stdint.h>
+#include <X11/Xlib.h>
 
-import com.jogamp.graph.font.Font;
+void* XineramaGetLibHandle();
+Bool XineramaReleaseLibHandle(void* xineramaLibHandle);
+void* XineramaGetQueryFunc(void *xineramaLibHandle);
+Bool XineramaIsEnabled(void *xineramaQueryFunc, Display* display);
 
-public interface FontConstructor {
-    Font create(File file) throws IOException ;
-    Font create(URL url) throws IOException ;
-}
+#endif /* XineramaHelper_h */
diff --git a/src/nativewindow/native/x11/Xmisc.c b/src/nativewindow/native/x11/Xmisc.c
index d28891c..439d9b3 100644
--- a/src/nativewindow/native/x11/Xmisc.c
+++ b/src/nativewindow/native/x11/Xmisc.c
@@ -91,9 +91,6 @@ Bool XF86VidModeSetGammaRamp(
     #define DBG_PRINT(args...)
 #endif
 
-/* Need to pull this in as we don't have a stub header for it */
-extern Bool XineramaEnabled(Display* display);
-
 static const char * const ClazzNameBuffers = "com/jogamp/common/nio/Buffers";
 static const char * const ClazzNameBuffersStaticCstrName = "copyByteBuffer";
 static const char * const ClazzNameBuffersStaticCstrSignature = "(Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;";
@@ -303,10 +300,10 @@ Java_jogamp_nativewindow_x11_X11Util_initialize0(JNIEnv *env, jclass _unused, jb
                 fprintf(stderr, "Warning: XInitThreads() failed\n");
             } else {
                 _xinitThreadsOK=JNI_TRUE;
-                fprintf(stderr, "Info: XInitThreads() called for concurrent Thread support\n");
+                DBG_PRINT( "X11: XInitThreads() called for concurrent Thread support\n");
             }
         } else {
-            fprintf(stderr, "Info: XInitThreads() _not_ called for concurrent Thread support\n");
+            DBG_PRINT( "X11: XInitThreads() _not_ called for concurrent Thread support\n");
         }
 
         _initClazzAccess(env);
@@ -423,10 +420,10 @@ Java_jogamp_nativewindow_x11_X11Lib_XCloseDisplay__J(JNIEnv *env, jclass _unused
 /*
  * Class:     jogamp_nativewindow_x11_X11Lib
  * Method:    CreateDummyWindow
- * Signature: (JIJII)J
+ * Signature: (JIIII)J
  */
 JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow
-  (JNIEnv *env, jclass unused, jlong display, jint screen_index, jlong visualID, jint width, jint height)
+  (JNIEnv *env, jclass unused, jlong display, jint screen_index, jint visualID, jint width, jint height)
 {
     Display * dpy  = (Display *)(intptr_t)display;
     int       scrn_idx = (int)screen_index;
@@ -466,7 +463,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_nativewindow_x11_X11Lib_CreateDummyWindow
     if(pVisualQuery!=NULL) {
         visual   = pVisualQuery->visual;
         depth    = pVisualQuery->depth;
-        visualID = (jlong)pVisualQuery->visualid;
+        visualID = (jint)pVisualQuery->visualid;
         XFree(pVisualQuery);
         pVisualQuery=NULL;
     }
diff --git a/src/newt/classes/com/jogamp/newt/NewtFactory.java b/src/newt/classes/com/jogamp/newt/NewtFactory.java
index 4e6fa1a..f551fcc 100644
--- a/src/newt/classes/com/jogamp/newt/NewtFactory.java
+++ b/src/newt/classes/com/jogamp/newt/NewtFactory.java
@@ -46,8 +46,6 @@ import jogamp.newt.DisplayImpl;
 import jogamp.newt.ScreenImpl;
 import jogamp.newt.WindowImpl;
 
-import com.jogamp.common.os.Platform;
-
 public class NewtFactory {
     public static final boolean DEBUG_IMPLEMENTATION = Debug.debug("Window");
 
diff --git a/src/newt/classes/com/jogamp/newt/Screen.java b/src/newt/classes/com/jogamp/newt/Screen.java
index d25d3e7..26f19ad 100644
--- a/src/newt/classes/com/jogamp/newt/Screen.java
+++ b/src/newt/classes/com/jogamp/newt/Screen.java
@@ -120,12 +120,22 @@ public abstract class Screen {
     public abstract int getIndex();
 
     /**
-     * @return the current screen width
+     * @return the x position of the virtual top-left origin.
+     */
+    public abstract int getX();
+    
+    /**
+     * @return the y position of the virtual top-left origin.
+     */
+    public abstract int getY();
+    
+    /**
+     * @return the <b>rotated</b> virtual width.
      */
     public abstract int getWidth();
 
     /**
-     * @return the current screen height
+     * @return the <b>rotated</b> virtual height.
      */
     public abstract int getHeight();
 
diff --git a/src/newt/classes/com/jogamp/newt/Window.java b/src/newt/classes/com/jogamp/newt/Window.java
index 32024a4..3c5441b 100644
--- a/src/newt/classes/com/jogamp/newt/Window.java
+++ b/src/newt/classes/com/jogamp/newt/Window.java
@@ -269,22 +269,22 @@ public interface Window extends NativeWindow, WindowClosingProtocol {
      */
     void warpPointer(int x, int y);
     
-    /** Defining ids for the reparenting strategy */
-    public interface ReparentAction {
+    /** Reparenting operation types */
+    public enum ReparentOperation {
         /** No native reparenting valid */
-        static final int ACTION_INVALID = -1;
+        ACTION_INVALID,
 
         /** No native reparenting action required, no change*/
-        static final int ACTION_UNCHANGED = 0;
+        ACTION_NOP,
 
         /** Native reparenting incl. Window tree */
-        static final int ACTION_NATIVE_REPARENTING = 1;
+        ACTION_NATIVE_REPARENTING,
 
         /** Native window creation after tree change - instead of reparenting. */
-        static final int ACTION_NATIVE_CREATION = 2;
+        ACTION_NATIVE_CREATION,
 
         /** Change Window tree only, native creation is pending */
-        static final int ACTION_NATIVE_CREATION_PENDING = 3;
+        ACTION_NATIVE_CREATION_PENDING;        
     }
 
     /**
@@ -299,9 +299,9 @@ public interface Window extends NativeWindow, WindowClosingProtocol {
      *
      * @return The issued reparent action type (strategy) as defined in Window.ReparentAction
      */
-    int reparentWindow(NativeWindow newParent);
+    ReparentOperation reparentWindow(NativeWindow newParent);
 
-    int reparentWindow(NativeWindow newParent, boolean forceDestroyCreate);
+    ReparentOperation reparentWindow(NativeWindow newParent, boolean forceDestroyCreate);
 
     boolean setFullscreen(boolean fullscreen);
     
diff --git a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java
index a71c610..9af4a02 100644
--- a/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java
+++ b/src/newt/classes/com/jogamp/newt/awt/NewtCanvasAWT.java
@@ -44,16 +44,16 @@ import java.util.Set;
 import javax.media.nativewindow.NativeWindow;
 import javax.media.nativewindow.OffscreenLayerOption;
 import javax.media.nativewindow.WindowClosingProtocol;
-import javax.media.nativewindow.awt.AWTWindowClosingProtocol;
 import javax.swing.MenuSelectionManager;
 
 import jogamp.nativewindow.awt.AWTMisc;
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.newt.Debug;
 import jogamp.newt.awt.NewtFactoryAWT;
 import jogamp.newt.awt.event.AWTParentWindowAdapter;
 import jogamp.newt.driver.DriverClearFocus;
 
+import com.jogamp.nativewindow.awt.AWTWindowClosingProtocol;
+import com.jogamp.nativewindow.awt.JAWTWindow;
 import com.jogamp.newt.Display;
 import com.jogamp.newt.Window;
 import com.jogamp.newt.event.InputEvent;
@@ -74,7 +74,7 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
     private boolean shallUseOffscreenLayer = false;
     private Window newtChild = null;
     private boolean isOnscreen = true;
-    private int newtChildCloseOp;
+    private WindowClosingMode newtChildCloseOp;
     private AWTAdapter awtAdapter = null;
     private AWTAdapter awtMouseAdapter = null;
     private AWTAdapter awtKeyAdapter = null;
@@ -136,20 +136,32 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
     public boolean isApplet() {
         return jawtWindow.isApplet();
     }
+
+    boolean isParent() {
+        return null!=newtChild && jawtWindow == newtChild.getParent();        
+    }
+    
+    boolean isFullscreen() {
+        return null != newtChild && newtChild.isFullscreen();
+    }
     
     class FocusAction implements Window.FocusRunnable {
         public boolean run() {
+            final boolean isParent = isParent();
+            final boolean isFullscreen = isFullscreen();
             if(DEBUG) {
-                System.err.println("NewtCanvasAWT.FocusAction: "+Display.getThreadName()+", isOnscreen "+isOnscreen+", hasFocus "+hasFocus());
+                System.err.println("NewtCanvasAWT.FocusAction: "+Display.getThreadName()+", isOnscreen "+isOnscreen+", hasFocus "+hasFocus()+", isParent "+isParent+", isFS "+isFullscreen);
             }
-            // Newt-EDT -> AWT-EDT may freeze Window's native peer requestFocus.
-            if(!hasFocus()) {
-                // Acquire the AWT focus 1st for proper AWT traversal
-                NewtCanvasAWT.super.requestFocus();
-            }
-            if(isOnscreen) {
-                // Remove the AWT focus in favor of the native NEWT focus
-                KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
+            if(isParent && !isFullscreen) {
+                // Newt-EDT -> AWT-EDT may freeze Window's native peer requestFocus.
+                if(!hasFocus()) {
+                    // Acquire the AWT focus 1st for proper AWT traversal
+                    NewtCanvasAWT.super.requestFocus();
+                }
+                if(isOnscreen) {
+                    // Remove the AWT focus in favor of the native NEWT focus
+                    KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
+                }
             }
             return false; // NEWT shall proceed requesting the native focus
         }
@@ -159,7 +171,9 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
     WindowListener clearAWTMenusOnNewtFocus = new WindowAdapter() {
           @Override
           public void windowGainedFocus(WindowEvent arg0) {
-              MenuSelectionManager.defaultManager().clearSelectedPath();
+              if( isParent() && !isFullscreen() ) {
+                  MenuSelectionManager.defaultManager().clearSelectedPath();
+              }
           }
     };
 
@@ -167,10 +181,14 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
          boolean suppress = false;
          
          public void keyPressed(KeyEvent e) {
-             handleKey(e, false);
+             if( isParent() && !isFullscreen() ) {
+                 handleKey(e, false);
+             }
          }
          public void keyReleased(KeyEvent e) {
-             handleKey(e, true);
+             if( isParent() && !isFullscreen() ) {
+                 handleKey(e, true);
+             }
          }
          public void keyTyped(KeyEvent e) {
              if(suppress) {
@@ -217,21 +235,25 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
         public void propertyChange(PropertyChangeEvent evt) {
             final Object oldF = evt.getOldValue();
             final Object newF = evt.getNewValue();
+            final boolean isParent = isParent();
+            final boolean isFullscreen = isFullscreen(); 
             if(DEBUG) {
-                System.err.println("NewtCanvasAWT.FocusProperty: "+evt.getPropertyName()+", src "+evt.getSource()+", "+oldF+" -> "+newF);
+                System.err.println("NewtCanvasAWT.FocusProperty: "+evt.getPropertyName()+", src "+evt.getSource()+", "+oldF+" -> "+newF+", isParent "+isParent+", isFS "+isFullscreen);
             }
-            if(oldF == NewtCanvasAWT.this && newF == null) {
-                // focus traversal to NEWT - NOP
-                if(DEBUG) {                    
-                    System.err.println("NewtCanvasAWT.FocusProperty: NEWT focus traversal");
-                }
-            } else if(null != newF && newF != NewtCanvasAWT.this) {
-                // focus traversal to another AWT component
-                if(DEBUG) {                    
-                    System.err.println("NewtCanvasAWT.FocusProperty: lost focus - clear focus");
-                }
-                if(newtChild.getDelegatedWindow() instanceof DriverClearFocus) {
-                    ((DriverClearFocus)newtChild.getDelegatedWindow()).clearFocus();
+            if(isParent && !isFullscreen) {
+                if(oldF == NewtCanvasAWT.this && newF == null) {
+                    // focus traversal to NEWT - NOP
+                    if(DEBUG) {                    
+                        System.err.println("NewtCanvasAWT.FocusProperty: NEWT focus traversal");
+                    }
+                } else if(null != newF && newF != NewtCanvasAWT.this) {
+                    // focus traversal to another AWT component
+                    if(DEBUG) {                    
+                        System.err.println("NewtCanvasAWT.FocusProperty: lost focus - clear focus");
+                    }
+                    if(newtChild.getDelegatedWindow() instanceof DriverClearFocus) {
+                        ((DriverClearFocus)newtChild.getDelegatedWindow()).clearFocus();
+                    }
                 }
             }
         }        
@@ -261,11 +283,11 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
      * or {@link #addNotify()} hasn't been called yet.*/
     public NativeWindow getNativeWindow() { return jawtWindow; }
     
-    public int getDefaultCloseOperation() {
+    public WindowClosingMode getDefaultCloseOperation() {
         return awtWindowClosingProtocol.getDefaultCloseOperation();
     }
 
-    public int setDefaultCloseOperation(int op) {
+    public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
         return awtWindowClosingProtocol.setDefaultCloseOperation(op);
     }
 
@@ -294,10 +316,10 @@ public class NewtCanvasAWT extends java.awt.Canvas implements WindowClosingProto
                     throw new InternalError("XXX");
                 }                
                 isOnscreen = jawtWindow.getGraphicsConfiguration().getChosenCapabilities().isOnscreen();
-                awtAdapter = new AWTParentWindowAdapter(newtChild).addTo(this);
+                awtAdapter = new AWTParentWindowAdapter(jawtWindow, newtChild).addTo(this);
                 newtChild.addWindowListener(clearAWTMenusOnNewtFocus);
                 newtChild.setFocusAction(focusAction); // enable AWT focus traversal
-                newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingProtocol.DO_NOTHING_ON_CLOSE);
+                newtChildCloseOp = newtChild.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE);
                 awtWindowClosingProtocol.addClosingListenerOneShot();
                 keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                 keyboardFocusManager.addPropertyChangeListener("focusOwner", focusPropertyChangeListener);
diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java
index a052f6f..d06aca0 100755
--- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java
+++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtApplet1Run.java
@@ -36,6 +36,7 @@ import java.awt.event.KeyListener;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
 
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 import javax.media.opengl.FPSCounter;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLEventListener;
@@ -64,7 +65,7 @@ import com.jogamp.newt.opengl.GLWindow;
  *  </p>
  *  
  *  <p>
- *  Example of an applet tag using GearsES2 in an undecorated, translucent and always-on-top window: 
+ *  Example of an applet tag using GearsES2 in an undecorated, translucent, closeable and always-on-top window: 
  *  <pre>
         <applet width=1 height=1>
            <param name="java_arguments" value="-Dsun.java2d.noddraw=true">
@@ -73,6 +74,7 @@ import com.jogamp.newt.opengl.GLWindow;
            <param name="gl_swap_interval" value="1">
            <param name="gl_undecorated" value="true">
            <param name="gl_alwaysontop" value="true">
+           <param name="gl_closeable" value="true">
            <param name="gl_alpha" value="1">
            <param name="gl_multisamplebuffer" value="0">
            <param name="gl_opaque" value="false">
@@ -115,6 +117,7 @@ public class JOGLNewtApplet1Run extends Applet {
         boolean glTrace=false;
         boolean glUndecorated=false;
         boolean glAlwaysOnTop=false;
+        boolean glCloseable=false;
         boolean glOpaque=true;
         int glAlphaBits=0;
         int glNumMultisampleBuffer=0;
@@ -128,6 +131,7 @@ public class JOGLNewtApplet1Run extends Applet {
             glTrace = JOGLNewtAppletBase.str2Bool(getParameter("gl_trace"), glTrace);
             glUndecorated = JOGLNewtAppletBase.str2Bool(getParameter("gl_undecorated"), glUndecorated);
             glAlwaysOnTop = JOGLNewtAppletBase.str2Bool(getParameter("gl_alwaysontop"), glAlwaysOnTop);
+            glCloseable = JOGLNewtAppletBase.str2Bool(getParameter("gl_closeable"), glCloseable);
             glOpaque = JOGLNewtAppletBase.str2Bool(getParameter("gl_opaque"), glOpaque);
             glAlphaBits = JOGLNewtAppletBase.str2Int(getParameter("gl_alpha"), glAlphaBits);
             glNumMultisampleBuffer = JOGLNewtAppletBase.str2Int(getParameter("gl_multisamplebuffer"), glNumMultisampleBuffer); 
@@ -157,6 +161,7 @@ public class JOGLNewtApplet1Run extends Applet {
             System.err.println("glTrace: "+glTrace);
             System.err.println("glUndecorated: "+glUndecorated);
             System.err.println("glAlwaysOnTop: "+glAlwaysOnTop);
+            System.err.println("glCloseable: "+glCloseable);
             System.err.println("glOpaque: "+glOpaque);
             System.err.println("glAlphaBits: "+glAlphaBits);
             System.err.println("glNumMultisampleBuffer: "+glNumMultisampleBuffer);
@@ -166,6 +171,7 @@ public class JOGLNewtApplet1Run extends Applet {
         base = new JOGLNewtAppletBase(glEventListenerClazzName, 
                                       glSwapInterval,
                                       glNoDefaultKeyListener,
+                                      glCloseable,
                                       glDebug,
                                       glTrace);
 
@@ -181,6 +187,7 @@ public class JOGLNewtApplet1Run extends Applet {
             glWindow.setUpdateFPSFrames(FPSCounter.DEFAULT_FRAMES_PER_INTERVAL, System.err);
             glWindow.setUndecorated(glUndecorated);
             glWindow.setAlwaysOnTop(glAlwaysOnTop);
+            glWindow.setDefaultCloseOperation(glCloseable ? WindowClosingMode.DISPOSE_ON_CLOSE : WindowClosingMode.DO_NOTHING_ON_CLOSE);
             container.setLayout(new BorderLayout());
             if(appletDebugTestBorder) {
                 container.add(new Button("North"), BorderLayout.NORTH);
diff --git a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
index 67da502..082c01c 100755
--- a/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
+++ b/src/newt/classes/com/jogamp/newt/awt/applet/JOGLNewtAppletBase.java
@@ -32,6 +32,7 @@ import java.security.AccessController;
 import java.security.PrivilegedAction;
 
 import javax.media.nativewindow.NativeWindow;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 import javax.media.opengl.FPSCounter;
 import javax.media.opengl.GL;
 import javax.media.opengl.GLAutoDrawable;
@@ -43,6 +44,7 @@ import jogamp.newt.Debug;
 import com.jogamp.newt.event.KeyEvent;
 import com.jogamp.newt.event.KeyListener;
 import com.jogamp.newt.event.MouseListener;
+import com.jogamp.newt.event.WindowAdapter;
 import com.jogamp.newt.event.WindowEvent;
 import com.jogamp.newt.event.WindowListener;
 import com.jogamp.newt.opengl.GLWindow;
@@ -58,6 +60,7 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
     String glEventListenerClazzName;
     int glSwapInterval;
     boolean noDefaultKeyListener;
+    boolean glClosable;
     boolean glDebug;
     boolean glTrace;
 
@@ -70,12 +73,14 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
     public JOGLNewtAppletBase(String glEventListenerClazzName, 
                               int glSwapInterval,
                               boolean noDefaultKeyListener,
+                              boolean glClosable,
                               boolean glDebug,
                               boolean glTrace) {
     
         this.glEventListenerClazzName=glEventListenerClazzName;
         this.glSwapInterval=glSwapInterval;
         this.noDefaultKeyListener = noDefaultKeyListener;
+        this.glClosable = glClosable;
         this.glDebug = glDebug;
         this.glTrace = glTrace;
     }
@@ -152,9 +157,24 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
         init(Thread.currentThread().getThreadGroup(), glWindow);
     }
 
-    public void init(ThreadGroup tg, GLWindow glWindow) {
+    public void init(ThreadGroup tg, final GLWindow glWindow) {
         isValid = false;
         this.glWindow = glWindow;
+        this.glWindow.addWindowListener(new WindowAdapter() {
+                // Closing action: back to parent!
+                @Override
+                public void windowDestroyNotify(WindowEvent e) {
+                    if( WindowClosingMode.DO_NOTHING_ON_CLOSE == glWindow.getDefaultCloseOperation() ) {
+                        if(null == glWindow.getParent()) {
+                            // we may be called directly by the native EDT
+                            new Thread(new Runnable() {
+                               public void run() {
+                                glWindow.reparentWindow(awtParent);
+                               }
+                            }).start();                         
+                        }                        
+                    }
+                } } );
 
         glEventListener = createInstance(glEventListenerClazzName);
         if(null == glEventListener) {
@@ -277,6 +297,9 @@ public class JOGLNewtAppletBase implements KeyListener, GLEventListener {
                 glWindow.reparentWindow(awtParent);
             } else {
                 glWindow.reparentWindow(null);
+                if(glClosable) {
+                    glWindow.setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE);
+                }
             }
        }
     }
diff --git a/src/newt/classes/com/jogamp/newt/event/InputEvent.java b/src/newt/classes/com/jogamp/newt/event/InputEvent.java
index d8a9235..819338c 100644
--- a/src/newt/classes/com/jogamp/newt/event/InputEvent.java
+++ b/src/newt/classes/com/jogamp/newt/event/InputEvent.java
@@ -45,9 +45,27 @@ public abstract class InputEvent extends NEWTEvent
  public static final int  BUTTON1_MASK   = 1 <<  6;
  public static final int  BUTTON2_MASK   = 1 <<  7;
  public static final int  BUTTON3_MASK   = 1 <<  8;
+ public static final int  BUTTON4_MASK   = 1 <<  9;
+ public static final int  BUTTON5_MASK   = 1 << 10;
+ public static final int  BUTTON6_MASK   = 1 << 11;
  public static final int  CONFINED_MASK  = 1 << 16;
  public static final int  INVISIBLE_MASK = 1 << 17;
 
+ /** 
+  * Returns the corresponding button mask for the given button.
+  * <p>
+  * In case the given button lies outside 
+  * of the valid range [{@link MouseEvent#BUTTON1} .. {@link MouseEvent#BUTTON6}],
+  * null is returned.
+  * </p>
+  */
+ public static final int getButtonMask(int button)  {
+     if( 0 < button && button <= MouseEvent.BUTTON_NUMBER ) {
+         return 1 << ( 5 + button ) ;
+     }
+     return 0;
+ }
+ 
  /** Object when attached via {@link #setAttachment(Object)} marks the event consumed,
   * ie. stops propagating the event any further to the event listener. 
   */
@@ -84,35 +102,27 @@ public abstract class InputEvent extends NEWTEvent
  }
 
  /**
-  * @return Array of pressed mouse buttons  [{@link MouseEvent#BUTTON1} ..]. 
+  * @return Array of pressed mouse buttons  [{@link MouseEvent#BUTTON1} .. {@link MouseEvent#BUTTON6}]. 
   *         If none is down, the resulting array is of length 0.
   */
  public final int[] getButtonsDown()  {
      int len = 0;
-     if(isButton1Down()) { len++; }
-     if(isButton2Down()) { len++; }
-     if(isButton3Down()) { len++; }
+     for(int i=1; i<=MouseEvent.BUTTON_NUMBER; i++) {
+         if(isButtonDown(i)) { len++; }
+     }
      
      int[] res = new int[len];
-     int i=0;
-     if(isButton1Down()) { res[i++] = MouseEvent.BUTTON1; }
-     if(isButton2Down()) { res[i++] = MouseEvent.BUTTON2; }
-     if(isButton3Down()) { res[i++] = MouseEvent.BUTTON3; }
+     int j = 0;
+     for(int i=1; i<=MouseEvent.BUTTON_NUMBER; i++) {
+         if(isButtonDown(i)) { res[j++] = ( MouseEvent.BUTTON1 - 1 ) + i; }
+     }
      return res;
  }
 
- public final boolean isButton1Down()  {
-    return (modifiers&BUTTON1_MASK)!=0;
- }
-
- public final boolean isButton2Down()  {
-    return (modifiers&BUTTON2_MASK)!=0;
+ public final boolean isButtonDown(int button)  {
+    return ( modifiers & getButtonMask(button) ) != 0;
  }
-
- public final boolean isButton3Down()  {
-    return (modifiers&BUTTON3_MASK)!=0;
- }
-
+ 
  public String toString() {
      return "InputEvent[modifiers: 0x"+Integer.toHexString(modifiers)+", "+super.toString()+"]";
  }
diff --git a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java
index 9bc3be1..ceaf7d4 100644
--- a/src/newt/classes/com/jogamp/newt/event/MouseEvent.java
+++ b/src/newt/classes/com/jogamp/newt/event/MouseEvent.java
@@ -37,12 +37,19 @@ package com.jogamp.newt.event;
 @SuppressWarnings("serial")
 public class MouseEvent extends InputEvent
 {
+    /** ID for button 1, value <code>1</code> */
     public static final int BUTTON1 = 1;
+    /** ID for button 2, value <code>2</code> */
     public static final int BUTTON2 = 2;
+    /** ID for button 3, value <code>3</code> */
     public static final int BUTTON3 = 3;
+    /** ID for button 4, value <code>4</code> */
     public static final int BUTTON4 = 4;
+    /** ID for button 5, value <code>5</code> */
     public static final int BUTTON5 = 5;
+    /** ID for button 6, value <code>6</code> */
     public static final int BUTTON6 = 6;
+    /** Number of buttons, value <code>6</code> */
     public static final int BUTTON_NUMBER = 6;
 
     public static final int getClickTimeout() { 
@@ -158,7 +165,7 @@ public class MouseEvent extends InputEvent
     }
 
     public String toString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("MouseEvent[").append(getEventTypeString(getEventType()))
         .append(", ").append(x).append("/").append(y)
         .append(", button ").append(button).append(", count ")
diff --git a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java
index 5dcd4d9..115743a 100644
--- a/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java
+++ b/src/newt/classes/com/jogamp/newt/event/awt/AWTMouseAdapter.java
@@ -30,7 +30,9 @@ package com.jogamp.newt.event.awt;
 
 import jogamp.newt.awt.event.AWTNewtEventFactory;
 
-public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener
+public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseListener, 
+                                                           java.awt.event.MouseMotionListener,
+                                                           java.awt.event.MouseWheelListener
 {
     public AWTMouseAdapter(com.jogamp.newt.event.MouseListener newtListener) {
         super(newtListener);
@@ -47,12 +49,14 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL
     public AWTAdapter addTo(java.awt.Component awtComponent) {
         awtComponent.addMouseListener(this);
         awtComponent.addMouseMotionListener(this);
+        awtComponent.addMouseWheelListener(this);
         return this;
     }
 
     public AWTAdapter removeFrom(java.awt.Component awtComponent) {
         awtComponent.removeMouseListener(this);
         awtComponent.removeMouseMotionListener(this);
+        awtComponent.removeMouseWheelListener(this);
         return this;
     }
 
@@ -118,5 +122,14 @@ public class AWTMouseAdapter extends AWTAdapter implements java.awt.event.MouseL
             enqueueEvent(false, event);
         }
     }
+
+    public void mouseWheelMoved(java.awt.event.MouseWheelEvent e) {
+        com.jogamp.newt.event.MouseEvent event = AWTNewtEventFactory.createMouseEvent(e, newtWindow);
+        if(null!=newtListener) {
+            ((com.jogamp.newt.event.MouseListener)newtListener).mouseWheelMoved(event);
+        } else {
+            enqueueEvent(false, event);
+        }
+    }
 }
 
diff --git a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java
index d03a475..34e0df6 100644
--- a/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java
+++ b/src/newt/classes/com/jogamp/newt/opengl/GLWindow.java
@@ -35,7 +35,6 @@
 package com.jogamp.newt.opengl;
 
 import java.io.PrintStream;
-import java.util.List;
 
 import com.jogamp.common.GlueGenVersion;
 import com.jogamp.common.util.VersionUtil;
@@ -95,7 +94,7 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
 
                 @Override
                 public void windowDestroyNotify(WindowEvent e) {
-                    if( DISPOSE_ON_CLOSE == GLWindow.this.getDefaultCloseOperation() ) {
+                    if( WindowClosingMode.DISPOSE_ON_CLOSE == GLWindow.this.getDefaultCloseOperation() ) {
                         // Is an animator thread perform rendering?
                         if (GLWindow.this.helper.isExternalAnimatorRunning()) {
                             // Pause animations before initiating safe destroy.
@@ -177,11 +176,11 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
     //----------------------------------------------------------------------
     // WindowClosingProtocol implementation
     //
-    public int getDefaultCloseOperation() {
+    public WindowClosingMode getDefaultCloseOperation() {
         return window.getDefaultCloseOperation();
     }
 
-    public int setDefaultCloseOperation(int op) {
+    public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
         return window.setDefaultCloseOperation(op);
     }
 
@@ -306,14 +305,14 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
     @Override
     public final String toString() {
         return "NEWT-GLWindow[ \n\tHelper: " + helper + ", \n\tDrawable: " + drawable + 
-               ", \n\tContext: " + context + /** ", \n\tWindow: "+window+", \n\tFactory: "+factory+ */ "]";
+               ", \n\tContext: " + context + ", \n\tWindow: "+window+ /** ", \n\tFactory: "+factory+ */ "]";
     }
 
-    public final int reparentWindow(NativeWindow newParent) {
+    public final ReparentOperation reparentWindow(NativeWindow newParent) {
         return window.reparentWindow(newParent);
     }
 
-    public final int reparentWindow(NativeWindow newParent, boolean forceDestroyCreate) {
+    public final ReparentOperation reparentWindow(NativeWindow newParent, boolean forceDestroyCreate) {
         return window.reparentWindow(newParent, forceDestroyCreate);
     }
 
@@ -355,14 +354,6 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
     // Hide methods here ..
     protected class GLLifecycleHook implements WindowImpl.LifecycleHook {
 
-        private class DisposeAction implements Runnable {
-            public final void run() {
-                // Lock: Covered by DestroyAction ..
-                helper.dispose(GLWindow.this);
-            }
-        }
-        DisposeAction disposeAction = new DisposeAction();
-
         public synchronized void destroyActionPreLock() {
             // nop
         }
@@ -380,11 +371,10 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
                     // Catch dispose GLExceptions by GLEventListener, just 'print' them
                     // so we can continue with the destruction.
                     try {
-                        helper.invokeGL(drawable, context, disposeAction, null);
+                        helper.disposeGL(GLWindow.this, drawable, context, null);
                     } catch (GLException gle) {
                         gle.printStackTrace();
                     }
-                    context.destroy();
                 }
                 drawable.setRealized(false);
             }
@@ -404,11 +394,12 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
         }
 
         public synchronized void setVisibleActionPost(boolean visible, boolean nativeWindowCreated) {
+            long t0;
             if(Window.DEBUG_IMPLEMENTATION) {
-                String msg = "GLWindow.setVisibleActionPost("+visible+", "+nativeWindowCreated+") "+Thread.currentThread()+", start";
-                System.err.println(msg);
-                // Exception e1 = new Exception(msg);
-                // e1.printStackTrace();
+                t0 = System.nanoTime();
+                System.err.println("GLWindow.setVisibleActionPost("+visible+", "+nativeWindowCreated+") "+Thread.currentThread()+", start");
+            } else {
+                t0 = 0;
             }
 
             /* if (nativeWindowCreated && null != context) {
@@ -430,13 +421,11 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
                 }
                 drawable.setRealized(true);
                 context = drawable.createContext(sharedContext);
+                context.setSynchronized(true);
                 context.setContextCreationFlags(additionalCtxCreationFlags);                
             }
             if(Window.DEBUG_IMPLEMENTATION) {
-                String msg = "GLWindow.setVisibleActionPost("+visible+", "+nativeWindowCreated+") "+Thread.currentThread()+", fin";
-                System.err.println(msg);
-                //Exception e1 = new Exception(msg);
-                //e1.printStackTrace();
+                System.err.println("GLWindow.setVisibleActionPost("+visible+", "+nativeWindowCreated+") "+Thread.currentThread()+", fin: dt "+ (System.nanoTime()-t0)/1e6 +"ms");
             }
         }
         
@@ -567,13 +556,8 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
         }
 
         if( null != context ) { // TODO: Check memory sync
-            if( NativeSurface.LOCK_SURFACE_NOT_READY < lockSurface() ) {
-                try {
-                    helper.invokeGL(drawable, context, displayAction, initAction);
-                } finally {
-                    unlockSurface();
-                }
-            }
+            // surface is locked/unlocked implicit by context's makeCurrent/release 
+            helper.invokeGL(drawable, context, displayAction, initAction);
         }
     }
     
@@ -910,12 +894,9 @@ public class GLWindow implements GLAutoDrawable, Window, NEWTEventConsumer, FPSC
         System.err.println(GlueGenVersion.getInstance());
         System.err.println(JoglVersion.getInstance());
 
+        System.err.println(JoglVersion.getDefaultOpenGLInfo(null).toString());
+
         final GLProfile glp = GLProfile.getDefault();
-        final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp);
-        final List<GLCapabilitiesImmutable> availCaps = factory.getAvailableCapabilities(null);
-        for(int i=0; i<availCaps.size(); i++) {
-            System.err.println(availCaps.get(i));
-        }
         final GLCapabilitiesImmutable caps = new GLCapabilities( glp );
 
         GLWindow glWindow = GLWindow.create(caps);
diff --git a/src/newt/classes/com/jogamp/newt/util/MainThread.java b/src/newt/classes/com/jogamp/newt/util/MainThread.java
index e71ef75..bbe415b 100644
--- a/src/newt/classes/com/jogamp/newt/util/MainThread.java
+++ b/src/newt/classes/com/jogamp/newt/util/MainThread.java
@@ -39,8 +39,8 @@ package com.jogamp.newt.util;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.InvocationTargetException;
-import java.security.AccessControlContext;
-import java.security.AccessController;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.media.nativewindow.NativeWindowFactory;
 
@@ -95,19 +95,19 @@ public class MainThread {
     private static final String MACOSXDisplayClassName = "jogamp.newt.driver.macosx.MacDisplay";
     private static final Platform.OSType osType;
     private static final boolean isMacOSX;
-        
+    private static final ThreadGroup rootThreadGroup;
     
     /** if true, use the main thread EDT, otherwise AWT's EDT */
     public static final boolean  HINT_USE_MAIN_THREAD;
     
     static {
-        final AccessControlContext localACC = AccessController.getContext();
         NativeWindowFactory.initSingleton(true);
         NEWTJNILibLoader.loadNEWT();
         HINT_USE_MAIN_THREAD = !NativeWindowFactory.isAWTAvailable() || 
-                                Debug.getBooleanProperty("newt.MainThread.force", true, localACC);
+                                Debug.getBooleanProperty("newt.MainThread.force", true);
         osType = Platform.getOSType();
-        isMacOSX = osType == Platform.OSType.MACOS;                
+        isMacOSX = osType == Platform.OSType.MACOS;
+        rootThreadGroup = getRootThreadGroup();
     }
     
     public static boolean useMainThread = false;
@@ -115,44 +115,116 @@ public class MainThread {
     protected static final boolean DEBUG = Debug.debug("MainThread");
 
     private static final MainThread singletonMainThread = new MainThread(); // one singleton MainThread
-
+    
+    private static final ThreadGroup getRootThreadGroup() {
+        ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
+        ThreadGroup parentGroup;
+        while ( ( parentGroup = rootGroup.getParent() ) != null ) {
+            rootGroup = parentGroup;
+        }
+        return rootGroup;   
+    }
+    
+    private static final Thread[] getAllThreads(int[] count) {
+        int tn;
+        Thread[] threads = new Thread[ rootThreadGroup.activeCount() ];
+        while ( ( tn = rootThreadGroup.enumerate( threads, true ) ) == threads.length ) {
+            threads = new Thread[ threads.length * 2 ];
+        }
+        count[0] = tn;
+        return threads;
+    }
+    private static final List<Thread> getNonDaemonThreads() {
+        List<Thread> res = new ArrayList<Thread>();
+        int[] tn = { 0 };
+        Thread[] threads = getAllThreads(tn);
+        for(int i = tn[0] - 1; i >= 0; i--) {
+            final Thread thread = threads[i];
+            try {
+                if(thread.isAlive() && !thread.isDaemon()) {
+                    res.add(thread);
+                    if(DEBUG) System.err.println("XXX0: "+thread.getName()+", "+thread);
+                }
+            } catch (Throwable t) {
+                t.printStackTrace();
+            }
+        }
+        return res;        
+    }
+    private static final int getNonDaemonThreadCount(List<Thread> ignoreThreads) {
+        int res = 0;
+        int[] tn = { 0 };
+        Thread[] threads = getAllThreads(tn);
+        
+        for(int i = tn[0] - 1; i >= 0; i--) {
+            final Thread thread = threads[i];
+            try {
+                if(thread.isAlive() && !thread.isDaemon() && !ignoreThreads.contains(thread)) {                    
+                    res++;
+                    if(DEBUG) System.err.println("MainAction.run(): non daemon thread: "+thread);
+                }
+            } catch (Throwable t) {
+                t.printStackTrace();
+            }
+        }
+        return res;        
+    }
+    
     static class UserApp extends Thread {
-        private String mainClassName;
-        private String[] mainClassArgs;
+        private final String mainClassNameShort;
+        private final String mainClassName;
+        private final String[] mainClassArgs;
+        private final Method mainClassMain;
+        private List<Thread> nonDaemonThreadsAtStart;
 
-        private Method mainClassMain;
-
-        public UserApp(String mainClassName, String[] mainClassArgs) {
+        public UserApp(String mainClassName, String[] mainClassArgs) throws SecurityException, NoSuchMethodException, ClassNotFoundException {
+            super();
             this.mainClassName=mainClassName;
             this.mainClassArgs=mainClassArgs;
+            
+            final Class<?> mainClass = ReflectionUtil.getClass(mainClassName, true, getClass().getClassLoader());
+            if(null==mainClass) {
+                throw new ClassNotFoundException("MainAction couldn't find main class "+mainClassName);
+            }
+            mainClassNameShort = mainClass.getSimpleName();
+            mainClassMain = mainClass.getDeclaredMethod("main", new Class[] { String[].class });
+            mainClassMain.setAccessible(true);
+
+            setName(getName()+"-UserApp-"+mainClassNameShort);
+            setDaemon(false);
+            
+            if(DEBUG) System.err.println("MainAction(): instantiated: "+getName()+", is daemon "+isDaemon()+", main-class: "+mainClass.getName());
         }
 
         @Override
         public void run() {
-            setName(getName()+"-UserApp");
-            
-            if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" start");
+            nonDaemonThreadsAtStart = getNonDaemonThreads();
+            if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" start, nonDaemonThreadsAtStart "+nonDaemonThreadsAtStart);
             // start user app ..
             try {
-                Class<?> mainClass = ReflectionUtil.getClass(mainClassName, true, getClass().getClassLoader());
-                if(null==mainClass) {
-                    throw new RuntimeException(new ClassNotFoundException("MainAction couldn't find main class "+mainClassName));
-                }
-                try {
-                    mainClassMain = mainClass.getDeclaredMethod("main", new Class[] { String[].class });
-                    mainClassMain.setAccessible(true);
-                } catch (Throwable t) {
-                    throw new RuntimeException(t);
-                }
                 if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" invoke "+mainClassName);
                 mainClassMain.invoke(null, new Object[] { mainClassArgs } );
             } catch (InvocationTargetException ite) {
                 ite.getTargetException().printStackTrace();
+                return;
             } catch (Throwable t) {
                 t.printStackTrace();
+                return;
             }
 
-            if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" user app fin");
+            // wait until no more active non-daemon threads are running
+            {
+                int ndtr;
+                while( 0 < ( ndtr = getNonDaemonThreadCount(nonDaemonThreadsAtStart) ) ) {
+                    if(DEBUG) System.err.println("MainAction.run(): post user app, non daemon threads alive: "+ndtr);
+                    try {
+                        Thread.sleep(1000);
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                }
+                if(DEBUG) System.err.println("MainAction.run(): "+Thread.currentThread().getName()+" user app fin: "+ndtr);
+            }
 
             if ( useMainThread ) {
                 if(isMacOSX) {
@@ -177,8 +249,11 @@ public class MainThread {
     }
     private static UserApp mainAction;
 
-    /** Your new java application main entry, which pipelines your application */
-    public static void main(String[] args) {
+    /** Your new java application main entry, which pipelines your application 
+     * @throws ClassNotFoundException 
+     * @throws NoSuchMethodException 
+     * @throws SecurityException */
+    public static void main(String[] args) throws SecurityException, NoSuchMethodException, ClassNotFoundException {
         final Thread cur = Thread.currentThread();
         
         useMainThread = HINT_USE_MAIN_THREAD;
diff --git a/src/newt/classes/com/jogamp/newt/util/MonitorMode.java b/src/newt/classes/com/jogamp/newt/util/MonitorMode.java
index 5a8bf5b..8104f20 100644
--- a/src/newt/classes/com/jogamp/newt/util/MonitorMode.java
+++ b/src/newt/classes/com/jogamp/newt/util/MonitorMode.java
@@ -43,8 +43,9 @@ public class MonitorMode {
     int refreshRate;
 
     public MonitorMode(SurfaceSize surfaceSize, DimensionImmutable screenSizeMM, int refreshRate) {
-        if(null==surfaceSize || refreshRate<=0) {
-            throw new IllegalArgumentException("surfaceSize must be set and refreshRate greater 0");
+        // Don't validate screenSizeMM and refreshRate, since they may not be supported by the OS 
+        if(null==surfaceSize) {
+            throw new IllegalArgumentException("surfaceSize must be set ("+surfaceSize+")");
         }
         this.surfaceSize=surfaceSize;
         this.screenSizeMM=screenSizeMM;
diff --git a/src/newt/classes/jogamp/newt/Debug.java b/src/newt/classes/jogamp/newt/Debug.java
index 85fbbe7..3c83da4 100644
--- a/src/newt/classes/jogamp/newt/Debug.java
+++ b/src/newt/classes/jogamp/newt/Debug.java
@@ -39,18 +39,17 @@
 
 package jogamp.newt;
 
-import java.security.*;
+import com.jogamp.common.util.PropertyAccess;
 
 /** Helper routines for logging and debugging. */
 
-public class Debug {
+public class Debug extends PropertyAccess {
   // Some common properties
-  private static boolean verbose;
-  private static boolean debugAll;
-  private static AccessControlContext localACC;
+  private static final boolean verbose;
+  private static final boolean debugAll;
   
   static {
-    localACC=AccessController.getContext();
+    PropertyAccess.addTrustedPrefix("newt.", Debug.class);
     verbose = isPropertyDefined("newt.verbose", true);
     debugAll = isPropertyDefined("newt.debug", true);
     if (verbose) {
@@ -61,71 +60,18 @@ public class Debug {
     }
   }
 
-  static int getIntProperty(final String property, final boolean jnlpAlias) {
-      return getIntProperty(property, jnlpAlias, localACC);
+  public static final boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
+    return PropertyAccess.isPropertyDefined(property, jnlpAlias, null);
   }
-
-  public static int getIntProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    int i=0;
-    try {
-        Integer iv = Integer.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-        i = iv.intValue();
-    } catch (NumberFormatException nfe) {}
-    return i;
-  }
-
-  static boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
-    return getBooleanProperty(property, jnlpAlias, localACC);
-  }
-
-  public static boolean getBooleanProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    Boolean b = Boolean.valueOf(Debug.getProperty(property, jnlpAlias, acc));
-    return b.booleanValue();
-  }
-
-  static boolean isPropertyDefined(final String property, final boolean jnlpAlias) {
-    return isPropertyDefined(property, jnlpAlias, localACC);
-  }
-
-  public static boolean isPropertyDefined(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    return (Debug.getProperty(property, jnlpAlias, acc) != null) ? true : false;
-  }
-
-  static String getProperty(final String property, final boolean jnlpAlias) {
-    return getProperty(property, jnlpAlias, localACC);
+    
+  public static final int getIntProperty(final String property, final boolean jnlpAlias, int defaultValue) {
+      return PropertyAccess.getIntProperty(property, jnlpAlias, null, defaultValue);
   }
-
-  public static String getProperty(final String property, final boolean jnlpAlias, final AccessControlContext acc) {
-    String s=null;
-    if(null!=acc && acc.equals(localACC)) {
-        s = (String) AccessController.doPrivileged(new PrivilegedAction() {
-            public Object run() {
-              String val=null;
-              try {
-                  val = System.getProperty(property);
-              } catch (Exception e) {}
-              if(null==val && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-                  try {
-                      val = System.getProperty(jnlp_prefix + property);
-                  } catch (Exception e) {}
-              }
-              return val;
-            }
-          });
-    } else {
-        try {
-            s = System.getProperty(property);
-        } catch (Exception e) {}
-        if(null==s && jnlpAlias && !property.startsWith(jnlp_prefix)) {
-            try {
-                s = System.getProperty(jnlp_prefix + property);
-            } catch (Exception e) {}
-        }
-    }
-    return s;
+  
+  public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias) {
+      return PropertyAccess.getBooleanProperty(property, jnlpAlias, null);
   }
-  public static final String jnlp_prefix = "jnlp." ;
-
+  
   public static boolean verbose() {
     return verbose;
   }
diff --git a/src/newt/classes/jogamp/newt/DisplayImpl.java b/src/newt/classes/jogamp/newt/DisplayImpl.java
index 908a44e..f2f3513 100644
--- a/src/newt/classes/jogamp/newt/DisplayImpl.java
+++ b/src/newt/classes/jogamp/newt/DisplayImpl.java
@@ -54,17 +54,17 @@ public abstract class DisplayImpl extends Display {
     {
         Class<?> displayClass = NewtFactory.getCustomClass(type, "Display");
         if(null==displayClass) {
-            if (NativeWindowFactory.TYPE_ANDROID.equals(type)) {
+            if (NativeWindowFactory.TYPE_ANDROID == type) {
                 displayClass = Class.forName("jogamp.newt.driver.android.AndroidDisplay");
-            } else if (NativeWindowFactory.TYPE_EGL.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_EGL == type) {
                 displayClass = Class.forName("jogamp.newt.driver.kd.KDDisplay");
-            } else if (NativeWindowFactory.TYPE_WINDOWS.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_WINDOWS == type) {
                 displayClass = Class.forName("jogamp.newt.driver.windows.WindowsDisplay");
-            } else if (NativeWindowFactory.TYPE_MACOSX.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_MACOSX == type) {
                 displayClass = Class.forName("jogamp.newt.driver.macosx.MacDisplay");
-            } else if (NativeWindowFactory.TYPE_X11.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_X11 == type) {
                 displayClass = Class.forName("jogamp.newt.driver.x11.X11Display");
-            } else if (NativeWindowFactory.TYPE_AWT.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_AWT == type) {
                 displayClass = Class.forName("jogamp.newt.driver.awt.AWTDisplay");
             } else {
                 throw new RuntimeException("Unknown display type \"" + type + "\"");
diff --git a/src/newt/classes/jogamp/newt/ScreenImpl.java b/src/newt/classes/jogamp/newt/ScreenImpl.java
index 6ea9aff..72f1b5a 100644
--- a/src/newt/classes/jogamp/newt/ScreenImpl.java
+++ b/src/newt/classes/jogamp/newt/ScreenImpl.java
@@ -34,6 +34,21 @@
 
 package jogamp.newt;
 
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.media.nativewindow.AbstractGraphicsScreen;
+import javax.media.nativewindow.NativeWindowException;
+import javax.media.nativewindow.NativeWindowFactory;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.DimensionImmutable;
+import javax.media.nativewindow.util.Point;
+import javax.media.nativewindow.util.SurfaceSize;
+
+
 import com.jogamp.common.util.ArrayHashSet;
 import com.jogamp.common.util.IntIntHashMap;
 import com.jogamp.newt.Display;
@@ -44,28 +59,27 @@ import com.jogamp.newt.event.ScreenModeListener;
 import com.jogamp.newt.util.MonitorMode;
 import com.jogamp.newt.util.ScreenModeUtil;
 
-import javax.media.nativewindow.*;
-import javax.media.nativewindow.util.DimensionImmutable;
-import javax.media.nativewindow.util.SurfaceSize;
-
-import java.security.*;
-import java.util.ArrayList;
-import java.util.List;
-
 public abstract class ScreenImpl extends Screen implements ScreenModeListener {
     protected static final boolean DEBUG_TEST_SCREENMODE_DISABLED = Debug.isPropertyDefined("newt.test.Screen.disableScreenMode", true);
 
+    protected static final int default_sm_bpp = 32;
+    protected static final int default_sm_widthmm = 519;
+    protected static final int default_sm_heightmm = 324;
+    protected static final int default_sm_rate = 60;
+    protected static final int default_sm_rotation = 0;
+    
     protected DisplayImpl display;
     protected int screen_idx;
     protected String fqname;
     protected int hashCode;
     protected AbstractGraphicsScreen aScreen;
     protected int refCount; // number of Screen references by Window
-    protected int width=-1, height=-1; // detected values: set using setScreenSize
-    protected static int usrWidth=-1, usrHeight=-1; // property values: newt.ws.swidth and newt.ws.sheight
-    private static AccessControlContext localACC = AccessController.getContext();
+    protected Point vOrigin = new Point(0, 0); // virtual top-left origin
+    protected Dimension vSize = new Dimension(0, 0); // virtual rotated screen size
+    protected static Dimension usrSize = null; // property values: newt.ws.swidth and newt.ws.sheight
+    protected static volatile boolean usrSizeQueried = false;
     private ArrayList<ScreenModeListener> referencedScreenModeListener = new ArrayList<ScreenModeListener>();
-    long t0; // creationTime
+    private long tCreated; // creationTime
 
     static {
         AccessController.doPrivileged(new PrivilegedAction<Object>() {
@@ -81,17 +95,17 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
     {
         Class<?> screenClass = NewtFactory.getCustomClass(type, "Screen");
         if(null==screenClass) {
-            if (NativeWindowFactory.TYPE_ANDROID.equals(type)) {
+            if (NativeWindowFactory.TYPE_ANDROID == type) {
                 screenClass = Class.forName("jogamp.newt.driver.android.AndroidScreen");
-            } else if (NativeWindowFactory.TYPE_EGL.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_EGL == type) {
                 screenClass = Class.forName("jogamp.newt.driver.kd.KDScreen");
-            } else if (NativeWindowFactory.TYPE_WINDOWS.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_WINDOWS == type) {
                 screenClass = Class.forName("jogamp.newt.driver.windows.WindowsScreen");
-            } else if (NativeWindowFactory.TYPE_MACOSX.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_MACOSX == type) {
                 screenClass = Class.forName("jogamp.newt.driver.macosx.MacScreen");
-            } else if (NativeWindowFactory.TYPE_X11.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_X11 == type) {
                 screenClass = Class.forName("jogamp.newt.driver.x11.X11Screen");
-            } else if (NativeWindowFactory.TYPE_AWT.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_AWT == type) {
                 screenClass = Class.forName("jogamp.newt.driver.awt.AWTScreen");
             } else {
                 throw new RuntimeException("Unknown window type \"" + type + "\"");
@@ -100,32 +114,36 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
         return (Class<? extends Screen>)screenClass;
     }
 
-    public static Screen create(Display display, final int idx) {
+    public static Screen create(Display display, int idx) {
         try {
-            if(usrWidth<0 || usrHeight<0) {
+            if(!usrSizeQueried) {
                 synchronized (Screen.class) {
-                    if(usrWidth<0 || usrHeight<0) {
-                        usrWidth  = Debug.getIntProperty("newt.ws.swidth", true, localACC);
-                        usrHeight = Debug.getIntProperty("newt.ws.sheight", true, localACC);
-                        if(usrWidth>0 || usrHeight>0) {
-                            System.err.println("User screen size "+usrWidth+"x"+usrHeight);
+                    if(!usrSizeQueried) {
+                        usrSizeQueried = true;
+                        final int w = Debug.getIntProperty("newt.ws.swidth", true, 0);
+                        final int h = Debug.getIntProperty("newt.ws.sheight", true, 0);                        
+                        if(w>0 && h>0) {
+                            usrSize = new Dimension(w, h);
+                            System.err.println("User screen size "+usrSize);
                         }
                     }
                 }
             }
             synchronized(screenList) {
+                Class<? extends Screen> screenClass = getScreenClass(display.getType());
+                ScreenImpl screen  = (ScreenImpl) screenClass.newInstance();
+                screen.display = (DisplayImpl) display;
+                idx = screen.validateScreenIndex(idx);
                 {
                     Screen screen0 = ScreenImpl.getLastScreenOf(display, idx, -1);
                     if(null != screen0) {
                         if(DEBUG) {
                             System.err.println("Screen.create() REUSE: "+screen0+" "+Display.getThreadName());
                         }
+                        screen = null;
                         return screen0;
                     }
                 }
-                Class<? extends Screen> screenClass = getScreenClass(display.getType());
-                ScreenImpl screen  = (ScreenImpl) screenClass.newInstance();
-                screen.display = (DisplayImpl) display;
                 screen.screen_idx = idx;
                 screen.fqname = (display.getFQName()+idx).intern();
                 screen.hashCode = screen.fqname.hashCode();
@@ -164,20 +182,26 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
 
     public synchronized final void createNative()
             throws NativeWindowException
-    {
+    {        
         if(null == aScreen) {
             if(DEBUG) {
+                tCreated = System.nanoTime();
                 System.err.println("Screen.createNative() START ("+DisplayImpl.getThreadName()+", "+this+")");
+            } else {
+                tCreated = 0;
             }
-            t0 = System.currentTimeMillis();
+            
             display.addReference();
+            
             createNativeImpl();
             if(null == aScreen) {
                 throw new NativeWindowException("Screen.createNative() failed to instanciate an AbstractGraphicsScreen");
             }
+            
             initScreenModeStatus();
+            updateVirtualScreenOriginAndSize();            
             if(DEBUG) {
-                System.err.println("Screen.createNative() END ("+DisplayImpl.getThreadName()+", "+this+")");
+                System.err.println("Screen.createNative() END ("+DisplayImpl.getThreadName()+", "+this+"), total "+ (System.nanoTime()-tCreated)/1e6 +"ms");
             }
             synchronized(screenList) {
                 screensActive++;
@@ -238,19 +262,39 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
 
     protected abstract void createNativeImpl();
     protected abstract void closeNativeImpl();
-
+    
+    /**
+     * Returns the validated screen index, which is either the passed <code>idx</code>
+     * value or <code>0</code>.
+     * <p>
+     * On big-desktops this shall return always 0.
+     * </p>
+     */
+    protected abstract int validateScreenIndex(int idx);
+    
+    /**
+     * Stores the virtual origin and virtual <b>rotated</b> screen size.
+     * <p>
+     * This method is called after the ScreenMode has been set, 
+     * hence you may utilize it.
+     * </p> 
+     * @param virtualOrigin the store for the virtual origin
+     * @param virtualSize the store for the virtual rotated size
+     */
+    protected abstract void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize); 
+    
     public final String getFQName() {
         return fqname;
     }
 
     /**
-     * Set the <b>rotated</b> ScreenSize.
-     * @see com.jogamp.newt.ScreenMode#getRotatedWidth()
-     * @see com.jogamp.newt.ScreenMode#getRotatedHeight()
+     * Updates the <b>rotated</b> virtual ScreenSize using the native impl.
      */
-    protected void setScreenSize(int w, int h) {
-        System.err.println("Detected screen size "+w+"x"+h);
-        width=w; height=h;
+    protected void updateVirtualScreenOriginAndSize() {
+        getVirtualScreenOriginAndSize(vOrigin, vSize);
+        if(DEBUG) {
+            System.err.println("Detected screen origin "+vOrigin+", size "+vSize);
+        }
     }
 
     public final Display getDisplay() {
@@ -269,21 +313,15 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
         return null != aScreen;
     }
 
+    public int getX() { return vOrigin.getX(); }
+    public int getY() { return vOrigin.getY(); }
     
-    /**
-     * @return the <b>rotated</b> width.
-     * @see com.jogamp.newt.ScreenMode#getRotatedWidth()
-     */
     public final int getWidth() {
-        return (usrWidth>0) ? usrWidth : (width>0) ? width : 480;
+        return (null != usrSize) ? usrSize.getWidth() : vSize.getWidth();
     }
 
-    /**
-     * @return the <b>rotated</b> height
-     * @see com.jogamp.newt.ScreenMode#getRotatedHeight()
-     */
     public final int getHeight() {
-        return (usrHeight>0) ? usrHeight : (height>0) ? height : 480;
+        return (null != usrSize) ? usrSize.getHeight() : vSize.getHeight();
     }
 
     @Override
@@ -333,7 +371,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
         ScreenMode smU = getScreenModesOrig().get(screenMode); // unify via value hash
         if(smU.equals(smC)) {
             if(DEBUG) {
-                System.err.println("Screen.setCurrentScreenMode ("+(System.currentTimeMillis()-t0)+"): 0.0 is-current (skip) "+smU+" == "+smC);
+                System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tCreated)+"): 0.0 is-current (skip) "+smU+" == "+smC);
             }            
             return true;
         }
@@ -344,35 +382,26 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
         boolean success;
         sms.lock();
         try {
-            long t0=0, t1=0;
+            final long tStart;
             if(DEBUG) {
-                System.err.println("Screen.setCurrentScreenMode ("+(System.currentTimeMillis()-t0)+"): 0.0 "+smU);
-                t0 = System.currentTimeMillis();
-            }                
-
+                tStart = System.nanoTime();                
+            } else {
+                tStart = 0;
+            }
+            
             sms.fireScreenModeChangeNotify(smU);
-
             if(DEBUG) {
-                System.err.println("Screen.setCurrentScreenMode ("+(System.currentTimeMillis()-t0)+"): 0.1 "+smU);
-                t1 = System.currentTimeMillis();
+                System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): fireScreenModeChangeNotify() "+smU);
             }
 
-            success = setCurrentScreenModeImpl(smU);                    
-            if(success) {
-                setScreenSize(smU.getRotatedWidth(), smU.getRotatedHeight());
-            }
-            
+            success = setCurrentScreenModeImpl(smU);                                
             if(DEBUG) {
-                t1 = System.currentTimeMillis() - t1;
-                System.err.println("Screen.setCurrentScreenMode ("+(System.currentTimeMillis()-t0)+"): X.0 "+smU+", success: "+success);
+                System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): setCurrentScreenModeImpl() "+smU+", success: "+success);
             }
 
-            sms.fireScreenModeChanged(smU, success);
-                            
+            sms.fireScreenModeChanged(smU, success);                            
             if(DEBUG) {
-                t0 = System.currentTimeMillis() - t0;
-                System.err.println("Screen.setCurrentScreenMode ("+(System.currentTimeMillis()-t0)+"): X.X "+smU+", success: "+success+
-                                   " - dt0 "+t0+"ms, dt1 "+t1+"ms");
+                System.err.println("Screen.setCurrentScreenMode ("+(System.nanoTime()-tStart)/1e6+"ms): X.X "+smU+", success: "+success);
             }
         } finally {
             sms.unlock();
@@ -388,7 +417,7 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
 
     public void screenModeChanged(ScreenMode sm, boolean success) {
         if(success) {
-            setScreenSize(sm.getRotatedWidth(), sm.getRotatedHeight());
+            updateVirtualScreenOriginAndSize();
         }
         for(int i=0; i<referencedScreenModeListener.size(); i++) {
             ((ScreenModeListener)referencedScreenModeListener.get(i)).screenModeChanged(sm, success);
@@ -462,18 +491,26 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
      * the current screen size and dummy values.
      */
     protected ScreenMode getCurrentScreenModeIntern() {
-        ScreenMode res = getCurrentScreenModeImpl();
+        ScreenMode res;
+        if(DEBUG_TEST_SCREENMODE_DISABLED) {
+            res = null;
+        } else {
+            res = getCurrentScreenModeImpl();
+        }
         if(null == res) {
+            if( 0==getWidth()*getHeight() ) {
+                updateVirtualScreenOriginAndSize();
+            }
             int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL];
             int i = 0;
             props[i++] = 0; // set later for verification of iterator
             props[i++] = getWidth();  // width
             props[i++] = getHeight(); // height
-            props[i++] = 32;   // bpp
-            props[i++] = 519;  // widthmm
-            props[i++] = 324;  // heightmm
-            props[i++] = 60;   // rate
-            props[i++] = 0;    // rot
+            props[i++] = default_sm_bpp;
+            props[i++] = default_sm_widthmm;
+            props[i++] = default_sm_heightmm;
+            props[i++] = default_sm_rate;
+            props[i++] = default_sm_rotation;
             props[i - ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL] = i; // count
             res = ScreenModeUtil.streamIn(props, 0);
         }
@@ -489,6 +526,14 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
     }
 
     private ScreenModeStatus initScreenModeStatus() {
+        long t0;
+        if(DEBUG) {
+            t0 = System.nanoTime();
+            System.err.println("Screen.initScreenModeStatus() START ("+DisplayImpl.getThreadName()+", "+this+")");
+        } else {
+            t0 = 0;
+        }
+
         ScreenModeStatus sms;
         ScreenModeStatus.lockScreenModeStatus();
         try {
@@ -501,11 +546,12 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
                 }
 
                 ArrayHashSet<ScreenMode> screenModes = collectNativeScreenModes(screenModesIdx2NativeIdx);
-                if(screenModes.size()==0) {
-                    if(DEBUG) {
-                        System.err.println("ScreenImpl.initScreenModeStatus: added current (last resort, collect failed): "+currentSM);
+                screenModes.getOrAdd(currentSM);
+                if(DEBUG) {
+                    int i=0;
+                    for(Iterator<ScreenMode> iter=screenModes.iterator(); iter.hasNext(); i++) {
+                        System.err.println(i+": "+iter.next());
                     }
-                    screenModes.getOrAdd(currentSM);
                 }
                 
                 sms = new ScreenModeStatus(screenModes, screenModesIdx2NativeIdx);
@@ -519,6 +565,9 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
         } finally {
             ScreenModeStatus.unlockScreenModeStatus();
         }
+        if(DEBUG) {
+            System.err.println("Screen.initScreenModeStatus() END dt "+ (System.nanoTime()-t0)/1e6 +"ms");
+        }
         return sms;
     }
 
@@ -549,9 +598,18 @@ public abstract class ScreenImpl extends Screen implements ScreenModeListener {
                 int nativeId = smProps[0];
                 int screenModeIdx = ScreenModeUtil.streamIn(resolutionPool, surfaceSizePool, screenSizeMMPool,
                                                             monitorModePool, screenModePool, smProps, 1);
+                if(DEBUG) {
+                    System.err.println("ScreenImpl.collectNativeScreenModes: #"+num+": idx: "+nativeId+" native -> "+screenModeIdx+" newt");
+                }
+                
                 if(screenModeIdx >= 0) {
                     screenModesIdx2NativeId.put(screenModeIdx, nativeId);
                 }
+            } else if(DEBUG) {
+                System.err.println("ScreenImpl.collectNativeScreenModes: #"+num+": smProps: "+(null!=smProps)+
+                                   ", len: "+(null != smProps ? smProps.length : 0)+
+                                   ", bpp: "+(null != smProps && 0 < smProps.length ? smProps[idxBpp] : 0)+
+                                   " - DROPPING");
             }
             num++;
         } while ( null != smProps && 0 < smProps.length );
diff --git a/src/newt/classes/jogamp/newt/WindowImpl.java b/src/newt/classes/jogamp/newt/WindowImpl.java
index a8e93d4..143e7c1 100644
--- a/src/newt/classes/jogamp/newt/WindowImpl.java
+++ b/src/newt/classes/jogamp/newt/WindowImpl.java
@@ -66,6 +66,7 @@ import javax.media.nativewindow.NativeWindow;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.nativewindow.SurfaceUpdatedListener;
+import javax.media.nativewindow.WindowClosingProtocol;
 import javax.media.nativewindow.util.DimensionImmutable;
 import javax.media.nativewindow.util.Insets;
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -78,6 +79,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
 {
     public static final boolean DEBUG_TEST_REPARENT_INCOMPATIBLE = Debug.isPropertyDefined("newt.test.Window.reparent.incompatible", true);
     
+    /** Timeout of queued events (repaint and resize) */
+    static final long QUEUED_EVENT_TO = 1200; // ms    
+    
     private volatile long windowHandle = 0; // lifecycle critical
     private volatile boolean visible = false; // lifecycle critical
     private RecursiveLock windowLock = LockFactory.createRecursiveLock();  // Window instance wide lock
@@ -90,25 +94,23 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     private AbstractGraphicsConfiguration config = null; // control access due to delegation
     protected CapabilitiesImmutable capsRequested = null;
     protected CapabilitiesChooser capabilitiesChooser = null; // default null -> default
-    protected boolean fullscreen = false, hasFocus = false;    
-    protected int width = 128, height = 128; // client-area size w/o insets, default: may be overwritten by user
-    protected int x = -1, y = -1; // client-area pos w/o insets, default: undefined (allow WM to choose if not set by user)
-    protected Insets insets = new Insets(); // insets of decoration (if top-level && decorated)
+    private boolean fullscreen = false, hasFocus = false, brokenFocusChange = false;    
+    private int width = 128, height = 128; // client-area size w/o insets, default: may be overwritten by user
+    private int x = 64, y = 64; // client-area pos w/o insets
+    private boolean autoPosition = true; // default: true (allow WM to choose top-level position, if not set by user)
+    private Insets insets = new Insets(); // insets of decoration (if top-level && decorated)
         
-    protected int nfs_width, nfs_height, nfs_x, nfs_y; // non fullscreen client-area size/pos w/o insets
-    protected String title = "Newt Window";
-    protected boolean undecorated = false;
-    protected boolean alwaysOnTop = false;
+    private int nfs_width, nfs_height, nfs_x, nfs_y; // non fullscreen client-area size/pos w/o insets
+    private NativeWindow nfs_parent = null;          // non fullscreen parent, in case explicit reparenting is performed (offscreen)
+    private String title = "Newt Window";
+    private boolean undecorated = false;
+    private boolean alwaysOnTop = false;
     private boolean pointerVisible = true;
     private boolean pointerConfined = false;
     private LifecycleHook lifecycleHook = null;
 
-    private DestroyAction destroyAction = new DestroyAction();
     private boolean handleDestroyNotify = true;
 
-    private ReparentActionRecreate reparentActionRecreate = new ReparentActionRecreate();
-
-    private RequestFocusAction requestFocusAction = new RequestFocusAction();
     private FocusRunnable focusAction = null;
     private KeyListener keyboardFocusHandler = null;
 
@@ -121,16 +123,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     private int  mouseButtonPressed = 0;  // current pressed mouse button number
     private long lastMousePressed = 0;    // last time when a mouse button was pressed
     private int  lastMouseClickCount = 0; // last mouse button click count
-    protected boolean mouseInWindow = false;// mouse entered window - is inside the window (may be synthetic)
-    protected Point lastMousePosition = new Point();
+    private boolean mouseInWindow = false;// mouse entered window - is inside the window (may be synthetic)
+    private Point lastMousePosition = new Point();
 
     private ArrayList<KeyListener> keyListeners = new ArrayList<KeyListener>();
 
     private ArrayList<WindowListener> windowListeners  = new ArrayList<WindowListener>();
     private boolean repaintQueued = false;
 
-    ScreenModeListenerImpl screenModeListenerImpl = new ScreenModeListenerImpl();
-
     // Workaround for initialization order problems on Mac OS X
     // between native Newt and (apparently) Fmod -- if Fmod is
     // initialized first then the connection to the window server
@@ -154,17 +154,17 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     {
         Class<?> windowClass = NewtFactory.getCustomClass(type, "Window");
         if(null==windowClass) {
-            if (NativeWindowFactory.TYPE_ANDROID.equals(type)) {
+            if (NativeWindowFactory.TYPE_ANDROID == type) {
                 windowClass = Class.forName("jogamp.newt.driver.android.AndroidWindow");
-            } else if (NativeWindowFactory.TYPE_EGL.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_EGL == type) {
                 windowClass = Class.forName("jogamp.newt.driver.kd.KDWindow");
-            } else if (NativeWindowFactory.TYPE_WINDOWS.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_WINDOWS == type) {
                 windowClass = Class.forName("jogamp.newt.driver.windows.WindowsWindow");
-            } else if (NativeWindowFactory.TYPE_MACOSX.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_MACOSX == type) {
                 windowClass = Class.forName("jogamp.newt.driver.macosx.MacWindow");
-            } else if (NativeWindowFactory.TYPE_X11.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_X11 == type) {
                 windowClass = Class.forName("jogamp.newt.driver.x11.X11Window");
-            } else if (NativeWindowFactory.TYPE_AWT.equals(type)) {
+            } else if (NativeWindowFactory.TYPE_AWT == type) {
                 windowClass = Class.forName("jogamp.newt.driver.awt.AWTWindow");
             } else {
                 throw new NativeWindowException("Unknown window type \"" + type + "\"");
@@ -269,17 +269,24 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     }
 
     private boolean createNative() {
+        long tStart;
         if(DEBUG_IMPLEMENTATION) {
+            tStart = System.nanoTime();
             System.err.println("Window.createNative() START ("+getThreadName()+", "+this+")");
-        }        
+        } else {
+            tStart = 0;
+        }
+        
         if( null != parentWindow && 
             NativeSurface.LOCK_SURFACE_NOT_READY >= parentWindow.lockSurface() ) {
             throw new NativeWindowException("Parent surface lock: not ready: "+parentWindow);
-        }        
-        if( ( 0>x || 0>y ) && ( isUndecorated() || null != parentWindow ) ) {
-            // default child/undecorated window position is 0/0, if not set by user
-            x = 0; y = 0;
         }
+        
+        // child window: position defaults to 0/0, no auto position, no negative position
+        if( null != parentWindow && ( autoPosition || 0>getX() || 0>getY() ) ) {                
+            definePosition(0, 0);
+        }
+        boolean postParentlockFocus = false;
         try {
             if(validateParentWindowHandle()) {
                 if(screenReferenceAdded) {
@@ -295,10 +302,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     confinePointerImpl(pointerConfined);
                     if(waitForVisible(true, false)) {
                         if(isFullscreen()) {
-                            fullscreen = false;
-                            FullScreenActionImpl fsa = new FullScreenActionImpl(true);
-                            fsa.run();
+                            synchronized(fullScreenAction) {
+                                fullscreen = false; // trigger a state change
+                                fullScreenAction.init(true);
+                                fullScreenAction.run();
+                            }
                         }
+                        postParentlockFocus = true;
                     }
                 }
             }
@@ -307,8 +317,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 parentWindow.unlockSurface();
             }
         }
+        if(postParentlockFocus) {
+            // harmonize focus behavior for all platforms: focus on creation
+            requestFocusInt(isFullscreen() /* skipFocusAction */);
+            ((DisplayImpl) screen.getDisplay()).dispatchMessagesNative(); // status up2date
+        }
         if(DEBUG_IMPLEMENTATION) {
-            System.err.println("Window.createNative() END ("+getThreadName()+", "+this+")");
+            System.err.println("Window.createNative() END ("+getThreadName()+", "+this+") total "+ (System.nanoTime()-tStart)/1e6 +"ms");
         }
         return isNativeValid() ;
     }
@@ -370,17 +385,17 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     // WindowClosingProtocol implementation
     //
     private Object closingListenerLock = new Object();
-    private int defaultCloseOperation = DISPOSE_ON_CLOSE;
+    private WindowClosingMode defaultCloseOperation = WindowClosingMode.DISPOSE_ON_CLOSE;
 
-    public int getDefaultCloseOperation() {
+    public WindowClosingMode getDefaultCloseOperation() {
         synchronized (closingListenerLock) {
             return defaultCloseOperation;
         }
     }
 
-    public int setDefaultCloseOperation(int op) {
+    public WindowClosingMode setDefaultCloseOperation(WindowClosingMode op) {
         synchronized (closingListenerLock) {
-            int _op = defaultCloseOperation;
+            WindowClosingMode _op = defaultCloseOperation;
             defaultCloseOperation = op;
             return _op;
         }
@@ -414,12 +429,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
      * The implementation should invoke the referenced java state callbacks
      * to notify this Java object of state changes.</p>
      * 
-     * @see #windowDestroyNotify()
+     * @see #windowDestroyNotify(boolean)
      * @see #focusChanged(boolean, boolean)
      * @see #visibleChanged(boolean, boolean)
      * @see #sizeChanged(int,int)
      * @see #positionChanged(boolean,int, int)
-     * @see #windowDestroyNotify()
+     * @see #windowDestroyNotify(boolean)
      */
     protected abstract void createNativeImpl();
 
@@ -473,8 +488,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                               ( isAlwaysOnTop() ? FLAG_IS_ALWAYSONTOP : 0 ) |
                               ( visible ? FLAG_IS_VISIBLE : 0 ) ;
     }
-    protected static String getReconfigureFlagsAsString(StringBuffer sb, int flags) {
-        if(null == sb) { sb = new StringBuffer(); }
+    protected static String getReconfigureFlagsAsString(StringBuilder sb, int flags) {
+        if(null == sb) { sb = new StringBuilder(); }
         sb.append("[");
         
         if( 0 != ( FLAG_CHANGE_PARENTING & flags) ) {
@@ -712,7 +727,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
               }
             }
             if(!isNativeValid() && visible) {
-                if( 0<width*height ) {
+                if( 0<getWidth()*getHeight() ) {
                     nativeWindowCreated = createNative();
                     madeVisible = nativeWindowCreated;
                 }
@@ -720,7 +735,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 WindowImpl.this.visible = true;                
             } else if(WindowImpl.this.visible != visible) {
                 if(isNativeValid()) {
-                    setVisibleImpl(visible, x, y, width, height);
+                    setVisibleImpl(visible, getX(), getY(), getWidth(), getHeight());
                     WindowImpl.this.waitForVisible(visible, true);
                     madeVisible = visible;
                 }
@@ -741,92 +756,90 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
               }
             }
             if(DEBUG_IMPLEMENTATION) {
-                System.err.println("Window setVisible: END ("+getThreadName()+") "+x+"/"+y+" "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+WindowImpl.this.visible+", nativeWindowCreated: "+nativeWindowCreated+", madeVisible: "+madeVisible);
+                System.err.println("Window setVisible: END ("+getThreadName()+") "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+WindowImpl.this.visible+", nativeWindowCreated: "+nativeWindowCreated+", madeVisible: "+madeVisible);
             }
         } finally {
             windowLock.unlock();
         }
         if( nativeWindowCreated || madeVisible ) {
             sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout and repaint to listener
-        }        
-    }    
+        }
+    }
     private class VisibleAction implements Runnable {
         boolean visible;
 
-        private VisibleAction (boolean visible) {
+        private VisibleAction(boolean visible) {
             this.visible = visible;
         }
 
         public final void run() {
             setVisibleActionImpl(visible);
         }
-    }    
+    }
+
     public void setVisible(boolean visible) {
         if(DEBUG_IMPLEMENTATION) {
-            System.err.println("Window setVisible: START ("+getThreadName()+") "+x+"/"+y+" "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+this.visible+" -> "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+(null!=parentWindow));
-            Thread.dumpStack();
+            System.err.println("Window setVisible: START ("+getThreadName()+") "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible: "+this.visible+" -> "+visible+", parentWindowHandle "+toHexString(parentWindowHandle)+", parentWindow "+(null!=parentWindow));
         }
         runOnEDTIfAvail(true, new VisibleAction(visible));
     }
     
-    final void setSizeActionImpl(int width, int height) {
-        boolean recreate = false;
-        windowLock.lock();
-        try {
-            int visibleAction = 0; // 1 invisible, 2 visible (create)
-            if ( !fullscreen && ( width != WindowImpl.this.width || WindowImpl.this.height != height ) ) {
-                recreate = isNativeValid() && !getGraphicsConfiguration().getChosenCapabilities().isOnscreen();
-                if(DEBUG_IMPLEMENTATION) {
-                    System.err.println("Window setSize: START "+WindowImpl.this.width+"x"+WindowImpl.this.height+" -> "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible "+visible+", recreate "+recreate);
-                }
-                if(recreate) {
-                    // will trigger visibleAction:=2 -> create if wasVisible
-                    final boolean wasVisible = WindowImpl.this.visible;
-                    screen.addReference(); // retain screen            
-                    destroyAction.run();
-                    WindowImpl.this.visible = wasVisible;
-                }                
-                if ( isNativeValid() && 0>=width*height && visible ) {
-                    visibleAction=1; // invisible
-                    WindowImpl.this.width = 0;
-                    WindowImpl.this.height = 0;
-                } else if ( !isNativeValid() && 0<width*height && visible ) {
-                    visibleAction = 2; // visible (create)
-                    WindowImpl.this.width = width;
-                    WindowImpl.this.height = height;
-                } else if ( isNativeValid() ) {
-                    // this width/height will be set by windowChanged, called by the native implementation
-                    reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(0, isVisible()));
-                } else {
-                    WindowImpl.this.width = width;
-                    WindowImpl.this.height = height;
-                }
-                if(DEBUG_IMPLEMENTATION) {
-                    System.err.println("Window setSize: END "+WindowImpl.this.width+"x"+WindowImpl.this.height+", visibleAction "+visibleAction);
-                }                    
-                switch(visibleAction) {
-                    case 1: setVisibleActionImpl(false); break;
-                    case 2: setVisibleActionImpl(true); break;
-                }
-            }
-        } finally {
-            if(recreate) {
-                screen.removeReference(); // bring back ref-count
-            }
-            windowLock.unlock();
-        }        
-    }
     private class SetSizeAction implements Runnable {
         int width, height;
 
         private SetSizeAction(int w, int h) {
-            width = w;
-            height = h;
+            this.width = w;
+            this.height = h;
         }
+
         public final void run() {
-            setSizeActionImpl(width, height);
+            boolean recreate = false;
+            windowLock.lock();
+            try {
+                if ( !isFullscreen() && ( getWidth() != width || getHeight() != height ) ) {
+                    recreate = isNativeValid() && !getGraphicsConfiguration().getChosenCapabilities().isOnscreen();
+                    if(DEBUG_IMPLEMENTATION) {
+                        System.err.println("Window setSize: START "+getWidth()+"x"+getHeight()+" -> "+width+"x"+height+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle)+", visible "+visible+", recreate "+recreate);
+                    }
+                    if(recreate) {
+                        // will trigger visibleAction:=2 -> create if wasVisible
+                        final boolean wasVisible = WindowImpl.this.visible;
+                        screen.addReference(); // retain screen
+                        destroyAction.run();
+                        WindowImpl.this.visible = wasVisible;
+                    }
+                    int visibleAction; // 0 nop, 1 invisible, 2 visible (create)
+                    if ( isNativeValid() && 0>=width*height && visible ) {
+                        visibleAction=1; // invisible
+                        defineSize(0, 0);
+                    } else if ( !isNativeValid() && 0<width*height && visible ) {
+                        visibleAction = 2; // visible (create)
+                        defineSize(width, height);
+                    } else if ( isNativeValid() ) {
+                        visibleAction = 0;
+                        // this width/height will be set by windowChanged, called by the native implementation
+                        reconfigureWindowImpl(getX(), getY(), width, height, getReconfigureFlags(0, isVisible()));
+                    } else {
+                        visibleAction = 0;
+                        defineSize(width, height);
+                    }
+                    if(DEBUG_IMPLEMENTATION) {
+                        System.err.println("Window setSize: END "+getWidth()+"x"+getHeight()+", visibleAction "+visibleAction);
+                    }
+                    switch(visibleAction) {
+                        case 1: setVisibleActionImpl(false); break;
+                        case 2: setVisibleActionImpl(true); break;
+                    }
+                }
+            } finally {
+                if(recreate) {
+                    screen.removeReference(); // bring back ref-count
+                }
+                windowLock.unlock();
+            }
         }
-    }    
+    }
+
     public void setSize(int width, int height) {
         runOnEDTIfAvail(true, new SetSizeAction(width, height));
     }    
@@ -846,8 +859,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             windowLock.lock();
             try {
                 if(DEBUG_IMPLEMENTATION) {
-                    String msg = "!!! Window DestroyAction() "+getThreadName();
-                    System.err.println(msg);
+                    System.err.println("Window DestroyAction() "+getThreadName());
                 }
                 // Childs first ..
                 synchronized(childWindowsLock) {
@@ -891,16 +903,18 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     System.err.println("Window.destroy() END "+getThreadName()/*+", "+WindowImpl.this*/);
                 }
             } finally {
+                // update states before release window lock
+                setWindowHandle(0);
+                visible = false;
+                fullscreen = false;
+                hasFocus = false;
+                parentWindowHandle = 0;
+
                 windowLock.unlock();
             }
             if(animatorPaused) {
                 lifecycleHook.resumeRenderingAction();
             }
-            setWindowHandle(0);
-            visible = false;
-            fullscreen = false;
-            hasFocus = false;
-            parentWindowHandle = 0;
             
             // these refs shall be kept alive - resurrection via setVisible(true)
             /**
@@ -920,6 +934,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             */                        
         }
     }
+    private final DestroyAction destroyAction = new DestroyAction();
 
     public void destroy() {
         visible = false; // Immediately mark synchronized visibility flag, avoiding possible recreation 
@@ -942,19 +957,19 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         return ofs;
     }
     
-    private class ReparentActionImpl implements Runnable, ReparentAction {
+    private class ReparentAction implements Runnable {
         NativeWindow newParentWindow;
         boolean forceDestroyCreate;
-        int reparentAction;
+        ReparentOperation operation;
 
-        private ReparentActionImpl(NativeWindow newParentWindow, boolean forceDestroyCreate) {
+        private ReparentAction(NativeWindow newParentWindow, boolean forceDestroyCreate) {
             this.newParentWindow = newParentWindow;
             this.forceDestroyCreate = forceDestroyCreate | DEBUG_TEST_REPARENT_INCOMPATIBLE;
-            this.reparentAction = -1; // ensure it's set
+            this.operation = ReparentOperation.ACTION_INVALID; // ensure it's set
         }
 
-        private int getStrategy() {
-            return reparentAction;
+        private ReparentOperation getOp() {
+            return operation;
         }
 
         private void setScreen(ScreenImpl newScreen) { // never null !
@@ -975,10 +990,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         
         private void reparent() {
             // mirror pos/size so native change notification can get overwritten
-            int x = WindowImpl.this.x;
-            int y = WindowImpl.this.y;
-            int width = WindowImpl.this.width;
-            int height = WindowImpl.this.height;
+            int x = getX();
+            int y = getY();
+            int width = getWidth();
+            int height = getHeight();
             boolean wasVisible;
 
             windowLock.lock();
@@ -1029,7 +1044,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                         // It may be created properly when the parent is made visible.
                         destroy();
                         setScreen( (ScreenImpl) newParentWindowNEWT.getScreen() );
-                        reparentAction = ACTION_NATIVE_CREATION_PENDING;
+                        operation = ReparentOperation.ACTION_NATIVE_CREATION_PENDING;
                     } else if(newParentWindow != getParent()) {
                         // Case: Parent's native window realized and changed
                         if( !isNativeValid() ) {
@@ -1045,9 +1060,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                                 }
                             }
                             if( 0<width*height ) {
-                                reparentAction = ACTION_NATIVE_CREATION;
+                                operation = ReparentOperation.ACTION_NATIVE_CREATION;
                             } else {
-                                reparentAction = ACTION_NATIVE_CREATION_PENDING;
+                                operation = ReparentOperation.ACTION_NATIVE_CREATION_PENDING;
                             }
                         } else if ( forceDestroyCreate || !NewtFactory.isScreenCompatible(newParentWindow, getScreen()) ) {
                             // Destroy this window, may create a new compatible Screen/Display,
@@ -1058,14 +1073,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                             } else {
                                 setScreen( (ScreenImpl) NewtFactory.createCompatibleScreen(newParentWindow, getScreen()) );
                             }
-                            reparentAction = ACTION_NATIVE_CREATION;
+                            operation = ReparentOperation.ACTION_NATIVE_CREATION;
                         } else {
                             // Mark it for native reparenting
-                            reparentAction = ACTION_NATIVE_REPARENTING;
+                            operation = ReparentOperation.ACTION_NATIVE_REPARENTING;
                         }
                     } else {
                         // Case: Parent's native window realized and not changed
-                        reparentAction = ACTION_UNCHANGED;
+                        operation = ReparentOperation.ACTION_NOP;
                     }
                 } else {
                     if( null != parentWindow ) {
@@ -1079,27 +1094,27 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     // Case: Top Window
                     if( 0 == parentWindowHandle ) {
                         // Already Top Window
-                        reparentAction = ACTION_UNCHANGED;
+                        operation = ReparentOperation.ACTION_NOP;
                     } else if( !isNativeValid() || forceDestroyCreate ) {
                         // Destroy this window and mark it for [pending] creation.
                         destroy();
                         if( 0<width*height ) {
-                            reparentAction = ACTION_NATIVE_CREATION;
+                            operation = ReparentOperation.ACTION_NATIVE_CREATION;
                         } else {
-                            reparentAction = ACTION_NATIVE_CREATION_PENDING;
+                            operation = ReparentOperation.ACTION_NATIVE_CREATION_PENDING;
                         }
                     } else {
                         // Mark it for native reparenting
-                        reparentAction = ACTION_NATIVE_REPARENTING;
+                        operation = ReparentOperation.ACTION_NATIVE_REPARENTING;
                     }
                 }
                 parentWindowHandle = newParentWindowHandle;
 
-                if ( ACTION_UNCHANGED > reparentAction ) {
+                if ( ReparentOperation.ACTION_INVALID == operation ) {
                     throw new NativeWindowException("Internal Error: reparentAction not set");
                 }
 
-                if( ACTION_UNCHANGED == reparentAction ) {
+                if( ReparentOperation.ACTION_NOP == operation ) {
                     if(DEBUG_IMPLEMENTATION) {
                         System.err.println("Window.reparent: NO CHANGE ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+" new parentWindowHandle "+toHexString(newParentWindowHandle)+", visible "+wasVisible);
                     }
@@ -1107,7 +1122,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 }
 
                 if(DEBUG_IMPLEMENTATION) {
-                    System.err.println("Window.reparent: ACTION ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+" new parentWindowHandle "+toHexString(newParentWindowHandle)+", reparentAction "+reparentAction+", visible "+wasVisible);
+                    System.err.println("Window.reparent: ACTION ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+" new parentWindowHandle "+toHexString(newParentWindowHandle)+", reparentAction "+operation+", visible "+wasVisible);
                 }
 
                 // rearrange window tree
@@ -1119,16 +1134,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     ((Window)parentWindow).addChild(WindowImpl.this);
                 }
 
-                if( ACTION_NATIVE_CREATION_PENDING == reparentAction ) {
+                if( ReparentOperation.ACTION_NATIVE_CREATION_PENDING == operation ) {
                     // make size and position persistent for proper recreation
-                    WindowImpl.this.x = x;
-                    WindowImpl.this.y = y;
-                    WindowImpl.this.width = width;
-                    WindowImpl.this.height = height;
+                    definePosition(x, y);
+                    defineSize(width, height);
                     return;
                 }
 
-                if( ACTION_NATIVE_REPARENTING == reparentAction ) {
+                if( ReparentOperation.ACTION_NATIVE_REPARENTING == operation ) {
                     DisplayImpl display = (DisplayImpl) screen.getDisplay();
                     display.dispatchMessagesNative(); // status up2date
 
@@ -1173,7 +1186,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                                 ok = WindowImpl.this.waitForSize(width, height, false, TIMEOUT_NATIVEWINDOW);
                             }
                             if(ok) {
-                                requestFocusInt(true);
+                                requestFocusInt(false /* skipFocusAction */);
                                 display.dispatchMessagesNative(); // status up2date                                
                             }
                         }
@@ -1182,10 +1195,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     if(!ok || !wasVisible) {
                         // make size and position persistent manual, 
                         // since we don't have a WM feedback (invisible or recreation)
-                        WindowImpl.this.x = x;
-                        WindowImpl.this.y = y;
-                        WindowImpl.this.width = width;
-                        WindowImpl.this.height = height;                        
+                        definePosition(x, y);
+                        defineSize(width, height);
                     }
                     
                     if(!ok) {
@@ -1194,7 +1205,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                             System.err.println("Window.reparent: native reparenting failed ("+getThreadName()+") windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle)+" -> "+toHexString(newParentWindowHandle)+" - Trying recreation");
                         }
                         destroy();
-                        reparentAction = ACTION_NATIVE_CREATION ;
+                        operation = ReparentOperation.ACTION_NATIVE_CREATION ;
                     }
                 }
                 
@@ -1205,7 +1216,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 windowLock.unlock();
             }
             if(wasVisible) {
-                switch (reparentAction) {
+                switch (operation) {
                     case ACTION_NATIVE_REPARENTING:
                         // trigger a resize/relayout and repaint to listener
                         sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED);
@@ -1237,15 +1248,16 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             }
         }
     }
+    private final ReparentActionRecreate reparentActionRecreate = new ReparentActionRecreate();
 
-    public final int reparentWindow(NativeWindow newParent) {
+    public final ReparentOperation reparentWindow(NativeWindow newParent) {
         return reparentWindow(newParent, false);
     }
 
-    public int reparentWindow(NativeWindow newParent, boolean forceDestroyCreate) {
-        final ReparentActionImpl reparentAction = new ReparentActionImpl(newParent, forceDestroyCreate);
+    public ReparentOperation reparentWindow(NativeWindow newParent, boolean forceDestroyCreate) {
+        final ReparentAction reparentAction = new ReparentAction(newParent, forceDestroyCreate);
         runOnEDTIfAvail(true, reparentAction);
-        return reparentAction.getStrategy();
+        return reparentAction.getOp();
     }
 
     public CapabilitiesChooser setCapabilitiesChooser(CapabilitiesChooser chooser) {
@@ -1262,10 +1274,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         return capsRequested;
     }
 
-    private class DecorationActionImpl implements Runnable {
+    private class DecorationAction implements Runnable {
         boolean undecorated;
 
-        private DecorationActionImpl(boolean undecorated) {
+        private DecorationAction(boolean undecorated) {
             this.undecorated = undecorated;
         }
 
@@ -1273,28 +1285,21 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             windowLock.lock();
             try {
                 if(WindowImpl.this.undecorated != undecorated) {
-                  final boolean nativeUndecorationChange = !fullscreen && isNativeValid() && 
-                                                           isUndecorated() != undecorated ;
-                  
-                  // set current state
-                  WindowImpl.this.undecorated = undecorated;
-                  
-                  if( nativeUndecorationChange ) {
-                    // Change decoration on active window
-                      
-                    // Mirror pos/size so native change notification can get overwritten
-                    final int x = WindowImpl.this.x;
-                    final int y = WindowImpl.this.y;
-                    final int width = WindowImpl.this.width;
-                    final int height = WindowImpl.this.height;
+                    // set current state
+                    WindowImpl.this.undecorated = undecorated;
+
+                    if( isNativeValid() && !isFullscreen() ) {
+                        // Mirror pos/size so native change notification can get overwritten
+                        final int x = getX();
+                        final int y = getY();
+                        final int width = getWidth();
+                        final int height = getHeight();
 
-                    if( isNativeValid() ) {
                         DisplayImpl display = (DisplayImpl) screen.getDisplay();
                         display.dispatchMessagesNative(); // status up2date
                         reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_DECORATION, isVisible()));
                         display.dispatchMessagesNative(); // status up2date
                     }
-                  }
                 }
             } finally {
                 windowLock.unlock();
@@ -1304,46 +1309,39 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     }
 
     public void setUndecorated(boolean value) {
-        runOnEDTIfAvail(true, new DecorationActionImpl(value));
+        runOnEDTIfAvail(true, new DecorationAction(value));
     }
 
     public final boolean isUndecorated() {
         return 0 != parentWindowHandle || undecorated || fullscreen ;
     }
 
-    private class AlwaysOnTopActionImpl implements Runnable {
+    private class AlwaysOnTopAction implements Runnable {
         boolean alwaysOnTop;
 
-        private AlwaysOnTopActionImpl(boolean undecorated) {
-            this.alwaysOnTop = undecorated;
+        private AlwaysOnTopAction(boolean alwaysOnTop) {
+            this.alwaysOnTop = alwaysOnTop;
         }
 
         public final void run() {
             windowLock.lock();
             try {
                 if(WindowImpl.this.alwaysOnTop != alwaysOnTop) {
-                  final boolean nativeAlwaysOnTopChange = !fullscreen && isNativeValid() && 
-                                                           isAlwaysOnTop() != alwaysOnTop ;
-                  
-                  // set current state
-                  WindowImpl.this.alwaysOnTop = alwaysOnTop;
+                    // set current state
+                    WindowImpl.this.alwaysOnTop = alwaysOnTop;
                   
-                  if( nativeAlwaysOnTopChange ) {
-                    // Change decoration on active window
-                      
-                    // Mirror pos/size so native change notification can get overwritten
-                    final int x = WindowImpl.this.x;
-                    final int y = WindowImpl.this.y;
-                    final int width = WindowImpl.this.width;
-                    final int height = WindowImpl.this.height;
-
                     if( isNativeValid() ) {
+                        // Mirror pos/size so native change notification can get overwritten
+                        final int x = getX();
+                        final int y = getY();
+                        final int width = getWidth();
+                        final int height = getHeight();
+
                         DisplayImpl display = (DisplayImpl) screen.getDisplay();
                         display.dispatchMessagesNative(); // status up2date
                         reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_ALWAYSONTOP, isVisible()));
                         display.dispatchMessagesNative(); // status up2date
                     }
-                  }
                 }
             } finally {
                 windowLock.unlock();
@@ -1353,11 +1351,11 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     }
 
     public final void setAlwaysOnTop(boolean value) {
-        runOnEDTIfAvail(true, new AlwaysOnTopActionImpl(value));
+        runOnEDTIfAvail(true, new AlwaysOnTopAction(value));
     }
     
     public final boolean isAlwaysOnTop() {
-        return alwaysOnTop || fullscreen ;
+        return alwaysOnTop;
     }
         
     public String getTitle() {
@@ -1397,7 +1395,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             if(!setVal) {
                 if(confine) {
                     requestFocus();
-                    warpPointer(width/2, height/2);
+                    warpPointer(getWidth()/2, getHeight()/2);
                 }
                 setVal = confinePointerImpl(confine);
                 if(confine) {
@@ -1444,6 +1442,27 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         return y;
     }
 
+    protected final boolean autoPosition() { return autoPosition; }
+    
+    /** Sets the position fields {@link #x} and {@link #y} to the given values and {@link #autoPosition} to false. */ 
+    protected final void definePosition(int x, int y) {
+        if(DEBUG_IMPLEMENTATION) {
+            System.err.println("definePosition: "+this.x+"/"+this.y+" -> "+x+"/"+y);
+            // Thread.dumpStack();
+        }
+        autoPosition = false;
+        this.x = x; this.y = y;
+    }
+
+    /** Sets the size fields {@link #width} and {@link #height} to the given values. */ 
+    protected final void defineSize(int width, int height) {
+        if(DEBUG_IMPLEMENTATION) {
+            System.err.println("defineSize: "+this.width+"x"+this.height+" -> "+width+"x"+height);
+            // Thread.dumpStack();
+        }
+        this.width = width; this.height = height;
+    }
+    
     public final boolean isVisible() {
         return visible;
     }
@@ -1486,8 +1505,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     
     /**
      * If set to true, the default value, this NEWT Window implementation will
-     * handle the destruction (ie {@link #destroy()} call) within {@link #windowDestroyNotify()} implementation.<br>
-     * If set to false, it's up to the caller/owner to handle destruction within {@link #windowDestroyNotify()}.
+     * handle the destruction (ie {@link #destroy()} call) within {@link #windowDestroyNotify(boolean)} implementation.<br>
+     * If set to false, it's up to the caller/owner to handle destruction within {@link #windowDestroyNotify(boolean)}.
      */
     public void setHandleDestroyNotify(boolean b) {
         handleDestroyNotify = b;
@@ -1518,8 +1537,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     "\n, ParentWindowHandle "+toHexString(parentWindowHandle)+" ("+(0!=getParentWindowHandle())+")"+
                     "\n, WindowHandle "+toHexString(getWindowHandle())+
                     "\n, SurfaceHandle "+toHexString(getSurfaceHandle())+ " (lockedExt window "+isWindowLockedByOtherThread()+", surface "+isSurfaceLockedByOtherThread()+")"+
-                    "\n, Pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+
-                    "\n, Visible "+isVisible()+
+                    "\n, Pos "+getX()+"/"+getY()+" (auto "+autoPosition()+"), size "+getWidth()+"x"+getHeight()+
+                    "\n, Visible "+isVisible()+", focus "+hasFocus()+
                     "\n, Undecorated "+undecorated+" ("+isUndecorated()+")"+
                     "\n, AlwaysOnTop "+alwaysOnTop+", Fullscreen "+fullscreen+
                     "\n, WrappedWindow "+getWrappedWindow()+
@@ -1541,7 +1560,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         for (int i = 0; i < keyListeners.size(); i++ ) {
           sb.append(keyListeners.get(i)+", ");
         }
-        sb.append("] ]");
+        sb.append("], surfaceLock "+surfaceLock);
+        sb.append(", windowLock "+windowLock+"]");
         return sb.toString();
     }
 
@@ -1558,14 +1578,22 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         d.runOnEDTIfAvail(wait, task);
     }
 
-    private class RequestFocusAction implements Runnable {
+    private final Runnable requestFocusAction = new Runnable() {
         public final void run() {
             if(DEBUG_IMPLEMENTATION) {
-                System.err.println("Window.RequestFocusAction: ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
+                System.err.println("Window.RequestFocusAction: force 0 - ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
             }
             WindowImpl.this.requestFocusImpl(false);
         }
-    }
+    };
+    private final Runnable requestFocusActionForced = new Runnable() {
+        public final void run() {
+            if(DEBUG_IMPLEMENTATION) {
+                System.err.println("Window.RequestFocusAction: force 1 - ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
+            }
+            WindowImpl.this.requestFocusImpl(true);
+        }
+    };
 
     public final boolean hasFocus() {
         return hasFocus;
@@ -1576,15 +1604,24 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     }
 
     public void requestFocus(boolean wait) {
-        if(isNativeValid() && !focusAction()) {
-            runOnEDTIfAvail(wait, requestFocusAction);
+        requestFocus(wait /* wait */, false /* skipFocusAction */, brokenFocusChange /* force */);
+    }
+    
+    private void requestFocus(boolean wait, boolean skipFocusAction, boolean force) {
+        if( isNativeValid() &&
+            ( force || !hasFocus() ) &&
+            ( skipFocusAction || !focusAction() ) ) {
+            runOnEDTIfAvail(wait, force ? requestFocusActionForced : requestFocusAction);
         }
     }
     
-    /** Internal request focus on current thread */
-    private void requestFocusInt(boolean force) {
-        if(!focusAction()) {
-            requestFocusImpl(force);
+    /** Internally forcing request focus on current thread */
+    private void requestFocusInt(boolean skipFocusAction) {
+        if( skipFocusAction || !focusAction() ) {
+            if(DEBUG_IMPLEMENTATION) {
+                System.err.println("Window.RequestFocusInt: forcing - ("+getThreadName()+"): "+hasFocus+" -> true - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
+            }
+            requestFocusImpl(true);
         }        
     }
     
@@ -1608,32 +1645,34 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         return res;
     }
     
+    protected void setBrokenFocusChange(boolean v) {
+        brokenFocusChange = v;
+    }
+    
     public void setKeyboardFocusHandler(KeyListener l) {
         keyboardFocusHandler = l;
     }
     
-    private class SetPositionActionImpl implements Runnable {
+    private class SetPositionAction implements Runnable {
         int x, y;
 
-        private SetPositionActionImpl(int x, int y) {
+        private SetPositionAction(int x, int y) {
             this.x = x;
             this.y = y;
         }
+
         public final void run() {
             windowLock.lock();
             try {
                 if(DEBUG_IMPLEMENTATION) {
-                    System.err.println("Window setPosition: "+WindowImpl.this.x+"/"+WindowImpl.this.y+" -> "+x+"/"+y+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle));
+                    System.err.println("Window setPosition: "+getX()+"/"+getY()+" -> "+x+"/"+y+", fs "+fullscreen+", windowHandle "+toHexString(windowHandle));
                 }
-                if ( WindowImpl.this.x != x || WindowImpl.this.y != y ) {
-                    if(!fullscreen) {
-                        if(0!=windowHandle) {
-                            // this.x/this.y will be set by sizeChanged, triggered by windowing event system
-                            reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(0, isVisible()));
-                        } else {
-                            WindowImpl.this.x = x;
-                            WindowImpl.this.y = y;
-                        }
+                if ( !isFullscreen() && ( getX() != x || getY() != y ) ) {
+                    if(isNativeValid()) {
+                        // this.x/this.y will be set by sizeChanged, triggered by windowing event system
+                        reconfigureWindowImpl(x, y, getWidth(), getHeight(), getReconfigureFlags(0, isVisible()));
+                    } else {
+                        definePosition(x, y); // set pos for createNative(..)
                     }
                 }
             } finally {
@@ -1643,115 +1682,141 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     }
 
     public void setPosition(int x, int y) {
-        runOnEDTIfAvail(true, new SetPositionActionImpl(x, y));
+        autoPosition = false;
+        runOnEDTIfAvail(true, new SetPositionAction(x, y));
     }
     
     public void setTopLevelPosition(int x, int y) {
         setPosition(x + getInsets().getLeftWidth(), y + getInsets().getTopHeight());
     }
-
-    private class FullScreenActionImpl implements Runnable {
+    
+    private class FullScreenAction implements Runnable {
         boolean fullscreen;
 
-        private FullScreenActionImpl (boolean fullscreen) {
-            this.fullscreen = fullscreen;
-        }
+        private boolean init(boolean fullscreen) {            
+            if(isNativeValid()) {
+                this.fullscreen = fullscreen;
+                return isFullscreen() != fullscreen;
+            } else {
+                WindowImpl.this.fullscreen = fullscreen; // set current state for createNative(..)
+                return false;
+            }
+        }                
+        public boolean fsOn() { return fullscreen; }
 
         public final void run() {
             windowLock.lock();
             try {
-              if(WindowImpl.this.fullscreen != fullscreen) {
-                final boolean nativeFullscreenChange = isNativeValid() && 
-                                                       isFullscreen() != fullscreen ;
-                  
                 // set current state
                 WindowImpl.this.fullscreen = fullscreen;
 
-                if( nativeFullscreenChange ) {
-                    int x,y,w,h;
+                int x,y,w,h;
+                
+                if(fullscreen) {
+                    nfs_x = getX();
+                    nfs_y = getY();
+                    nfs_width = getWidth();
+                    nfs_height = getHeight();
+                    x = screen.getX(); 
+                    y = screen.getY();
+                    w = screen.getWidth();
+                    h = screen.getHeight();
+                } else {
+                    x = nfs_x;
+                    y = nfs_y;
+                    w = nfs_width;
+                    h = nfs_height;
                     
-                    if(fullscreen) {
-                        nfs_x = WindowImpl.this.x;
-                        nfs_y = WindowImpl.this.y;
-                        nfs_width = WindowImpl.this.width;
-                        nfs_height = WindowImpl.this.height;
-                        x = 0; y = 0;
-                        w = screen.getWidth();
-                        h = screen.getHeight();
-                    } else {
-                        x = nfs_x;
-                        y = nfs_y;
-                        w = nfs_width;
-                        h = nfs_height;
-                        
-                        if(null!=parentWindow) {
-                            // reset position to 0/0 within parent space
-                            x = 0;
-                            y = 0;
-        
-                            // refit if size is bigger than parent
-                            if( w > parentWindow.getWidth() ) {
-                                w = parentWindow.getWidth();
-                            }
-                            if( h > parentWindow.getHeight() ) {
-                                h = parentWindow.getHeight();
-                            }
+                    if(null!=parentWindow) {
+                        // reset position to 0/0 within parent space
+                        x = 0;
+                        y = 0;
+    
+                        // refit if size is bigger than parent
+                        if( w > parentWindow.getWidth() ) {
+                            w = parentWindow.getWidth();
+                        }
+                        if( h > parentWindow.getHeight() ) {
+                            h = parentWindow.getHeight();
                         }
                     }
-                    if(DEBUG_IMPLEMENTATION) {
-                        System.err.println("Window fs: "+fullscreen+" "+x+"/"+y+" "+w+"x"+h+", "+isUndecorated()+", "+screen);
-                    }
+                }
+                if(DEBUG_IMPLEMENTATION) {
+                    System.err.println("Window fs: "+fullscreen+" "+x+"/"+y+" "+w+"x"+h+", "+isUndecorated()+", "+screen);
+                }
 
-                    DisplayImpl display = (DisplayImpl) screen.getDisplay();
-                    display.dispatchMessagesNative(); // status up2date
-                    boolean wasVisible = isVisible();
-                    
-                    // Lock parentWindow only during reparenting (attempt)
-                    final NativeWindow parentWindowLocked;
-                    if( null != parentWindow ) {
-                        parentWindowLocked = parentWindow;
-                        if( NativeSurface.LOCK_SURFACE_NOT_READY >= parentWindowLocked.lockSurface() ) {
-                            throw new NativeWindowException("Parent surface lock: not ready: "+parentWindow);
-                        }
-                    } else {
-                        parentWindowLocked = null;
+                DisplayImpl display = (DisplayImpl) screen.getDisplay();
+                display.dispatchMessagesNative(); // status up2date
+                boolean wasVisible = isVisible();
+                
+                // Lock parentWindow only during reparenting (attempt)
+                final NativeWindow parentWindowLocked;
+                if( null != parentWindow ) {
+                    parentWindowLocked = parentWindow;
+                    if( NativeSurface.LOCK_SURFACE_NOT_READY >= parentWindowLocked.lockSurface() ) {
+                        throw new NativeWindowException("Parent surface lock: not ready: "+parentWindow);
                     }
-                    try {
-                        reconfigureWindowImpl(x, y, w, h, 
-                                              getReconfigureFlags( ( ( null != parentWindowLocked ) ? FLAG_CHANGE_PARENTING : 0 ) | 
-                                                                   FLAG_CHANGE_FULLSCREEN | FLAG_CHANGE_DECORATION, wasVisible) ); 
-                    } finally {
-                        if(null!=parentWindowLocked) {
-                            parentWindowLocked.unlockSurface();
-                        }
+                } else {
+                    parentWindowLocked = null;
+                }
+                try {
+                    reconfigureWindowImpl(x, y, w, h, 
+                                          getReconfigureFlags( ( ( null != parentWindowLocked ) ? FLAG_CHANGE_PARENTING : 0 ) | 
+                                                               FLAG_CHANGE_FULLSCREEN | FLAG_CHANGE_DECORATION, wasVisible) ); 
+                } finally {
+                    if(null!=parentWindowLocked) {
+                        parentWindowLocked.unlockSurface();
                     }
-                    display.dispatchMessagesNative(); // status up2date
+                }
+                display.dispatchMessagesNative(); // status up2date
+                
+                if(wasVisible) {
+                    setVisibleImpl(true, x, y, w, h);
+                    WindowImpl.this.waitForVisible(true, false);
+                    display.dispatchMessagesNative(); // status up2date                                                        
+                    WindowImpl.this.waitForSize(w, h, false, TIMEOUT_NATIVEWINDOW);
+                    display.dispatchMessagesNative(); // status up2date                                                        
                     
-                    if(wasVisible) {
-                        setVisibleImpl(true, x, y, w, h);
-                        WindowImpl.this.waitForVisible(true, false);
-                        display.dispatchMessagesNative(); // status up2date                                                        
-                        WindowImpl.this.waitForSize(w, h, false, TIMEOUT_NATIVEWINDOW);
-                        display.dispatchMessagesNative(); // status up2date                                                        
-                        requestFocusInt(true);
-                        display.dispatchMessagesNative(); // status up2date
-                        
-                        if(DEBUG_IMPLEMENTATION) {
-                            System.err.println("Window fs done: " + WindowImpl.this);
-                        }
+                    if(DEBUG_IMPLEMENTATION) {
+                        System.err.println("Window fs done: " + WindowImpl.this);
                     }
                 }
-              }    
             } finally {
                 windowLock.unlock();
             }
             sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout and repaint to listener
         }
     }
+    private final FullScreenAction fullScreenAction = new FullScreenAction();
 
     public boolean setFullscreen(boolean fullscreen) {
-        runOnEDTIfAvail(true, new FullScreenActionImpl(fullscreen));
-        return this.fullscreen;
+        synchronized(fullScreenAction) {
+            if( fullScreenAction.init(fullscreen) ) {               
+                if(fullScreenAction.fsOn() && 
+                   isOffscreenInstance(WindowImpl.this, parentWindow)) { 
+                    // enable fullscreen on offscreen instance
+                    if(null != parentWindow) {
+                        nfs_parent = parentWindow;
+                        reparentWindow(null, true);
+                    } else {
+                        throw new InternalError("Offscreen instance w/o parent unhandled");
+                    }
+                }
+                
+                runOnEDTIfAvail(true, fullScreenAction);
+                
+                if(!fullScreenAction.fsOn() && null != nfs_parent) {
+                    // disable fullscreen on offscreen instance
+                    reparentWindow(nfs_parent, true);
+                    nfs_parent = null;
+                }
+                
+                if(isVisible()) {         
+                    requestFocus(true /* wait */, this.fullscreen /* skipFocusAction */, true /* force */);
+                }
+            }
+            return this.fullscreen;                
+        }
     }
 
     private class ScreenModeListenerImpl implements ScreenModeListener {
@@ -1773,6 +1838,10 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             }
 
             if(success) {
+                if(!animatorPaused && null!=lifecycleHook) {
+                    // Didn't pass above notify method. probably detected screen change after it happened.
+                    animatorPaused = lifecycleHook.pauseRenderingAction();
+                }
                 DimensionImmutable screenSize = sm.getMonitorMode().getSurfaceSize().getResolution();
                 if ( getHeight() > screenSize.getHeight()  ||
                      getWidth() > screenSize.getWidth() ) {
@@ -1786,6 +1855,9 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED); // trigger a resize/relayout and repaint to listener
         }
     }
+    private final ScreenModeListenerImpl screenModeListenerImpl = new ScreenModeListenerImpl();
+
+
 
     //----------------------------------------------------------------------
     // Child Window Management
@@ -1837,11 +1909,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                     // make sure only one repaint event is queued
                     if(!repaintQueued) {
                         repaintQueued=true;
+                        final boolean discardTO = QUEUED_EVENT_TO <= System.currentTimeMillis()-e.getWhen();
                         if(DEBUG_IMPLEMENTATION) {
-                            System.err.println("Window.consumeEvent: queued "+e);
+                            System.err.println("Window.consumeEvent: "+Thread.currentThread().getName()+" - queued "+e+", discard-to "+discardTO);
                             // Thread.dumpStack();
-                        }
-                        return false;
+                        }                                                
+                        return discardTO; // discardTO:=true -> consumed
                     }
                     return true;
                 }
@@ -1852,11 +1925,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             case WindowEvent.EVENT_WINDOW_RESIZED:
                 // queue event in case window is locked, ie in operation
                 if( isWindowLocked() ) {
+                    final boolean discardTO = QUEUED_EVENT_TO <= System.currentTimeMillis()-e.getWhen();
                     if(DEBUG_IMPLEMENTATION) {
-                        System.err.println("Window.consumeEvent: queued "+e);
+                        System.err.println("Window.consumeEvent: "+Thread.currentThread().getName()+" - queued "+e+", discard-to "+discardTO);
                         // Thread.dumpStack();
                     }
-                    return false;
+                    return discardTO; // discardTO:=true -> consumed
                 }
                 break;
             default:
@@ -1914,11 +1988,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 y = lastMousePosition.getY();
             }
             // clip coordinates to window dimension
-            x = Math.min(Math.max(x,  0), width-1);
-            y = Math.min(Math.max(y,  0), height-1);
+            x = Math.min(Math.max(x,  0), getWidth()-1);
+            y = Math.min(Math.max(y,  0), getHeight()-1);
             mouseInWindow = eventType == MouseEvent.EVENT_MOUSE_ENTERED;
+            lastMousePressed=0;   // clear state
+            mouseButtonPressed=0; // clear state
         }
-        if(x<0||y<0||x>=width||y>=height) {
+        if(x<0||y<0||x>=getWidth()||y>=getHeight()) {
             return; // .. invalid ..
         }
         if(DEBUG_MOUSE_EVENT) {
@@ -1926,15 +2002,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                                ", mod "+modifiers+", pos "+x+"/"+y+", button "+button+", lastMousePosition: "+lastMousePosition);
         }
         long when = System.currentTimeMillis();
+        MouseEvent eEntered = null;
         if(eventType == MouseEvent.EVENT_MOUSE_MOVED) {
             if(!mouseInWindow) {
                 mouseInWindow = true;
-                MouseEvent e = new MouseEvent(MouseEvent.EVENT_MOUSE_ENTERED, this, when,
-                                              modifiers, x, y, lastMouseClickCount, button, 0);
-                if(DEBUG_MOUSE_EVENT) {
-                    System.err.println("doMouseEvent: synthesized MOUSE_ENTERED event: "+e);
-                }
-                doEvent(enqueue, wait, e);
+                eEntered = new MouseEvent(MouseEvent.EVENT_MOUSE_ENTERED, this, when,
+                                          modifiers, x, y, lastMouseClickCount, button, 0);
+                lastMousePressed=0;   // clear state
+                mouseButtonPressed=0; // clear state
             } else if(lastMousePosition.getX() == x && lastMousePosition.getY()==y) { 
                 if(DEBUG_MOUSE_EVENT) {
                     System.err.println("doMouseEvent: skip EVENT_MOUSE_MOVED w/ same position: "+lastMousePosition);
@@ -1944,9 +2019,12 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
             lastMousePosition.setX(x);
             lastMousePosition.setY(y);
         }
-        if(button<0||button>MouseEvent.BUTTON_NUMBER) {
+        if( 0 > button || button > MouseEvent.BUTTON_NUMBER ) {
             throw new NativeWindowException("Invalid mouse button number" + button);
         }
+        // Fixes Bug 571: X11 behavior, where the PRESSED button is not included in the native mask.
+        modifiers |= InputEvent.getButtonMask(button);
+
         MouseEvent eClicked = null;
         MouseEvent e = null;
 
@@ -1991,7 +2069,13 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         } else {
             e = new MouseEvent(eventType, this, when, modifiers, x, y, 0, button, 0);
         }
-        doEvent(enqueue, wait, e);
+        if(null!=eEntered) {
+            if(DEBUG_MOUSE_EVENT) {
+                System.err.println("doMouseEvent: synthesized MOUSE_ENTERED event: "+eEntered);
+            }
+            doEvent(enqueue, wait, eEntered);
+        }
+        doEvent(enqueue, wait, e); // actual mouse event
         if(null!=eClicked) {
             if(DEBUG_MOUSE_EVENT) {
                 System.err.println("doMouseEvent: synthesized MOUSE_CLICKED event: "+eClicked);
@@ -2257,7 +2341,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
 
     /** Triggered by implementation's WM events to update the focus state. */
     protected void focusChanged(boolean defer, boolean focusGained) {
-        if(hasFocus != focusGained) {
+        if(brokenFocusChange || hasFocus != focusGained) {
             if(DEBUG_IMPLEMENTATION) {
                 System.err.println("Window.focusChanged: ("+getThreadName()+"): (defer: "+defer+") "+this.hasFocus+" -> "+focusGained+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
             }
@@ -2269,7 +2353,7 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
                 enqueueWindowEvent(false, evt);
             }
         }
-    }
+    }    
 
     /** Triggered by implementation's WM events to update the visibility state. */
     protected void visibleChanged(boolean defer, boolean visible) {
@@ -2304,15 +2388,14 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
 
     /** Triggered by implementation's WM events to update the client-area size w/o insets/decorations. */ 
     protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) {
-        if(force || width != newWidth || height != newHeight) {
+        if(force || getWidth() != newWidth || getHeight() != newHeight) {
             if(DEBUG_IMPLEMENTATION) {
-                System.err.println("Window.sizeChanged: ("+getThreadName()+"): (defer: "+defer+") force "+force+", "+width+"x"+height+" -> "+newWidth+"x"+newHeight+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
+                System.err.println("Window.sizeChanged: ("+getThreadName()+"): (defer: "+defer+") force "+force+", "+getWidth()+"x"+getHeight()+" -> "+newWidth+"x"+newHeight+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
             }
             if(0>newWidth || 0>newHeight) {
                 throw new NativeWindowException("Illegal width or height "+newWidth+"x"+newHeight+" (must be >= 0)");
             }
-            width = newWidth;
-            height = newHeight;
+            defineSize(newWidth, newHeight);
             if(isNativeValid()) {
                 if(!defer) {
                     sendWindowEvent(WindowEvent.EVENT_WINDOW_RESIZED);
@@ -2349,17 +2432,18 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
     
     /** Triggered by implementation's WM events to update the position. */ 
     protected void positionChanged(boolean defer, int newX, int newY) {
-        if ( x != newX || y != newY ) {
+        if ( getX() != newX || getY() != newY ) {
             if(DEBUG_IMPLEMENTATION) {
-                System.err.println("Window.positionChanged: ("+getThreadName()+"): (defer: "+defer+") "+x+"/"+y+" -> "+newX+"/"+newY+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
+                System.err.println("Window.positionChanged: ("+getThreadName()+"): (defer: "+defer+") "+getX()+"/"+getY()+" -> "+newX+"/"+newY+" - windowHandle "+toHexString(windowHandle)+" parentWindowHandle "+toHexString(parentWindowHandle));
             }
-            x = newX;
-            y = newY;
+            definePosition(newX, newY);
             if(!defer) {
                 sendWindowEvent(WindowEvent.EVENT_WINDOW_MOVED);
             } else {
                 enqueueWindowEvent(false, WindowEvent.EVENT_WINDOW_MOVED);
             }
+        } else {
+            autoPosition = false; // ensure it's off even w/ same position            
         }
     }
 
@@ -2389,21 +2473,34 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
         }
     }
     
-    protected void windowDestroyNotify() {
+    /**
+     * Triggered by implementation's WM events or programmatically
+     * 
+     * @param force if true, overrides {@link #setDefaultCloseOperation(WindowClosingMode)} with {@link WindowClosingProtocol#DISPOSE_ON_CLOSE}
+     *              and hence force destruction. Otherwise is follows the user settings.
+     * @return true if this window is no more valid and hence has been destroyed, otherwise false.
+     */
+    protected boolean windowDestroyNotify(boolean force) {
         if(DEBUG_IMPLEMENTATION) {
-            System.err.println("Window.windowDestroyNotify START "+getThreadName());
+            System.err.println("Window.windowDestroyNotify(force: "+force+") START "+getThreadName()+": "+this);
+        }
+        if(force) {
+            setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE);
         }
 
         // send synced destroy notifications
         enqueueWindowEvent(true, WindowEvent.EVENT_WINDOW_DESTROY_NOTIFY);
 
-        if(handleDestroyNotify && DISPOSE_ON_CLOSE == defaultCloseOperation) {
+        if(handleDestroyNotify && WindowClosingMode.DISPOSE_ON_CLOSE == getDefaultCloseOperation()) {
             destroy();
         }
+        
+        final boolean destroyed = !isNativeValid();
 
         if(DEBUG_IMPLEMENTATION) {
-            System.err.println("Window.windowDestroyeNotify END "+getThreadName());
+            System.err.println("Window.windowDestroyNotify(force: "+force+") END "+getThreadName()+": destroyed "+destroyed+", "+this);
         }
+        return destroyed;
     }
 
     public void windowRepaint(int x, int y, int width, int height) {
@@ -2414,10 +2511,8 @@ public abstract class WindowImpl implements Window, NEWTEventConsumer
      * Triggered by implementation's WM events to update the content
      */ 
     protected void windowRepaint(boolean defer, int x, int y, int width, int height) {
-        x = ( 0 > x ) ? this.x : x;
-        y = ( 0 > y ) ? this.y : y;
-        width = ( 0 >= width ) ? this.width : width;
-        height = ( 0 >= height ) ? this.height : height;
+        width = ( 0 >= width ) ? getWidth() : width;
+        height = ( 0 >= height ) ? getHeight() : height;
         if(DEBUG_IMPLEMENTATION) {
             System.err.println("Window.windowRepaint "+getThreadName()+" (defer: "+defer+") "+x+"/"+y+" "+width+"x"+height);
         }
diff --git a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java
index 2ca3d2c..861a6d6 100644
--- a/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java
+++ b/src/newt/classes/jogamp/newt/awt/NewtFactoryAWT.java
@@ -33,11 +33,11 @@ import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.NativeWindow;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.NativeWindowFactory;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
 
-import jogamp.nativewindow.jawt.JAWTWindow;
 import jogamp.newt.Debug;
 
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.JAWTWindow;
 import com.jogamp.newt.NewtFactory;
 
 public class NewtFactoryAWT extends NewtFactory {
@@ -47,7 +47,7 @@ public class NewtFactoryAWT extends NewtFactory {
    * Wraps an AWT component into a {@link javax.media.nativewindow.NativeWindow} utilizing the {@link javax.media.nativewindow.NativeWindowFactory},<br>
    * using a configuration agnostic dummy {@link javax.media.nativewindow.DefaultGraphicsConfiguration}.<br>
    * <p>
-   * The actual wrapping implementation is {@link jogamp.nativewindow.jawt.JAWTWindow}.<br></p>
+   * The actual wrapping implementation is {@link com.jogamp.nativewindow.awt.JAWTWindow}.<br></p>
    * <p>
    * Purpose of this wrapping is to access the AWT window handle,<br>
    * not to actually render into it.<br>
diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java
index d64cc93..cb70da1 100644
--- a/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java
+++ b/src/newt/classes/jogamp/newt/awt/event/AWTNewtEventFactory.java
@@ -120,7 +120,8 @@ public class AWTNewtEventFactory {
         if(0xFFFFFFFF != type) {
             int rotation = 0;
             if (event instanceof java.awt.event.MouseWheelEvent) {
-                rotation = ((java.awt.event.MouseWheelEvent)event).getWheelRotation();
+                // AWT/NEWT rotation is reversed - AWT +1 is down, NEWT +1 is up.
+                rotation = -1 * ((java.awt.event.MouseWheelEvent)event).getWheelRotation();
             }
 
             int mods = awtModifiers2Newt(event.getModifiers(), true);
diff --git a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java
index 8e9c028..ce8ed7c 100644
--- a/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java
+++ b/src/newt/classes/jogamp/newt/awt/event/AWTParentWindowAdapter.java
@@ -30,6 +30,8 @@ package jogamp.newt.awt.event;
 
 import java.awt.KeyboardFocusManager;
 
+import javax.media.nativewindow.NativeWindow;
+
 import jogamp.newt.driver.DriverUpdatePosition;
 
 import com.jogamp.newt.event.awt.AWTAdapter;
@@ -43,8 +45,11 @@ public class AWTParentWindowAdapter
     extends AWTWindowAdapter 
     implements java.awt.event.HierarchyListener
 {
-    public AWTParentWindowAdapter(com.jogamp.newt.Window downstream) {
+    NativeWindow downstreamParent;
+    
+    public AWTParentWindowAdapter(NativeWindow downstreamParent, com.jogamp.newt.Window downstream) {
         super(downstream);
+        this.downstreamParent = downstreamParent;
     }
 
     public AWTAdapter addTo(java.awt.Component awtComponent) {
@@ -61,13 +66,17 @@ public class AWTParentWindowAdapter
         // forward focus to NEWT child
         final com.jogamp.newt.Window newtChild = getNewtWindow();
         final boolean isOnscreen = newtChild.isNativeValid() && newtChild.getGraphicsConfiguration().getChosenCapabilities().isOnscreen();
+        final boolean isParent = downstreamParent == newtChild.getParent();
+        final boolean isFullscreen = newtChild.isFullscreen();
         if(DEBUG_IMPLEMENTATION) {
-            System.err.println("AWT: focusGained: onscreen "+ isOnscreen+", "+e);
+            System.err.println("AWT: focusGained: onscreen "+ isOnscreen+", "+e+", isParent: "+isParent+", isFS "+isFullscreen);
         }
-        if(isOnscreen) {
-            KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
+        if(isParent) {
+            if(isOnscreen && !isFullscreen) {
+                KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
+            }
+            newtChild.requestFocus(false);
         }
-        newtChild.requestFocus(false);
     }
 
     public void focusLost(java.awt.event.FocusEvent e) {
diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java b/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java
index 72c0bce..3f360f2 100644
--- a/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java
+++ b/src/newt/classes/jogamp/newt/driver/android/AndroidDisplay.java
@@ -32,9 +32,10 @@ import jogamp.newt.*;
 import jogamp.opengl.egl.*;
 
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.egl.*;
 import javax.media.opengl.GLException;
 
+import com.jogamp.nativewindow.egl.*;
+
 public class AndroidDisplay extends jogamp.newt.DisplayImpl {
     static {
         NEWTJNILibLoader.loadNEWT();
@@ -54,13 +55,11 @@ public class AndroidDisplay extends jogamp.newt.DisplayImpl {
 
     protected void createNativeImpl() {
         // EGL Device
-        final long eglDisplay = EGL.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
+        final long eglDisplay = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
         if (eglDisplay == EGL.EGL_NO_DISPLAY) {
             throw new GLException("Failed to created EGL default display: error 0x"+Integer.toHexString(EGL.eglGetError()));
-        } else if(DEBUG) {
-            System.err.println("Android Display.createNativeImpl: eglDisplay(EGL_DEFAULT_DISPLAY): 0x"+Long.toHexString(eglDisplay));
         }
-        if (!EGL.eglInitialize(eglDisplay, null, null)) {
+        if (!EGLDisplayUtil.eglInitialize(eglDisplay, null, null)) {
             throw new GLException("eglInitialize failed eglDisplay 0x"+Long.toHexString(eglDisplay)+", error 0x"+Integer.toHexString(EGL.eglGetError()));
         }
         aDevice = new EGLGraphicsDevice(eglDisplay, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT);        
@@ -68,7 +67,7 @@ public class AndroidDisplay extends jogamp.newt.DisplayImpl {
 
     protected void closeNativeImpl() {
         if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) {
-            EGL.eglTerminate(aDevice.getHandle());
+            EGLDisplayUtil.eglTerminate(aDevice.getHandle());
         }
     }
 
diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java b/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java
index ce6a9c5..e108ed0 100644
--- a/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java
+++ b/src/newt/classes/jogamp/newt/driver/android/AndroidScreen.java
@@ -29,6 +29,8 @@
 package jogamp.newt.driver.android;
 
 import javax.media.nativewindow.*;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
 
 import com.jogamp.newt.ScreenMode;
 import com.jogamp.newt.util.ScreenModeUtil;
@@ -74,6 +76,18 @@ public class AndroidScreen extends jogamp.newt.ScreenImpl {
         return ScreenModeUtil.streamIn(props, 0);
     }
     
+    protected int validateScreenIndex(int idx) {
+        return 0; // FIXME: only one screen available ? 
+    }
+    
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(0);
+        virtualOrigin.setY(0);
+        final ScreenMode sm = getCurrentScreenMode();
+        virtualSize.setWidth(sm.getRotatedWidth());
+        virtualSize.setHeight(sm.getRotatedHeight());
+    }
+    
     //----------------------------------------------------------------------
     // Internals only
     //
@@ -91,7 +105,7 @@ public class AndroidScreen extends jogamp.newt.ScreenImpl {
         if (ScreenMode.ROTATE_90 == nrot || ScreenMode.ROTATE_270 == nrot) {
             props[offset++] = outMetrics.heightPixels;
             props[offset++] = outMetrics.widthPixels;
-        } else {        
+        } else {
             props[offset++] = outMetrics.widthPixels;
             props[offset++] = outMetrics.heightPixels;
         }
diff --git a/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java b/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java
index 32879b0..63d5f70 100644
--- a/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/android/AndroidWindow.java
@@ -28,21 +28,19 @@
 
 package jogamp.newt.driver.android;
 
-import java.nio.IntBuffer;
-
+import jogamp.common.os.android.StaticContext;
 import jogamp.newt.driver.android.event.AndroidNewtEventFactory;
 
 import javax.media.nativewindow.Capabilities;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.NativeWindowException;
-import javax.media.nativewindow.egl.EGLGraphicsDevice;
+import javax.media.nativewindow.VisualIDHolder;
 import javax.media.nativewindow.util.Insets;
 import javax.media.nativewindow.util.Point;
 import javax.media.opengl.GLCapabilitiesChooser;
 import javax.media.opengl.GLCapabilitiesImmutable;
 
-import com.jogamp.common.nio.Buffers;
-import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.nativewindow.egl.EGLGraphicsDevice;
 
 import jogamp.opengl.egl.EGL;
 import jogamp.opengl.egl.EGLGraphicsConfiguration;
@@ -51,30 +49,18 @@ import jogamp.opengl.egl.EGLGraphicsConfigurationFactory;
 import android.content.Context;
 import android.graphics.PixelFormat;
 import android.util.Log;
-import android.view.MotionEvent;
 import android.view.Surface;
 import android.view.SurfaceHolder;
 import android.view.SurfaceHolder.Callback2;
 import android.view.SurfaceView;
 import android.view.View;
-import android.view.Window;
-import android.view.WindowManager;
 
-public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
+public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {    
     static {
         AndroidDisplay.initSingleton();
     }
 
-    public static CapabilitiesImmutable fixCapsAlpha(CapabilitiesImmutable rCaps) {
-        if(rCaps.getAlphaBits()==0) {
-            Capabilities nCaps = (Capabilities) rCaps.cloneMutable();
-            nCaps.setAlphaBits(1);
-            return nCaps;
-        }
-        return rCaps;
-    }
-    
-    public static CapabilitiesImmutable fixCaps(int format, CapabilitiesImmutable rCaps) {
+    public static CapabilitiesImmutable fixCaps(boolean matchFormatPrecise, int format, CapabilitiesImmutable rCaps) {
         PixelFormat pf = new PixelFormat(); 
         PixelFormat.getPixelFormatInfo(format, pf);
         final CapabilitiesImmutable res;        
@@ -90,18 +76,19 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
             case PixelFormat.RGB_332:   r=3; g=3; b=2; a=0; break;
             default: throw new InternalError("Unhandled pixelformat: "+format);
         }
-        final boolean fits = rCaps.getRedBits()   <= r &&
-                             rCaps.getGreenBits() <= g &&
-                             rCaps.getBlueBits()  <= b &&
-                             rCaps.getAlphaBits() <= a ;
+        final boolean change = matchFormatPrecise ||
+                               rCaps.getRedBits()   > r &&
+                               rCaps.getGreenBits() > g &&
+                               rCaps.getBlueBits()  > b &&
+                               rCaps.getAlphaBits() > a ;
         
-        if(!fits) {
+        if(change) {
             Capabilities nCaps = (Capabilities) rCaps.cloneMutable();
             nCaps.setRedBits(r);
             nCaps.setGreenBits(g);
             nCaps.setBlueBits(b);
             nCaps.setAlphaBits(a);
-            res = nCaps;            
+            res = nCaps;        
         } else {
             res = rCaps;
         }
@@ -138,63 +125,98 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         return fmt;
     }
     
-    class AndroidEvents implements /* View.OnKeyListener, */ View.OnTouchListener {
+    public static boolean isAndroidFormatTransparent(int aFormat) {
+        switch (aFormat) {
+            case PixelFormat.TRANSLUCENT:
+            case PixelFormat.TRANSPARENT:
+                return true;
+        }
+        return false;
+    }
+    
+    class AndroidEvents implements View.OnKeyListener, View.OnTouchListener, View.OnFocusChangeListener {
 
-        public boolean onTouch(View v, MotionEvent event) {
-            MouseEvent[] newtEvents = AndroidNewtEventFactory.createMouseEvents(AndroidWindow.this, event);
+        @Override
+        public boolean onTouch(View v, android.view.MotionEvent event) {
+            final com.jogamp.newt.event.MouseEvent[] newtEvents = AndroidNewtEventFactory.createMouseEvents(event, AndroidWindow.this);
             if(null != newtEvents) {
+                focusChanged(false, true);
                 for(int i=0; i<newtEvents.length; i++) {
                     AndroidWindow.this.enqueueEvent(false, newtEvents[i]);
                 }
+                try { Thread.sleep((long) (1000.0F/30.0F)); }
+                catch(InterruptedException e) { }
+                return true; // consumed/handled, further interest in events
             }
-            return true;
+            return false; // no mapping, no further interest in the event!
         }
 
-        /** TODO
-        public boolean onKey(View v, int keyCode, KeyEvent event) {
+        @Override
+        public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
+            final com.jogamp.newt.event.KeyEvent[] newtEvents = AndroidNewtEventFactory.createKeyEvents(keyCode, event, AndroidWindow.this);
+            if(null != newtEvents) {
+                for(int i=0; i<newtEvents.length; i++) {
+                    AndroidWindow.this.enqueueEvent(false, newtEvents[i]);
+                }
+                return true;
+            }
             return false;
-        } */
+        }
+        
+        @Override
+        public void onFocusChange(View v, boolean hasFocus) {
+            AndroidWindow.this.focusChanged(false, hasFocus);
+        }
+        
+    }
+
+    public static Class<?>[] getCustomConstructorArgumentTypes() {
+        return new Class<?>[] { Context.class } ;
+    }
+    
+    public AndroidWindow() {
+        reset();
     }
 
+    private void reset() {
+        ownAndroidWindow = false;
+        androidView = null;
+        nativeFormat = VisualIDHolder.VID_UNDEFINED;
+        androidFormat = VisualIDHolder.VID_UNDEFINED;
+        capsByFormat = null;
+        surface = null;
+        surfaceHandle = 0;
+        eglSurface = 0;
+        definePosition(0, 0); // default to 0/0
+        setBrokenFocusChange(true);
+    }
+    
     @Override
     protected void instantiationFinished() {
-        androidView = new MSurfaceView(jogamp.common.os.android.StaticContext.getContext());
-        AndroidEvents ae = new AndroidEvents();
+        final Context ctx = StaticContext.getContext();        
+        if(null == ctx) {
+            throw new NativeWindowException("No static [Application] Context has been set. Call StaticContext.setContext(Context) first.");
+        }
+        androidView = new MSurfaceView(ctx);
+        
+        final AndroidEvents ae = new AndroidEvents();
         androidView.setOnTouchListener(ae);
         androidView.setClickable(false);
-        // nsv.setOnKeyListener(ae);
-        SurfaceHolder sh = androidView.getHolder();
-        sh.addCallback(this); 
-        // setFormat is done by SurfaceView in SDK 2.3 and newer. Uncomment
-        // this statement if back-porting to 2.2 or older:
-        // sh.setFormat(PixelFormat.RGB_565);
-        // sh.setFormat(PixelFormat.RGBA_5551);
-        // sh.setFormat(PixelFormat.RGBA_8888);
+        androidView.setOnKeyListener(ae);
+        androidView.setOnFocusChangeListener(ae);
+        androidView.setFocusable(true);
+        androidView.setFocusableInTouchMode(true);
+        
+        final SurfaceHolder sh = androidView.getHolder();
+        sh.addCallback(AndroidWindow.this); 
         sh.setFormat(getFormat(getRequestedCapabilities()));
-        // setType is not needed for SDK 2.0 or newer. Uncomment this
-        // statement if back-porting this code to older SDKs.
-        // sh.setType(SurfaceHolder.SURFACE_TYPE_GPU);
-        // sh.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
         
         // default size -> TBD ! 
-        this.width = 0;
-        this.height = 0;
+        defineSize(0, 0);
     }
     
     public SurfaceView getAndroidView() { return androidView; }
     
-    public void setAndroidWindow(android.view.Window window) { 
-        System.err.println("setandroidWindow: "+window+", "+width+"x"+height);
-        androidWindow = window;
-        androidWindowConfigurationPreCreate();
-        if(width>0 && height>0 && !isFullscreen()) {
-            if(null != androidWindow) {
-                androidWindow.setLayout(width, height);
-            }
-        }
-    }
-    public android.view.Window getAndroidWindow() { return androidWindow; }
-    
     @Override
     protected boolean canCreateNativeImpl() {
         final boolean b = 0 != surfaceHandle;
@@ -205,8 +227,8 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
     @Override
     protected void createNativeImpl() {
         Log.d(MD.TAG, "createNativeImpl 0 - surfaceHandle 0x"+Long.toHexString(surfaceHandle)+
-                    ", format "+format+", "+x+"/"+y+" "+width+"x"+height+" - "+Thread.currentThread().getName());
-        Thread.dumpStack();
+                    ", format [a "+androidFormat+", n "+nativeFormat+"], "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight()+" - "+Thread.currentThread().getName());
+
         if(0!=getParentWindowHandle()) {
             throw new NativeWindowException("Window parenting not supported (yet)");
         }
@@ -217,20 +239,15 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         final EGLGraphicsDevice eglDevice = (EGLGraphicsDevice) getScreen().getDisplay().getGraphicsDevice();
         final EGLGraphicsConfiguration eglConfig = EGLGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(
                 capsByFormat, (GLCapabilitiesImmutable) getRequestedCapabilities(), 
-                (GLCapabilitiesChooser)capabilitiesChooser, getScreen().getGraphicsScreen(), format);
+                (GLCapabilitiesChooser)capabilitiesChooser, getScreen().getGraphicsScreen(), nativeFormat, 
+                isAndroidFormatTransparent(androidFormat));
         if (eglConfig == null) {
             throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this);
         }
-        // query native VisualID and pass it to Surface
-        final long eglConfigHandle = eglConfig.getNativeConfig();
-        final IntBuffer nativeVisualID = Buffers.newDirectIntBuffer(1);
-        if(!EGL.eglGetConfigAttrib(eglDevice.getHandle(), eglConfigHandle, EGL.EGL_NATIVE_VISUAL_ID, nativeVisualID)) {
-            throw new NativeWindowException("eglgetConfigAttrib EGL_NATIVE_VISUAL_ID failed eglDisplay 0x"+Long.toHexString(eglDevice.getHandle())+ 
-                                  ", error 0x"+Integer.toHexString(EGL.eglGetError()));
-        }        
-        Log.d(MD.TAG, "nativeVisualID 0x"+Integer.toHexString(nativeVisualID.get(0)));
-        if(nativeVisualID.get(0)>0) {
-            setSurfaceVisualID0(surfaceHandle, nativeVisualID.get(0));
+        final int nativeVisualID = eglConfig.getVisualID(VisualIDHolder.VIDType.NATIVE);
+        Log.d(MD.TAG, "nativeVisualID 0x"+Integer.toHexString(nativeVisualID));
+        if(VisualIDHolder.VID_UNDEFINED != nativeVisualID) {
+            setSurfaceVisualID0(surfaceHandle, nativeVisualID);
         }
         
         eglSurface = EGL.eglCreateWindowSurface(eglDevice.getHandle(), eglConfig.getNativeConfig(), surfaceHandle, null);
@@ -241,6 +258,7 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         // propagate data ..
         setGraphicsConfiguration(eglConfig);
         setWindowHandle(surfaceHandle);
+        focusChanged(false, true);
         Log.d(MD.TAG, "createNativeImpl X");
     }
 
@@ -257,33 +275,31 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         return eglSurface;
     }
     
-    protected void requestFocusImpl(boolean reparented) { }
-
-    protected void androidWindowConfigurationPreCreate() {
-        if( null != androidWindow) {
-            if( isFullscreen() || isUndecorated() ) {
-                androidWindow.requestFeature(Window.FEATURE_NO_TITLE);
-            }
-            if( isFullscreen() ) {
-                androidWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
-                                       WindowManager.LayoutParams.FLAG_FULLSCREEN);
-            }
+    protected void requestFocusImpl(boolean reparented) { 
+        if(null != androidView) {
+            Log.d(MD.TAG, "requestFocusImpl: reparented "+reparented);
+            androidView.post(new Runnable() {
+                public void run() {
+                    androidView.requestFocus();
+                    androidView.bringToFront();
+                }
+            });
         }
     }
-    
+
     protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) {
         if( 0 != ( FLAG_CHANGE_FULLSCREEN & flags) ) {
-            System.err.println("reconfigureWindowImpl.setFullscreen post creation (setContentView()) n/a");
+            Log.d(MD.TAG, "reconfigureWindowImpl.setFullscreen post creation (setContentView()) n/a");
             return false;
         }
         if(width>0 || height>0) {
             if(0!=getWindowHandle()) {
-                System.err.println("reconfigureWindowImpl.setSize n/a");
+                Log.d(MD.TAG, "reconfigureWindowImpl.setSize n/a");
                 return false;
             }
         }
         if(x>=0 || y>=0) {
-            System.err.println("reconfigureWindowImpl.setPos n/a");
+            Log.d(MD.TAG, "reconfigureWindowImpl.setPos n/a");
             return false;
         }
         if( 0 != ( FLAG_CHANGE_VISIBILITY & flags) ) {
@@ -292,29 +308,6 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         return true;
     }
 
-    /**
-    Canvas cLock = null;
-    
-    @Override
-    protected int lockSurfaceImpl() {
-        if (null != cLock) {
-            throw new InternalError("surface already locked");
-        }        
-        if (0 != surfaceHandle) {
-            cLock = nsv.getHolder().lockCanvas();
-        }
-        return ( null != cLock ) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY;
-    }
-
-    @Override
-    protected void unlockSurfaceImpl() {
-        if (null == cLock) {
-            throw new InternalError("surface not locked");
-        }
-        nsv.getHolder().unlockCanvasAndPost(cLock);
-        cLock=null;
-    } */
-    
     protected Point getLocationOnScreenImpl(int x, int y) {
         return new Point(x,y);
     }
@@ -328,56 +321,56 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
     //
     
     public void surfaceCreated(SurfaceHolder holder) {    
-        Log.d(MD.TAG, "surfaceCreated: "+x+"/"+y+" "+width+"x"+height);
+        Log.d(MD.TAG, "surfaceCreated: "+getX()+"/"+getY()+" "+getWidth()+"x"+getHeight());
     }
 
     public void surfaceChanged(SurfaceHolder aHolder, int aFormat, int aWidth, int aHeight) {
-        Log.d(MD.TAG, "surfaceChanged: f "+format+" -> "+aFormat+", "+aWidth+"x"+aHeight+", current surfaceHandle: 0x"+Long.toHexString(surfaceHandle));
-        if(0!=surfaceHandle && format != aFormat) {
+        Log.d(MD.TAG, "surfaceChanged: f "+nativeFormat+" -> "+aFormat+", "+aWidth+"x"+aHeight+", current surfaceHandle: 0x"+Long.toHexString(surfaceHandle));
+        if(0!=surfaceHandle && androidFormat != aFormat ) {
             // re-create
             Log.d(MD.TAG, "surfaceChanged (destroy old)");
-            windowDestroyNotify();
-            if(isNativeValid()) {
+            if(!windowDestroyNotify(true)) {
                 destroy();
             }
             surfaceHandle = 0;
             surface=null;
         }
-        getScreen().getCurrentScreenMode(); // if ScreenMode changed .. trigger ScreenMode event
+        if(getScreen().isNativeValid()) {
+            getScreen().getCurrentScreenMode(); // if ScreenMode changed .. trigger ScreenMode event
+        }
 
-        if(0>x || 0>y) {
-            x = 0;
-            y = 0;
+        if(0>getX() || 0>getY()) {
             positionChanged(false, 0, 0);
         }
         
         if(0 == surfaceHandle) {
+            androidFormat = aFormat;
             surface = aHolder.getSurface();
             surfaceHandle = getSurfaceHandle0(surface);
             acquire0(surfaceHandle);
-            format = getSurfaceVisualID0(surfaceHandle);
+            nativeFormat = getSurfaceVisualID0(surfaceHandle);
             final int nWidth = getWidth0(surfaceHandle);
             final int nHeight = getHeight0(surfaceHandle);
-            capsByFormat = (GLCapabilitiesImmutable) fixCaps(format, getRequestedCapabilities());
+            capsByFormat = (GLCapabilitiesImmutable) fixCaps(true /* matchFormatPrecise */, nativeFormat, getRequestedCapabilities());
             sizeChanged(false, nWidth, nHeight, false);
     
             Log.d(MD.TAG, "surfaceRealized: isValid: "+surface.isValid()+
-                          ", new surfaceHandle 0x"+Long.toHexString(surfaceHandle)+", format: "+format+
-                          ", "+x+"/"+y+" "+nWidth+"x"+nHeight+", visible: "+isVisible());
+                          ", new surfaceHandle 0x"+Long.toHexString(surfaceHandle)+
+                          ", format [a "+androidFormat+"/n "+nativeFormat+"], "+
+                          getX()+"/"+getY()+" "+nWidth+"x"+nHeight+", visible: "+isVisible());
     
             if(isVisible()) {
-               setVisible(true); 
+               setVisible(true);
             }
-        } else {
-            sizeChanged(false, aWidth, aHeight, false);
         }
+        sizeChanged(false, aWidth, aHeight, false);
         windowRepaint(0, 0, aWidth, aHeight);
         Log.d(MD.TAG, "surfaceChanged: X");
     }
     
     public void surfaceDestroyed(SurfaceHolder holder) {
         Log.d(MD.TAG, "surfaceDestroyed");
-        windowDestroyNotify();
+        windowDestroyNotify(true); // actually too late .. however ..
     }
 
     public void surfaceRedrawNeeded(SurfaceHolder holder) {
@@ -385,18 +378,20 @@ public class AndroidWindow extends jogamp.newt.WindowImpl implements Callback2 {
         windowRepaint(0, 0, getWidth(), getHeight());
     }
         
+    private boolean ownAndroidWindow;
     private MSurfaceView androidView;
-    private android.view.Window androidWindow;
-    private int format; // stored current PixelFormat
+    private int nativeFormat; // chosen current native PixelFormat (suitable for EGL)
+    private int androidFormat; // chosen current android PixelFormat (-1, -2 ..)
     private GLCapabilitiesImmutable capsByFormat; // fixed requestedCaps by PixelFormat
-    private Surface surface = null;
-    private volatile long surfaceHandle = 0;
-    private long eglSurface = 0;
+    private Surface surface;
+    private volatile long surfaceHandle;
+    private long eglSurface;
     
     class MSurfaceView extends SurfaceView {
         public MSurfaceView (Context ctx) {
             super(ctx);
             setBackgroundDrawable(null);
+            // setBackgroundColor(Color.TRANSPARENT);
         }
     }
     //----------------------------------------------------------------------
diff --git a/src/newt/classes/jogamp/newt/driver/android/MD.java b/src/newt/classes/jogamp/newt/driver/android/MD.java
index 06f7872..150dea9 100644
--- a/src/newt/classes/jogamp/newt/driver/android/MD.java
+++ b/src/newt/classes/jogamp/newt/driver/android/MD.java
@@ -27,11 +27,6 @@
  */
 package jogamp.newt.driver.android;
 
-import java.util.List;
-
-import javax.media.opengl.GLDrawableFactory;
-import javax.media.opengl.GLProfile;
-
 import com.jogamp.common.GlueGenVersion;
 import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.VersionUtil;
@@ -40,22 +35,17 @@ import com.jogamp.opengl.JoglVersion;
 public class MD {
    public static final String TAG = "JogAmp.NEWT";
    
-   public static String getInfo() { 
-       
-        StringBuffer sb = new StringBuffer();
+   public static String getInfo() {        
+        StringBuilder sb = new StringBuilder();
         
         sb.append(VersionUtil.getPlatformInfo()).append(Platform.NEWLINE)
               .append(GlueGenVersion.getInstance()).append(Platform.NEWLINE)
               .append(JoglVersion.getInstance()).append(Platform.NEWLINE)
               .append(Platform.NEWLINE);
               
-        final GLDrawableFactory factory = GLDrawableFactory.getEGLFactory();
-        final List/*<GLCapabilitiesImmutable>*/ availCaps = factory.getAvailableCapabilities(null);
-        for(int i=0; i<availCaps.size(); i++) {
-            sb.append(availCaps.get(i)).append(Platform.NEWLINE);
-        }
-       
-       return sb.toString();       
+        JoglVersion.getDefaultOpenGLInfo(sb);
+
+        return sb.toString();       
    }
    
     public static void main(String args[]) {
diff --git a/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java b/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java
index f7c05cd..4537fa9 100644
--- a/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java
+++ b/src/newt/classes/jogamp/newt/driver/android/NewtBaseActivity.java
@@ -27,50 +27,197 @@
  */
 package jogamp.newt.driver.android;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.media.nativewindow.CapabilitiesImmutable;
+import javax.media.opengl.FPSCounter;
+
 import com.jogamp.newt.Window;
 import com.jogamp.opengl.util.Animator;
 
 import jogamp.newt.driver.android.AndroidWindow;
 
 import android.app.Activity;
+import android.content.Context;
 import android.os.Bundle;
 import android.util.Log;
+import android.view.WindowManager;
 
 public class NewtBaseActivity extends Activity {
-   AndroidWindow newtWindow = null;
+   List<Window> newtWindows = new ArrayList<Window>();
    Animator animator = null;
     
-   boolean isInvokedByExternalActivity = false;
-   Activity extActivity = this;
+   boolean isDelegatedActivity;
+   Activity rootActivity;
+   boolean setThemeCalled = false;
+      
+   public NewtBaseActivity() {
+       super();
+       isDelegatedActivity = false;
+       rootActivity = this;
+   }
    
-   public void setIsInvokedByExternalActivity(Activity extActivity) {
-       this.extActivity = extActivity;
-       this.isInvokedByExternalActivity = null != extActivity;
+   public void setRootActivity(Activity rootActivity) {
+       this.isDelegatedActivity = true;
+       this.rootActivity = rootActivity;
    }
-   public boolean getIsInvokedByExternalActivity() {
-       return null != extActivity;
+   
+   public final boolean isDelegatedActivity() {
+       return isDelegatedActivity;
    }
    
-   public Activity getActivity() {
-       if(isInvokedByExternalActivity) {
-           return extActivity;
-       } else {
-           return this;               
-       }
+   public final Activity getActivity() {
+       return rootActivity;
    }     
    
+   /**
+    * This is one of the three registration methods (see below).
+    * <p>
+    * This methods issues {@link android.view.Window#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) androidWindow.setContenView(newtWindow.getAndroidView())}
+    * and finally calls {@link #registerNEWTWindow(Window)}.
+    * </p>  
+    * @param androidWindow
+    * @param newtWindow
+    * @see #addContentView(android.view.Window, Window, android.view.ViewGroup.LayoutParams)
+    */
    public void setContentView(android.view.Window androidWindow, Window newtWindow) {
        newtWindow = newtWindow.getDelegatedWindow();
        if(newtWindow instanceof AndroidWindow) {
-           this.newtWindow = (AndroidWindow)newtWindow;
-           this.newtWindow.setAndroidWindow(androidWindow);
-           if(isInvokedByExternalActivity) {
-               extActivity.setContentView(this.newtWindow.getAndroidView());
-           } else {
-               super.setContentView(this.newtWindow.getAndroidView());               
-           }
+           adaptTheme4Transparency(newtWindow.getRequestedCapabilities());
+           layoutForNEWTWindow(androidWindow, newtWindow);
+           AndroidWindow newtAWindow = (AndroidWindow)newtWindow;
+           androidWindow.setContentView(newtAWindow.getAndroidView());
+           registerNEWTWindow(newtAWindow);
+       } else {
+           throw new IllegalArgumentException("Given NEWT Window is not an Android Window: "+newtWindow.getClass()); 
+       }
+   }
+   /**
+    * This is one of the three registration methods (see below).
+    * <p>
+    * This methods issues {@link android.view.Window#addContentView(android.view.View, android.view.ViewGroup.LayoutParams) androidWindow.addContenView(newtWindow.getAndroidView(), params)}
+    * and finally calls {@link #registerNEWTWindow(Window)}.
+    * </p>  
+    * @param androidWindow
+    * @param newtWindow
+    * @param params
+    * @see #setContentView(android.view.Window, Window)
+    * @see #registerNEWTWindow(Window)
+    */
+   public void addContentView(android.view.Window androidWindow, Window newtWindow, android.view.ViewGroup.LayoutParams params) {
+       newtWindow = newtWindow.getDelegatedWindow();
+       if(newtWindow instanceof AndroidWindow) {
+           AndroidWindow newtAWindow = (AndroidWindow)newtWindow;
+           androidWindow.addContentView(newtAWindow.getAndroidView(), params);
+           registerNEWTWindow(newtAWindow);
        } else {
            throw new IllegalArgumentException("Given NEWT Window is not an Android Window: "+newtWindow.getClass()); 
+       }       
+   }
+   /**
+    * This is one of the three registration methods (see below).
+    * <p>
+    * This methods simply registers the given NEWT window to ensure it's destruction at {@link #onDestroy()}.
+    * </p>  
+    * 
+    * @param newtWindow
+    * @see #setContentView(android.view.Window, Window)
+    * @see #addContentView(android.view.Window, Window, android.view.ViewGroup.LayoutParams)
+    */
+   public void registerNEWTWindow(Window newtWindow) {
+       newtWindows.add(newtWindow);
+   }
+   
+   /**
+    * Convenient method to set the Android window's flags to fullscreen or size-layout depending on the given NEWT window. 
+    * <p>
+    * Must be called before creating the view and adding any content, i.e. setContentView() !
+    * </p>
+    * @param androidWindow
+    * @param newtWindow
+    */
+   public void layoutForNEWTWindow(android.view.Window androidWindow, Window newtWindow) {
+        if(null == androidWindow || null == newtWindow) {
+            throw new IllegalArgumentException("Android or NEWT Window null");
+        }
+        
+        if( newtWindow.isFullscreen() || newtWindow.isUndecorated() ) {
+            androidWindow.requestFeature(android.view.Window.FEATURE_NO_TITLE);
+        }
+        if( newtWindow.isFullscreen() ) {
+            androidWindow.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+            androidWindow.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
+        } else {
+            androidWindow.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
+            androidWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);                
+        }
+        
+        if(newtWindow.getWidth()>0 && newtWindow.getHeight()>0 && !newtWindow.isFullscreen()) {            
+            androidWindow.setLayout(newtWindow.getWidth(), newtWindow.getHeight());
+        }       
+   }
+
+   /**
+    * Convenient method to set the Android window's flags to fullscreen or size-layout depending on the given NEWT window. 
+    * <p>
+    * Must be called before creating the view and adding any content, i.e. setContentView() !
+    * </p>
+    * @param androidWindow
+    * @param newtWindow
+    */
+   public void setFullscreenFeature(android.view.Window androidWindow, boolean fullscreen) {
+        if(null == androidWindow) {
+            throw new IllegalArgumentException("Android or Window null");
+        }
+        
+        if( fullscreen ) {
+            androidWindow.requestFeature(android.view.Window.FEATURE_NO_TITLE);
+            androidWindow.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+            androidWindow.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
+        } else {
+            androidWindow.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
+            androidWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+        }
+   }
+   
+   /**
+    * Convenient method to set this context's theme to transparency depending on {@link CapabilitiesImmutable#isBackgroundOpaque()}. 
+    * <p>
+    * Must be called before creating the view and adding any content, i.e. setContentView() !
+    * </p>
+    */
+   protected void adaptTheme4Transparency(CapabilitiesImmutable caps) {
+        if(!caps.isBackgroundOpaque()) {
+            setTransparencyTheme();
+        }
+   }
+   
+   /**
+    * Convenient method to set this context's theme to transparency.
+    * <p>
+    * Must be called before creating the view and adding any content, i.e. setContentView() !
+    * </p>
+    * <p>
+    * Is normally issued by {@link #setContentView(android.view.Window, Window)}
+    * if the requested NEWT Capabilities ask for transparency.
+    * </p>
+    * <p>
+    * Can be called only once.
+    * </p>  
+    */
+   public void setTransparencyTheme() {
+       if(!setThemeCalled) {
+           setThemeCalled = true;
+           final Context ctx = getActivity().getApplicationContext();            
+           final String frn = ctx.getPackageName()+":style/Theme.Transparent";
+           final int resID = ctx.getResources().getIdentifier("Theme.Transparent", "style", ctx.getPackageName());
+           if(0 == resID) {
+               Log.d(MD.TAG, "SetTransparencyTheme: Resource n/a: "+frn);
+           } else {
+               Log.d(MD.TAG, "SetTransparencyTheme: Setting style: "+frn+": 0x"+Integer.toHexString(resID));
+               ctx.setTheme(resID);
+           }
        }
    }
    
@@ -90,20 +237,16 @@ public class NewtBaseActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(MD.TAG, "onCreate");
-       if(!isInvokedByExternalActivity) {
+       if(!isDelegatedActivity()) {
            super.onCreate(savedInstanceState);
-           // register application context 
-           jogamp.common.os.android.StaticContext.setContext(getApplicationContext());
-       } else {
-           jogamp.common.os.android.StaticContext.setContext(extActivity.getApplicationContext());
        }
-       extActivity.getWindow();
+       jogamp.common.os.android.StaticContext.init(rootActivity.getApplicationContext());
    }
    
    @Override
    public void onStart() {
      Log.d(MD.TAG, "onStart");
-     if(!isInvokedByExternalActivity) {
+     if(!isDelegatedActivity()) {
          super.onStart();
      }
    }
@@ -111,7 +254,7 @@ public class NewtBaseActivity extends Activity {
    @Override
    public void onRestart() {
      Log.d(MD.TAG, "onRestart");
-     if(!isInvokedByExternalActivity) {
+     if(!isDelegatedActivity()) {
          super.onRestart();
      }
    }
@@ -119,11 +262,18 @@ public class NewtBaseActivity extends Activity {
    @Override
    public void onResume() {
      Log.d(MD.TAG, "onResume");
-     if(!isInvokedByExternalActivity) {
+     if(!isDelegatedActivity()) {
          super.onResume();
      }
      if(null != animator) {
          animator.resume();
+         animator.resetFPSCounter();
+     }
+     for(int i=newtWindows.size()-1; i>=0; i--) {
+         final Window win = newtWindows.get(i);
+         if(win instanceof FPSCounter) {
+             ((FPSCounter)win).resetFPSCounter();
+         }
      }
    }
 
@@ -133,7 +283,7 @@ public class NewtBaseActivity extends Activity {
      if(null != animator) {
          animator.pause();
      }
-     if(!isInvokedByExternalActivity) {
+     if(!isDelegatedActivity()) {
          super.onPause();
      }
    }
@@ -141,7 +291,7 @@ public class NewtBaseActivity extends Activity {
    @Override
    public void onStop() {
      Log.d(MD.TAG, "onStop");
-     if(!isInvokedByExternalActivity) {
+     if(!isDelegatedActivity()) {
          super.onStop();  
      }
    }
@@ -153,11 +303,12 @@ public class NewtBaseActivity extends Activity {
          animator.stop();
          animator = null;
      }
-     if(null != newtWindow) {
-         newtWindow.destroy();
-         newtWindow = null;
+     while(newtWindows.size()>0) {
+         final Window win = newtWindows.remove(newtWindows.size()-1);
+         win.destroy();
      }
-     if(!isInvokedByExternalActivity) {
+     jogamp.common.os.android.StaticContext.clear();
+     if(!isDelegatedActivity()) {
          super.onDestroy(); 
      }
    }   
diff --git a/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java
index 863bfd3..d23b5f5 100644
--- a/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java
+++ b/src/newt/classes/jogamp/newt/driver/android/event/AndroidNewtEventFactory.java
@@ -45,10 +45,6 @@ public class AndroidNewtEventFactory {
         IntIntHashMap map = new IntIntHashMap();
         map.setKeyNotFoundValue(0xFFFFFFFF);
         
-        map.put(android.view.KeyEvent.ACTION_DOWN, com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED);
-        map.put(android.view.KeyEvent.ACTION_UP, com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED);
-        map.put(android.view.KeyEvent.ACTION_MULTIPLE, com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED);
-        
         map.put(android.view.MotionEvent.ACTION_DOWN, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_PRESSED);
         map.put(android.view.MotionEvent.ACTION_UP, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED);
         map.put(android.view.MotionEvent.ACTION_CANCEL, com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED);
@@ -64,46 +60,47 @@ public class AndroidNewtEventFactory {
     }
 
     static final int androidKeyCode2Newt(int androidKeyCode) {
-        //safest ...but ugly
-        if (android.view.KeyEvent.KEYCODE_0 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_0;
-        if (android.view.KeyEvent.KEYCODE_1 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_1;
-        if (android.view.KeyEvent.KEYCODE_2 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_2;
-        if (android.view.KeyEvent.KEYCODE_3 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_3;
-        if (android.view.KeyEvent.KEYCODE_4 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_4;
-        if (android.view.KeyEvent.KEYCODE_5 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_5;
-        if (android.view.KeyEvent.KEYCODE_6 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_6;
-        if (android.view.KeyEvent.KEYCODE_7 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_7;
-        if (android.view.KeyEvent.KEYCODE_8 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_8;
-        if (android.view.KeyEvent.KEYCODE_9 == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_9;
-        
-        if (android.view.KeyEvent.KEYCODE_A == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_A;
-        if (android.view.KeyEvent.KEYCODE_B == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_B;
-        if (android.view.KeyEvent.KEYCODE_C == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_C;
-        if (android.view.KeyEvent.KEYCODE_D == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_D;
-        if (android.view.KeyEvent.KEYCODE_E == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_E;
-        if (android.view.KeyEvent.KEYCODE_F == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_F;
-        if (android.view.KeyEvent.KEYCODE_G == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_G;
-        if (android.view.KeyEvent.KEYCODE_H == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_H;
-        if (android.view.KeyEvent.KEYCODE_I == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_I;
-        if (android.view.KeyEvent.KEYCODE_J == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_J;
-        if (android.view.KeyEvent.KEYCODE_K == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_K;
-        if (android.view.KeyEvent.KEYCODE_L == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_L;
-        if (android.view.KeyEvent.KEYCODE_M == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_M;
-        if (android.view.KeyEvent.KEYCODE_N == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_N;
-        if (android.view.KeyEvent.KEYCODE_O == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_O;
-        if (android.view.KeyEvent.KEYCODE_P == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_P;
-        if (android.view.KeyEvent.KEYCODE_Q == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_Q;
-        if (android.view.KeyEvent.KEYCODE_R == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_R;
-        if (android.view.KeyEvent.KEYCODE_S == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_S;
-        if (android.view.KeyEvent.KEYCODE_T == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_T;
-        if (android.view.KeyEvent.KEYCODE_U == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_U;
-        if (android.view.KeyEvent.KEYCODE_V == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_V;
-        if (android.view.KeyEvent.KEYCODE_W == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_W;
-        if (android.view.KeyEvent.KEYCODE_X == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_X;
-        if (android.view.KeyEvent.KEYCODE_Y == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_Y;
-        if (android.view.KeyEvent.KEYCODE_Z == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_Z;
-          
-        if (android.view.KeyEvent.KEYCODE_AT == androidKeyCode) return com.jogamp.newt.event.KeyEvent.VK_AT;
+        if(android.view.KeyEvent.KEYCODE_0 <= androidKeyCode && androidKeyCode <= android.view.KeyEvent.KEYCODE_9) {
+            return com.jogamp.newt.event.KeyEvent.VK_0 + ( androidKeyCode - android.view.KeyEvent.KEYCODE_0 ) ; 
+        }
+        if(android.view.KeyEvent.KEYCODE_A <= androidKeyCode && androidKeyCode <= android.view.KeyEvent.KEYCODE_Z) {
+            return com.jogamp.newt.event.KeyEvent.VK_A + ( androidKeyCode - android.view.KeyEvent.KEYCODE_A ) ; 
+        }
+        if(android.view.KeyEvent.KEYCODE_F1 <= androidKeyCode && androidKeyCode <= android.view.KeyEvent.KEYCODE_F12) {
+            return com.jogamp.newt.event.KeyEvent.VK_F1 + ( androidKeyCode - android.view.KeyEvent.KEYCODE_F1 ) ; 
+        }
+        if(android.view.KeyEvent.KEYCODE_NUMPAD_0 <= androidKeyCode && androidKeyCode <= android.view.KeyEvent.KEYCODE_NUMPAD_9) {
+            return com.jogamp.newt.event.KeyEvent.VK_NUMPAD0 + ( androidKeyCode - android.view.KeyEvent.KEYCODE_NUMPAD_0 ) ; 
+        }           
+        switch(androidKeyCode) {
+            case android.view.KeyEvent.KEYCODE_COMMA: return com.jogamp.newt.event.KeyEvent.VK_COMMA; 
+            case android.view.KeyEvent.KEYCODE_PERIOD: return com.jogamp.newt.event.KeyEvent.VK_PERIOD;
+            case android.view.KeyEvent.KEYCODE_ALT_LEFT: return com.jogamp.newt.event.KeyEvent.VK_ALT;
+            case android.view.KeyEvent.KEYCODE_ALT_RIGHT: return com.jogamp.newt.event.KeyEvent.VK_ALT_GRAPH;
+            case android.view.KeyEvent.KEYCODE_SHIFT_LEFT: return com.jogamp.newt.event.KeyEvent.VK_SHIFT;
+            case android.view.KeyEvent.KEYCODE_SHIFT_RIGHT: return com.jogamp.newt.event.KeyEvent.VK_SHIFT;
+            case android.view.KeyEvent.KEYCODE_TAB: return com.jogamp.newt.event.KeyEvent.VK_TAB;
+            case android.view.KeyEvent.KEYCODE_SPACE: return com.jogamp.newt.event.KeyEvent.VK_SPACE;
+            case android.view.KeyEvent.KEYCODE_ENTER: return com.jogamp.newt.event.KeyEvent.VK_ENTER;
+            case android.view.KeyEvent.KEYCODE_DEL: return com.jogamp.newt.event.KeyEvent.VK_DELETE;
+            case android.view.KeyEvent.KEYCODE_MINUS: return com.jogamp.newt.event.KeyEvent.VK_MINUS;
+            case android.view.KeyEvent.KEYCODE_EQUALS: return com.jogamp.newt.event.KeyEvent.VK_EQUALS;
+            case android.view.KeyEvent.KEYCODE_LEFT_BRACKET: return com.jogamp.newt.event.KeyEvent.VK_LEFT_PARENTHESIS;
+            case android.view.KeyEvent.KEYCODE_RIGHT_BRACKET: return com.jogamp.newt.event.KeyEvent.VK_RIGHT_PARENTHESIS;
+            case android.view.KeyEvent.KEYCODE_BACKSLASH: return com.jogamp.newt.event.KeyEvent.VK_BACK_SLASH;
+            case android.view.KeyEvent.KEYCODE_SEMICOLON: return com.jogamp.newt.event.KeyEvent.VK_SEMICOLON;
+            // case android.view.KeyEvent.KEYCODE_APOSTROPHE: ??
+            case android.view.KeyEvent.KEYCODE_SLASH: return com.jogamp.newt.event.KeyEvent.VK_SLASH;
+            case android.view.KeyEvent.KEYCODE_AT: return com.jogamp.newt.event.KeyEvent.VK_AT;
+            // case android.view.KeyEvent.KEYCODE_MUTE: ??
+            case android.view.KeyEvent.KEYCODE_PAGE_UP: return com.jogamp.newt.event.KeyEvent.VK_PAGE_UP;
+            case android.view.KeyEvent.KEYCODE_PAGE_DOWN: return com.jogamp.newt.event.KeyEvent.VK_PAGE_DOWN;
+            // case android.view.KeyEvent.KEYCODE_HOME: return com.jogamp.newt.event.KeyEvent.VK_HOME;
+            // case android.view.KeyEvent.KEYCODE_BACK: return com.jogamp.newt.event.KeyEvent.VK_BACK_SPACE;
+            case android.view.KeyEvent.KEYCODE_ESCAPE: return com.jogamp.newt.event.KeyEvent.VK_ESCAPE;
+            case android.view.KeyEvent.KEYCODE_CTRL_LEFT: return com.jogamp.newt.event.KeyEvent.VK_CONTROL;
+            case android.view.KeyEvent.KEYCODE_CTRL_RIGHT: return com.jogamp.newt.event.KeyEvent.VK_CONTROL; // ??
+        }        
         return 0;
     }
     
@@ -124,18 +121,47 @@ public class AndroidNewtEventFactory {
         return newtMods;
     }
     
-    public static final com.jogamp.newt.event.KeyEvent createKeyEvent(android.view.KeyEvent event, com.jogamp.newt.Window newtSource) {
-        int type = eventTypeANDROID2NEWT.get(event.getAction());
+    private static final int androidKeyAction2NewtEventType(int androidKeyAction) {
+        switch(androidKeyAction) {
+            case android.view.KeyEvent.ACTION_DOWN: 
+            case android.view.KeyEvent.ACTION_MULTIPLE:
+                return com.jogamp.newt.event.KeyEvent.EVENT_KEY_PRESSED;
+            case android.view.KeyEvent.ACTION_UP:
+                return com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED;
+            default: 
+                return 0;
+        }
+    }
+    
+    public static final com.jogamp.newt.event.KeyEvent[] createKeyEvents(int keyCode, android.view.KeyEvent event, com.jogamp.newt.Window newtSource) {
+        final int type = androidKeyAction2NewtEventType(event.getAction());        
+        if(Window.DEBUG_MOUSE_EVENT) {
+            System.err.println("createKeyEvent: type 0x"+Integer.toHexString(type)+", keyCode 0x"+Integer.toHexString(keyCode)+", "+event);
+        }
         if(0xFFFFFFFF != type) {
-            return new com.jogamp.newt.event.KeyEvent(
-                           type, (null==newtSource)?null:(Object)newtSource, event.getEventTime(), 
-                           androidKeyModifiers2Newt(event.getMetaState()), 
-                           androidKeyCode2Newt(event.getKeyCode()), event.getDisplayLabel());
+            final int newtKeyCode = androidKeyCode2Newt(keyCode);
+            if(0 != newtKeyCode) {
+                final Object src = (null==newtSource)?null:(Object)newtSource;
+                final long unixTime = System.currentTimeMillis() + ( event.getEventTime() - android.os.SystemClock.uptimeMillis() );
+                final int newtMods = androidKeyModifiers2Newt(event.getMetaState());
+                
+                final com.jogamp.newt.event.KeyEvent ke1 = new com.jogamp.newt.event.KeyEvent(
+                                    type, src, unixTime, newtMods, newtKeyCode, event.getDisplayLabel());
+                
+                if( com.jogamp.newt.event.KeyEvent.EVENT_KEY_RELEASED == type ) {
+                    return new com.jogamp.newt.event.KeyEvent[] { ke1,
+                            new com.jogamp.newt.event.KeyEvent(
+                                    com.jogamp.newt.event.KeyEvent.EVENT_KEY_TYPED,
+                                    src, unixTime, newtMods, newtKeyCode, event.getDisplayLabel()) };
+                } else {
+                    return new com.jogamp.newt.event.KeyEvent[] { ke1 };
+                }
+            }
         }
         return null;
     }
 
-    public static final com.jogamp.newt.event.MouseEvent[] createMouseEvents(com.jogamp.newt.Window newtSource, android.view.MotionEvent event) {
+    public static final com.jogamp.newt.event.MouseEvent[] createMouseEvents(android.view.MotionEvent event, com.jogamp.newt.Window newtSource) {
         if(Window.DEBUG_MOUSE_EVENT) {
             System.err.println("createMouseEvent: "+toString(event));
         }
@@ -167,30 +193,24 @@ public class AndroidNewtEventFactory {
                 }
             }
                                 
-            com.jogamp.newt.event.MouseEvent res[];
-
-            com.jogamp.newt.event.MouseEvent me1 = 
-                    new com.jogamp.newt.event.MouseEvent(
-                           type, 
-                           (null==newtSource)?null:(Object)newtSource, event.getEventTime(),
+            final Object src = (null==newtSource)?null:(Object)newtSource;
+            final long unixTime = System.currentTimeMillis() + ( event.getEventTime() - android.os.SystemClock.uptimeMillis() );
+            final int button = pointers.length==1 ? MouseEvent.BUTTON1 : 0;
+            
+            final com.jogamp.newt.event.MouseEvent me1 = new com.jogamp.newt.event.MouseEvent(
+                           type,  src, unixTime,
                            modifiers, x, y, pressure, pointers, clickCount, 
-                           pointers.length==1 ? MouseEvent.BUTTON1 : 0, rotation);
+                           button, rotation);
             
             if(type == com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_RELEASED) {
-                com.jogamp.newt.event.MouseEvent me2 =
+                return new com.jogamp.newt.event.MouseEvent[] { me1, 
                     new com.jogamp.newt.event.MouseEvent(
                            com.jogamp.newt.event.MouseEvent.EVENT_MOUSE_CLICKED, 
-                           (null==newtSource)?null:(Object)newtSource, event.getEventTime(),
-                           modifiers, x, y, pressure, pointers, clickCount, 
-                           pointers.length==1 ? MouseEvent.BUTTON1 : 0, rotation);
-                res = new com.jogamp.newt.event.MouseEvent[2];
-                res[0] = me1;
-                res[1] = me2;
+                           src, unixTime, modifiers, x, y, pressure, pointers, clickCount, 
+                           button, rotation) };
             } else {
-                res = new com.jogamp.newt.event.MouseEvent[1];
-                res[0] = me1;                
+                return new com.jogamp.newt.event.MouseEvent[] { me1 }; 
             }
-            return res;
         } 
         return null; // no mapping ..
     }
diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java
index b63e433..5a49dd5 100644
--- a/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java
+++ b/src/newt/classes/jogamp/newt/driver/awt/AWTCanvas.java
@@ -46,9 +46,11 @@ import javax.media.nativewindow.CapabilitiesChooser;
 import javax.media.nativewindow.CapabilitiesImmutable;
 import javax.media.nativewindow.GraphicsConfigurationFactory;
 import javax.media.nativewindow.NativeWindowException;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
+
+
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
 import com.jogamp.newt.Window;
 
 public class AWTCanvas extends Canvas {
@@ -196,12 +198,12 @@ public class AWTCanvas extends Canvas {
         if(Window.DEBUG_IMPLEMENTATION) {
             Exception e = new Exception("Info: Call Stack: "+Thread.currentThread().getName());
             e.printStackTrace();
-            System.err.println("!!! Created Config (n): HAVE    GC "+chosen);
-            System.err.println("!!! Created Config (n): THIS    GC "+gc);
-            System.err.println("!!! Created Config (n): Choosen GC "+compatible);
-            System.err.println("!!! Created Config (n): HAVE    CF "+awtConfig);
-            System.err.println("!!! Created Config (n): Choosen CF "+config);
-            System.err.println("!!! Created Config (n): EQUALS CAPS "+config.getChosenCapabilities().equals(awtConfig.getChosenCapabilities()));
+            System.err.println("Created Config (n): HAVE    GC "+chosen);
+            System.err.println("Created Config (n): THIS    GC "+gc);
+            System.err.println("Created Config (n): Choosen GC "+compatible);
+            System.err.println("Created Config (n): HAVE    CF "+awtConfig);
+            System.err.println("Created Config (n): Choosen CF "+config);
+            System.err.println("Created Config (n): EQUALS CAPS "+config.getChosenCapabilities().equals(awtConfig.getChosenCapabilities()));
         }
 
         if (compatible != null) {
diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java b/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java
index f22ec6f..166da5c 100644
--- a/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java
+++ b/src/newt/classes/jogamp/newt/driver/awt/AWTDisplay.java
@@ -34,8 +34,9 @@
 
 package jogamp.newt.driver.awt;
 
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
 import com.jogamp.newt.NewtFactory;
+
 import jogamp.newt.DisplayImpl;
 
 public class AWTDisplay extends DisplayImpl {
diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java
index 6d0b102..9426511 100644
--- a/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java
+++ b/src/newt/classes/jogamp/newt/driver/awt/AWTEDTUtil.java
@@ -28,27 +28,15 @@
 
 package jogamp.newt.driver.awt;
 
-import java.awt.EventQueue;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
+import javax.media.opengl.Threading;
 
-import javax.media.nativewindow.NativeWindowException;
-
-import com.jogamp.newt.Display;
 import com.jogamp.newt.util.EDTUtil;
 import jogamp.newt.Debug;
 
 public class AWTEDTUtil implements EDTUtil {
     public static final boolean DEBUG = Debug.debug("EDT");
 
-    private static Timer pumpMessagesTimer=null;
-    private static TimerTask pumpMessagesTimerTask=null;
-    private static final Map<Display, Runnable> pumpMessageDisplayMap = new HashMap<Display, Runnable>();
     private static AWTEDTUtil singletonMainThread = new AWTEDTUtil(); // one singleton MainThread
-    private static long pollPeriod = EDTUtil.defaultEDTPollPeriod;
     
     public static AWTEDTUtil getSingleton() {
         return singletonMainThread;
@@ -59,11 +47,11 @@ public class AWTEDTUtil implements EDTUtil {
     }
 
     final public long getPollPeriod() {
-        return pollPeriod;
+        return 0;
     }
 
     final public void setPollPeriod(long ms) {
-        pollPeriod = ms;
+        // nop
     }
     
     final public void reset() {
@@ -75,7 +63,7 @@ public class AWTEDTUtil implements EDTUtil {
     }
 
     final public boolean isCurrentThreadEDT() {
-        return EventQueue.isDispatchThread();
+        return Threading.isToolkitThread();
     }
 
     final public boolean isRunning() {
@@ -90,62 +78,22 @@ public class AWTEDTUtil implements EDTUtil {
         if(r == null) {
             return;
         }
-
-        // handover to AWT MainThread ..
-        try {
-            if ( isCurrentThreadEDT() ) {
-                r.run();
-                return;
-            }
-            if(wait) {
-                EventQueue.invokeAndWait(r);
-            } else {
-                EventQueue.invokeLater(r);
-            }
-        } catch (Exception e) {
-            throw new NativeWindowException(e);
-        }
+        
+        Threading.invoke(wait, r, null);
     }
 
     final public void waitUntilIdle() {
         // wait until previous events are processed, at least ..
         try {
-            EventQueue.invokeAndWait( new Runnable() {
+            Threading.invoke(true, new Runnable() {
                 public void run() { }
-            });
+            }, null);
         } catch (Exception e) { }
     }
 
     final public void waitUntilStopped() {
         // nop: AWT is always running
     }
-
-    public static void addPumpMessage(Display dpy, Runnable pumpMessage) {
-        if(DEBUG) {
-            System.err.println("AWTEDTUtil.addPumpMessage(): "+Thread.currentThread().getName()+" - dpy "+dpy);
-        }
-        
-        synchronized (pumpMessageDisplayMap) {
-            if(null == pumpMessagesTimer) {
-                // AWT pump messages .. MAIN_THREAD uses main thread
-                pumpMessagesTimer = new Timer();
-                pumpMessagesTimerTask = new TimerTask() {
-                    public void run() {
-                        synchronized(pumpMessageDisplayMap) {
-                            for(Iterator<Runnable> i = pumpMessageDisplayMap.values().iterator(); i.hasNext(); ) {
-                                AWTEDTUtil.getSingleton().invoke(true, i.next());
-                                // AWTEDTUtil.getSingleton().invoke(false, i.next());
-                                // i.next().run();
-                            }
-                        }
-                    }
-                };
-                pumpMessagesTimer.scheduleAtFixedRate(pumpMessagesTimerTask, 0, pollPeriod);
-            }
-            pumpMessageDisplayMap.put(dpy, pumpMessage);
-        }
-    }
-
 }
 
 
diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java b/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java
index 644c963..a3c0281 100644
--- a/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java
+++ b/src/newt/classes/jogamp/newt/driver/awt/AWTScreen.java
@@ -36,8 +36,11 @@ package jogamp.newt.driver.awt;
 import java.awt.DisplayMode;
 
 import jogamp.newt.ScreenImpl;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
+
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
 
 public class AWTScreen extends ScreenImpl {
     public AWTScreen() {
@@ -45,21 +48,34 @@ public class AWTScreen extends ScreenImpl {
 
     protected void createNativeImpl() {
         aScreen = new AWTGraphicsScreen((AWTGraphicsDevice)display.getGraphicsDevice());
-        
-        final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode();
-        if(null != mode) {
-            setScreenSize(mode.getWidth(), mode.getHeight());
-        }
     }
 
     protected void setAWTGraphicsScreen(AWTGraphicsScreen s) {
         aScreen = s;
     }
 
-    // done by AWTWindow ..
-    protected void setScreenSize(int w, int h) {
-        super.setScreenSize(w, h);
+    /**
+     *  Used by AWTWindow ..
+     */
+    @Override
+    protected void updateVirtualScreenOriginAndSize() {
+        super.updateVirtualScreenOriginAndSize();
     }
 
     protected void closeNativeImpl() { }
+    
+    protected int validateScreenIndex(int idx) {
+        return idx; // pass through ... 
+    }    
+
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        final DisplayMode mode = ((AWTGraphicsDevice)getDisplay().getGraphicsDevice()).getGraphicsDevice().getDisplayMode();
+        if(null != mode) {
+            virtualOrigin.setX(0);
+            virtualOrigin.setY(0);
+            virtualSize.setWidth(mode.getWidth());
+            virtualSize.setHeight(mode.getHeight());
+        }
+    }
+    
 }
diff --git a/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java b/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java
index ca280fa..2b2fed5 100644
--- a/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/awt/AWTWindow.java
@@ -36,16 +36,17 @@ package jogamp.newt.driver.awt;
 
 import java.awt.BorderLayout;
 import java.awt.Container;
-import java.awt.DisplayMode;
 import java.awt.Frame;
 import java.awt.Insets;
 
 import javax.media.nativewindow.NativeWindowException;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
-import javax.media.nativewindow.awt.AWTGraphicsDevice;
-import javax.media.nativewindow.awt.AWTGraphicsScreen;
 import javax.media.nativewindow.util.Point;
+
 import jogamp.newt.WindowImpl;
+
+import com.jogamp.nativewindow.awt.AWTGraphicsConfiguration;
+import com.jogamp.nativewindow.awt.AWTGraphicsDevice;
+import com.jogamp.nativewindow.awt.AWTGraphicsScreen;
 import com.jogamp.newt.event.awt.AWTKeyAdapter;
 import com.jogamp.newt.event.awt.AWTMouseAdapter;
 import com.jogamp.newt.event.awt.AWTWindowAdapter;
@@ -60,13 +61,12 @@ public class AWTWindow extends WindowImpl {
         this(null);
     }
 
-    public static Class[] getCustomConstructorArgumentTypes() {
-        return new Class[] { Container.class } ;
+    public static Class<?>[] getCustomConstructorArgumentTypes() {
+        return new Class<?>[] { Container.class } ;
     }
 
     public AWTWindow(Container container) {
         super();
-        title = "AWT NewtWindow";
         this.container = container;
         if(container instanceof Frame) {
             frame = (Frame) container;
@@ -100,10 +100,8 @@ public class AWTWindow extends WindowImpl {
             owningFrame=true;
         } else {
             owningFrame=false;
-            width = container.getWidth();
-            height = container.getHeight();
-            x = container.getX();
-            y = container.getY();
+            defineSize(container.getWidth(), container.getHeight());
+            definePosition(container.getX(), container.getY());            
         }
         if(null!=frame) {
             frame.setTitle(getTitle());
@@ -118,11 +116,11 @@ public class AWTWindow extends WindowImpl {
 
         // canvas.addComponentListener(listener);
         container.add(canvas, BorderLayout.CENTER);
-        container.setSize(width, height);
-        container.setLocation(x, y);
+        container.setSize(getWidth(), getHeight());
+        container.setLocation(getX(), getY());
         new AWTWindowAdapter(this).addTo(container); // fwd all AWT Window events to here
 
-        reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY | FLAG_CHANGE_DECORATION, true));
+        reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY | FLAG_CHANGE_DECORATION, true));
         // throws exception if failed ..
         
         setWindowHandle(1); // just a marker ..
@@ -157,10 +155,7 @@ public class AWTWindow extends WindowImpl {
             ((AWTScreen)getScreen()).setAWTGraphicsScreen((AWTGraphicsScreen)cfg.getScreen());
             ((AWTDisplay)getScreen().getDisplay()).setAWTGraphicsDevice((AWTGraphicsDevice)cfg.getScreen().getDevice());
     
-            final DisplayMode mode = ((AWTGraphicsDevice)cfg.getScreen().getDevice()).getGraphicsDevice().getDisplayMode();
-            if(null != mode) {
-                ((AWTScreen)getScreen()).setScreenSize(mode.getWidth(), mode.getHeight());
-            }
+            ((AWTScreen)getScreen()).updateVirtualScreenOriginAndSize();
         }
         return res;
     }
@@ -188,11 +183,6 @@ public class AWTWindow extends WindowImpl {
             container.setVisible(0 != ( FLAG_IS_VISIBLE & flags));
         }
         
-        x=(x>=0)?x:AWTWindow.this.x;
-        y=(x>=0)?y:AWTWindow.this.y;
-        width=(width>0)?width:AWTWindow.this.width;
-        height=(height>0)?height:AWTWindow.this.height;
-
         container.setLocation(x, y);
         Insets insets = container.getInsets();
         container.setSize(width + insets.left + insets.right,
@@ -230,15 +220,13 @@ public class AWTWindow extends WindowImpl {
         @Override
         public void windowMoved(com.jogamp.newt.event.WindowEvent e) {
             if(null!=container) {
-                x = container.getX();
-                y = container.getY();
+                definePosition(container.getX(), container.getY());
             }
         }
         @Override
         public void windowResized(com.jogamp.newt.event.WindowEvent e) {
             if(null!=canvas) {
-                width = canvas.getWidth();
-                height = canvas.getHeight();
+                defineSize(canvas.getWidth(), canvas.getHeight());
             }
         }
     }
diff --git a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java
index 1ed91c1..40d0ad2 100644
--- a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java
+++ b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Display.java
@@ -36,7 +36,8 @@ package jogamp.newt.driver.broadcom.egl;
 import jogamp.newt.*;
 import jogamp.opengl.egl.*;
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.egl.*;
+
+import com.jogamp.nativewindow.egl.*;
 
 public class Display extends jogamp.newt.DisplayImpl {
 
diff --git a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Screen.java b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Screen.java
index 0a84537..11b8dfc 100644
--- a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Screen.java
+++ b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Screen.java
@@ -34,6 +34,8 @@
 package jogamp.newt.driver.broadcom.egl;
 
 import javax.media.nativewindow.*;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
 
 public class Screen extends jogamp.newt.ScreenImpl {
 
@@ -47,16 +49,26 @@ public class Screen extends jogamp.newt.ScreenImpl {
 
     protected void createNativeImpl() {
         aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx);
-        setScreenSize(fixedWidth, fixedHeight);
     }
 
     protected void closeNativeImpl() { }
 
+    protected int validateScreenIndex(int idx) {
+        return 0; // only one screen available 
+    }
+     
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(0);
+        virtualOrigin.setY(0);
+        virtualSize.setWidth(fixedWidth); // FIXME
+        virtualSize.setHeight(fixedHeight); // FIXME
+    }
+    
     //----------------------------------------------------------------------
     // Internals only
     //
 
-    static final int fixedWidth = 1920;
-    static final int fixedHeight = 1080;
+    static final int fixedWidth = 1920;  // FIXME
+    static final int fixedHeight = 1080; // FIXME
 }
 
diff --git a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java
index 6f66eed..bd63f83 100644
--- a/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java
+++ b/src/newt/classes/jogamp/newt/driver/broadcom/egl/Window.java
@@ -35,7 +35,6 @@ package jogamp.newt.driver.broadcom.egl;
 
 import jogamp.opengl.egl.*;
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.awt.AWTGraphicsConfiguration;
 import javax.media.nativewindow.util.Insets;
 import javax.media.nativewindow.util.Point;
 import javax.media.opengl.GLCapabilitiesImmutable;
@@ -62,7 +61,7 @@ public class Window extends jogamp.newt.WindowImpl {
         setGraphicsConfiguration(cfg);
         setSizeImpl(getScreen().getWidth(), getScreen().getHeight());
 
-        setWindowHandle(realizeWindow(true, width, height));
+        setWindowHandle(realizeWindow(true, getWidth(), getHeight()));
         if (0 == getWindowHandle()) {
             throw new NativeWindowException("Error native Window Handle is null");
         }
@@ -81,8 +80,7 @@ public class Window extends jogamp.newt.WindowImpl {
             // n/a in BroadcomEGL
             System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window");
         } else {
-            this.width = width;
-            this.height = height;
+            defineSize(width, height);
         }
     }
 
@@ -101,8 +99,7 @@ public class Window extends jogamp.newt.WindowImpl {
                 // n/a in BroadcomEGL
                 System.err.println("BCEGL Window.setSizeImpl n/a in BroadcomEGL with realized window");
             } else {
-                this.width=(width>0)?width:this.width;
-                this.height=(height>0)?height:this.height;
+                defineSize((width>0)?width:getWidth(), (height>0)?height:getHeight());
             }
         }
         if(x>=0 || y>=0) {
@@ -152,8 +149,7 @@ public class Window extends jogamp.newt.WindowImpl {
     }
 
     private void windowCreated(int cfgID, int width, int height) {
-        this.width = width;
-        this.height = height;
+        defineSize(width, height);
         GLCapabilitiesImmutable capsReq = (GLCapabilitiesImmutable) getGraphicsConfiguration().getRequestedCapabilities();
         final AbstractGraphicsConfiguration cfg = EGLGraphicsConfiguration.create(capsReq, getScreen().getGraphicsScreen(), cfgID);
         if (null == cfg) {
diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java
index 26b7120..66ad1c6 100644
--- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java
+++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/Screen.java
@@ -33,8 +33,10 @@
 
 package jogamp.newt.driver.intel.gdl;
 
-import jogamp.newt.*;
-import javax.media.nativewindow.*;
+import javax.media.nativewindow.AbstractGraphicsDevice;
+import javax.media.nativewindow.DefaultGraphicsScreen;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
 
 public class Screen extends jogamp.newt.ScreenImpl {
 
@@ -53,6 +55,17 @@ public class Screen extends jogamp.newt.ScreenImpl {
 
     protected void closeNativeImpl() { }
 
+    protected int validateScreenIndex(int idx) {
+        return 0; // only one screen available 
+    }
+        
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(0);
+        virtualOrigin.setY(0);
+        virtualSize.setWidth(cachedWidth);
+        virtualSize.setHeight(cachedHeight);
+    }
+    
     //----------------------------------------------------------------------
     // Internals only
     //
@@ -62,7 +75,11 @@ public class Screen extends jogamp.newt.ScreenImpl {
 
     // called by GetScreenInfo() ..
     private void screenCreated(int width, int height) {
-        setScreenSize(width, height);
+        cachedWidth = width;
+        cachedHeight = height;
     }
+    
+    private static int cachedWidth = 0;
+    private static int cachedHeight = 0;
 }
 
diff --git a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java b/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java
index 6fc76a1..09e0e30 100644
--- a/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java
+++ b/src/newt/classes/jogamp/newt/driver/intel/gdl/Window.java
@@ -64,7 +64,7 @@ public class Window extends jogamp.newt.WindowImpl {
         synchronized(Window.class) {
             setWindowHandle(nextWindowHandle++); // just a marker
 
-            surfaceHandle = CreateSurface(aDevice.getHandle(), getScreen().getWidth(), getScreen().getHeight(), x, y, width, height);
+            surfaceHandle = CreateSurface(aDevice.getHandle(), getScreen().getWidth(), getScreen().getHeight(), getX(), getY(), getWidth(), getHeight());
             if (surfaceHandle == 0) {
                 throw new NativeWindowException("Error creating window");
             }
@@ -84,11 +84,6 @@ public class Window extends jogamp.newt.WindowImpl {
     protected boolean reconfigureWindowImpl(int x, int y, int width, int height, int flags) {
         Screen  screen = (Screen) getScreen();
 
-        x=(x>=0)?x:this.x;
-        y=(x>=0)?y:this.y;
-        width=(width>0)?width:this.width;
-        height=(height>0)?height:this.height;
-
         if(width>screen.getWidth()) {
             width=screen.getWidth();
         }
@@ -143,10 +138,8 @@ public class Window extends jogamp.newt.WindowImpl {
     private        native void SetBounds0(long surfaceHandle, int scrn_width, int scrn_height, int x, int y, int width, int height);
 
     private void updateBounds(int x, int y, int width, int height) {
-        this.x = x;
-        this.y = y;
-        this.width = width;
-        this.height = height;
+        definePosition(x, y);
+        defineSize(width, height);
     }
 
     private long   surfaceHandle;
diff --git a/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java b/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java
index bbfe101..ed8cb82 100644
--- a/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java
+++ b/src/newt/classes/jogamp/newt/driver/kd/KDDisplay.java
@@ -33,11 +33,12 @@
 
 package jogamp.newt.driver.kd;
 
+import com.jogamp.nativewindow.egl.*;
 import com.jogamp.newt.*;
+
 import jogamp.newt.*;
 import jogamp.opengl.egl.*;
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.egl.*;
 
 public class KDDisplay extends DisplayImpl {
 
@@ -59,11 +60,11 @@ public class KDDisplay extends DisplayImpl {
 
     protected void createNativeImpl() {
         // FIXME: map name to EGL_*_DISPLAY
-        long handle = EGL.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
+        long handle = EGLDisplayUtil.eglGetDisplay(EGL.EGL_DEFAULT_DISPLAY);
         if (handle == EGL.EGL_NO_DISPLAY) {
             throw new NativeWindowException("eglGetDisplay failed");
         }
-        if (!EGL.eglInitialize(handle, null, null)) {
+        if (!EGLDisplayUtil.eglInitialize(handle, null, null)) {
             throw new NativeWindowException("eglInitialize failed");
         }
         aDevice = new EGLGraphicsDevice(handle, AbstractGraphicsDevice.DEFAULT_CONNECTION, AbstractGraphicsDevice.DEFAULT_UNIT);
@@ -71,7 +72,7 @@ public class KDDisplay extends DisplayImpl {
 
     protected void closeNativeImpl() {
         if (aDevice.getHandle() != EGL.EGL_NO_DISPLAY) {
-            EGL.eglTerminate(aDevice.getHandle());
+            EGLDisplayUtil.eglTerminate(aDevice.getHandle());
         }
     }
 
diff --git a/src/newt/classes/jogamp/newt/driver/kd/KDScreen.java b/src/newt/classes/jogamp/newt/driver/kd/KDScreen.java
index a11b08b..6b6aecb 100644
--- a/src/newt/classes/jogamp/newt/driver/kd/KDScreen.java
+++ b/src/newt/classes/jogamp/newt/driver/kd/KDScreen.java
@@ -35,6 +35,8 @@ package jogamp.newt.driver.kd;
 
 import jogamp.newt.ScreenImpl;
 import javax.media.nativewindow.*;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
 
 public class KDScreen extends ScreenImpl {
     static {
@@ -50,8 +52,22 @@ public class KDScreen extends ScreenImpl {
 
     protected void closeNativeImpl() { }
 
-    // elevate access to this package ..
-    protected void setScreenSize(int w, int h) {
-        super.setScreenSize(w, h);
+    protected int validateScreenIndex(int idx) {
+        return 0; // only one screen available 
+    }       
+    
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(0);
+        virtualOrigin.setY(0);
+        virtualSize.setWidth(cachedWidth);
+        virtualSize.setHeight(cachedHeight);
     }
+    
+    protected void sizeChanged(int w, int h) {
+        cachedWidth = w;
+        cachedHeight = h;
+    }
+    
+    private static int cachedWidth = 0;
+    private static int cachedHeight = 0;    
 }
diff --git a/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java b/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java
index 0c720e5..8ae0b65 100644
--- a/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/kd/KDWindow.java
@@ -34,7 +34,6 @@
 package jogamp.newt.driver.kd;
 
 import jogamp.newt.*;
-import jogamp.newt.driver.intel.gdl.Display;
 import jogamp.opengl.egl.*;
 import javax.media.nativewindow.*;
 import javax.media.nativewindow.util.Insets;
@@ -102,8 +101,8 @@ public class KDWindow extends WindowImpl {
             }
             // int _x=(x>=0)?x:this.x;
             // int _y=(x>=0)?y:this.y;
-            width=(width>0)?width:this.width;
-            height=(height>0)?height:this.height;
+            width=(width>0)?width:getWidth();
+            height=(height>0)?height:getHeight();
             if(width>0 || height>0) {
                 setSize0(eglWindowHandle, width, height);
             }
@@ -145,8 +144,8 @@ public class KDWindow extends WindowImpl {
 
     @Override
     protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) {
-        if(fullscreen) {
-            ((KDScreen)getScreen()).setScreenSize(width, height);
+        if(isFullscreen()) {
+            ((KDScreen)getScreen()).sizeChanged(getWidth(), getHeight());
         }
         super.sizeChanged(defer, newWidth, newHeight, force);
     }
diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java b/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java
index 2ac98f2..18f8d95 100644
--- a/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java
+++ b/src/newt/classes/jogamp/newt/driver/macosx/MacDisplay.java
@@ -33,9 +33,13 @@
 
 package jogamp.newt.driver.macosx;
 
-import javax.media.nativewindow.*;
-import javax.media.nativewindow.macosx.*;
-import jogamp.newt.*;
+import javax.media.nativewindow.AbstractGraphicsDevice;
+import javax.media.nativewindow.NativeWindowException;
+
+import com.jogamp.nativewindow.macosx.MacOSXGraphicsDevice;
+
+import jogamp.newt.DisplayImpl;
+import jogamp.newt.NEWTJNILibLoader;
 
 public class MacDisplay extends DisplayImpl {
     static {
diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java b/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java
index 67a3f8e..b9c725f 100644
--- a/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java
+++ b/src/newt/classes/jogamp/newt/driver/macosx/MacScreen.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2011 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -33,13 +34,28 @@
 
 package jogamp.newt.driver.macosx;
 
-import com.jogamp.newt.*;
+import java.util.List;
+
+import javax.media.nativewindow.DefaultGraphicsScreen;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.DimensionImmutable;
+import javax.media.nativewindow.util.Point;
+
 import jogamp.newt.ScreenImpl;
-import javax.media.nativewindow.*;
+
+import com.jogamp.common.util.IntObjectHashMap;
+import com.jogamp.newt.ScreenMode;
+import com.jogamp.newt.util.ScreenModeUtil;
 
 public class MacScreen extends ScreenImpl {
+    
+    // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call)
+    private static IntObjectHashMap/*<int, DimensionImmutable>*/ scrnIdx2Dimension;
+    
     static {
         MacDisplay.initSingleton();
+        scrnIdx2Dimension = new IntObjectHashMap();
+        scrnIdx2Dimension.setKeyNotFoundValue(null);
     }
 
     public MacScreen() {
@@ -47,11 +63,81 @@ public class MacScreen extends ScreenImpl {
 
     protected void createNativeImpl() {
         aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx);
-        setScreenSize(getWidthImpl0(screen_idx), getHeightImpl0(screen_idx));
     }
 
     protected void closeNativeImpl() { }
 
     private static native int getWidthImpl0(int scrn_idx);
     private static native int getHeightImpl0(int scrn_idx);
+    
+    private int[] getScreenModeIdx(int idx) {
+        // caching native CGDisplayScreenSize() results, since it's ridiculous slow (~6 ms each call)
+        DimensionImmutable dim = (DimensionImmutable) scrnIdx2Dimension.get(screen_idx);
+        if(null == dim) {
+            int[] res = getScreenSizeMM0(screen_idx);
+            if(null == res || 0 == res.length) {
+                return null;
+            }
+            dim = new Dimension(res[0], res[1]);
+            scrnIdx2Dimension.put(screen_idx, dim);
+        }
+
+        int[] modeProps = getScreenMode0(screen_idx, idx, dim.getWidth(), dim.getHeight());
+        if (null == modeProps || 0 == modeProps.length) {
+            return null;
+        }
+        if(modeProps.length < ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL) {
+            throw new RuntimeException("properties array too short, should be >= "+ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL+", is "+modeProps.length);
+        }
+        return modeProps;
+    }
+
+    private int nativeModeIdx;
+    
+    protected int[] getScreenModeFirstImpl() {
+        nativeModeIdx = 0;
+        return getScreenModeNextImpl();
+    }
+
+    protected int[] getScreenModeNextImpl() {
+        int[] modeProps = getScreenModeIdx(nativeModeIdx);
+        if (null != modeProps && 0 < modeProps.length) {
+            nativeModeIdx++;
+            return modeProps;
+        }
+        return null;
+    }
+
+    protected ScreenMode getCurrentScreenModeImpl() {
+        int[] modeProps = getScreenModeIdx(-1);
+        if (null != modeProps && 0 < modeProps.length) {
+            return ScreenModeUtil.streamIn(modeProps, 0);
+        }
+        return null;
+    }
+    
+    protected boolean setCurrentScreenModeImpl(final ScreenMode screenMode) {
+        final List<ScreenMode> screenModes = this.getScreenModesOrig();
+        final int screenModeIdx = screenModes.indexOf(screenMode);
+        if(0>screenModeIdx) {
+            throw new RuntimeException("ScreenMode not element of ScreenMode list: "+screenMode);
+        }
+        final int nativeModeIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx);
+        return setScreenMode0(screen_idx, nativeModeIdx);
+    }
+    
+    protected int validateScreenIndex(int idx) {
+        return idx; 
+    }
+        
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(0);
+        virtualOrigin.setY(0);
+        virtualSize.setWidth(getWidthImpl0(screen_idx));
+        virtualSize.setHeight(getHeightImpl0(screen_idx));
+    }
+
+    private native int[] getScreenSizeMM0(int screen_idx);
+    private native int[] getScreenMode0(int screen_index, int mode_index, int widthMM, int heightMM);
+    private native boolean setScreenMode0(int screen_index, int mode_idx);
 }
diff --git a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
index 47c599a..b45c60e 100644
--- a/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/macosx/MacWindow.java
@@ -67,7 +67,7 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
             throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this);
         }
         setGraphicsConfiguration(cfg);
-        reconfigureWindowImpl(x, y, width, height, getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true));        
+        reconfigureWindowImpl(getX(), getY(), getWidth(), getHeight(), getReconfigureFlags(FLAG_CHANGE_VISIBILITY, true));        
         if (0 == getWindowHandle()) {
             throw new NativeWindowException("Error creating window");
         }
@@ -77,16 +77,19 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
     protected void closeNativeImpl() {
         try {
             if(DEBUG_IMPLEMENTATION) { System.err.println("MacWindow.CloseAction "+Thread.currentThread().getName()); }
-            if (getWindowHandle() != 0) {
-                close0(getWindowHandle());
+            final long handle = getWindowHandle(); 
+            setWindowHandle(0);
+            surfaceHandle = 0;
+            sscSurfaceHandle = 0;
+            isOffscreenInstance = false;            
+            if (0 != handle) {
+                close0(handle);
             }
         } catch (Throwable t) {
             if(DEBUG_IMPLEMENTATION) { 
                 Exception e = new Exception("Warning: closeNative failed - "+Thread.currentThread().getName(), t);
                 e.printStackTrace();
             }
-        } finally {
-            setWindowHandle(0);
         }
     }
     
@@ -244,8 +247,8 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
         
     @Override
     protected void sizeChanged(boolean defer, int newWidth, int newHeight, boolean force) {
-        if(width != newWidth || height != newHeight) {
-            final Point p0S = getTopLevelLocationOnScreen(x, y);            
+        if(getWidth() != newWidth || getHeight() != newHeight) {
+            final Point p0S = getTopLevelLocationOnScreen(getX(), getY());            
             setFrameTopLeftPoint0(getParentWindowHandle(), getWindowHandle(), p0S.getX(), p0S.getY());               
         }
         super.sizeChanged(defer, newWidth, newHeight, force);
@@ -268,7 +271,7 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
     @Override
     protected boolean setPointerVisibleImpl(final boolean pointerVisible) {
         if( !isOffscreenInstance ) {                
-            return setPointerVisible0(getWindowHandle(), pointerVisible);
+            return setPointerVisible0(getWindowHandle(), hasFocus(), pointerVisible);
         } // else may need offscreen solution ? FIXME
         return false;
     }
@@ -293,10 +296,13 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
         // Note that we send the key char for the key code on this
         // platform -- we do not get any useful key codes out of the system
         final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar);
-        if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.sendKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2));
-        // only deliver keyChar on key Typed events, harmonizing platform behavior
-        keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
-        super.sendKeyEvent(eventType, modifiers, keyCode2, keyChar);        
+        final boolean valid = validateKeyEvent(eventType, modifiers, keyCode);
+        if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.sendKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid);
+        if(valid) {
+            // only deliver keyChar on key Typed events, harmonizing platform behavior
+            keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
+            super.sendKeyEvent(eventType, modifiers, keyCode2, keyChar);
+        }
     }
     
     @Override
@@ -304,12 +310,37 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
         // Note that we send the key char for the key code on this
         // platform -- we do not get any useful key codes out of the system
         final int keyCode2 = MacKeyUtil.validateKeyCode(keyCode, keyChar);
-        if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.enqueueKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2));
-        // only deliver keyChar on key Typed events, harmonizing platform behavior
-        keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
-        super.enqueueKeyEvent(wait, eventType, modifiers, keyCode2, keyChar);
+        final boolean valid = validateKeyEvent(eventType, modifiers, keyCode);
+        if(DEBUG_IMPLEMENTATION) System.err.println("MacWindow.enqueueKeyEvent "+Thread.currentThread().getName()+" char: 0x"+Integer.toHexString(keyChar)+", code 0x"+Integer.toHexString(keyCode)+" -> 0x"+Integer.toHexString(keyCode2)+", valid "+valid);
+        if(valid) {
+            // only deliver keyChar on key Typed events, harmonizing platform behavior
+            keyChar = KeyEvent.EVENT_KEY_TYPED == eventType ? keyChar : (char)-1;
+            super.enqueueKeyEvent(wait, eventType, modifiers, keyCode2, keyChar);
+        }
     }
 
+    private int keyDownModifiers = 0;
+    private int keyDownCode = 0;
+    
+    private boolean validateKeyEvent(int eventType, int modifiers, int keyCode) {
+        switch(eventType) {
+            case KeyEvent.EVENT_KEY_PRESSED:
+                keyDownModifiers = modifiers;
+                keyDownCode = keyCode;
+                return true;
+            case KeyEvent.EVENT_KEY_RELEASED:
+                return keyDownModifiers == modifiers && keyDownCode == keyCode;
+            case KeyEvent.EVENT_KEY_TYPED:
+                final boolean matchKeyDown = keyDownModifiers == modifiers && keyDownCode == keyCode;
+                keyDownModifiers = 0;
+                keyDownCode = 0;
+                return matchKeyDown;
+            default:
+                throw new NativeWindowException("Unexpected key event type " + eventType);
+        }
+    }
+    
+
     //----------------------------------------------------------------------
     // Internals only
     //    
@@ -378,7 +409,7 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
     private native void setFrameTopLeftPoint0(long parentWindowHandle, long window, int x, int y);
     private native void setAlwaysOnTop0(long window, boolean atop);
     private static native Object getLocationOnScreen0(long windowHandle, int src_x, int src_y);
-    private static native boolean setPointerVisible0(long windowHandle, boolean visible);
+    private static native boolean setPointerVisible0(long windowHandle, boolean hasFocus, boolean visible);
     private static native boolean confinePointer0(long windowHandle, boolean confine);
     private static native void warpPointer0(long windowHandle, int x, int y);
     
@@ -394,8 +425,8 @@ public class MacWindow extends WindowImpl implements SurfaceChangeable, DriverCl
     private static final int NSBackingStoreNonretained  = 1;
     private static final int NSBackingStoreBuffered     = 2;
 
-    private volatile long surfaceHandle;
-    private long sscSurfaceHandle;
-    private boolean isOffscreenInstance;
+    private volatile long surfaceHandle = 0;
+    private long sscSurfaceHandle = 0;
+    private boolean isOffscreenInstance = false;
     
 }
diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java
index 524d9fc..225b115 100644
--- a/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java
+++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsDisplay.java
@@ -40,7 +40,8 @@ import jogamp.newt.DisplayImpl;
 import jogamp.newt.NEWTJNILibLoader;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.NativeWindowException;
-import javax.media.nativewindow.windows.WindowsGraphicsDevice;
+
+import com.jogamp.nativewindow.windows.WindowsGraphicsDevice;
 
 public class WindowsDisplay extends DisplayImpl {
 
diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java
index 6566d72..f8bce9d 100644
--- a/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java
+++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsScreen.java
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2010 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -32,12 +33,15 @@
  */
 package jogamp.newt.driver.windows;
 
+import javax.media.nativewindow.DefaultGraphicsScreen;
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
+
 import jogamp.newt.ScreenImpl;
+
 import com.jogamp.newt.ScreenMode;
 import com.jogamp.newt.util.ScreenModeUtil;
 
-import javax.media.nativewindow.*;
-
 public class WindowsScreen extends ScreenImpl {
 
     static {
@@ -49,9 +53,8 @@ public class WindowsScreen extends ScreenImpl {
 
     protected void createNativeImpl() {
         aScreen = new DefaultGraphicsScreen(getDisplay().getGraphicsDevice(), screen_idx);
-        setScreenSize(getWidthImpl0(screen_idx), getHeightImpl0(screen_idx));
     }
-
+    
     protected void closeNativeImpl() {
     }
 
@@ -99,9 +102,21 @@ public class WindowsScreen extends ScreenImpl {
                               sm.getRotation());
     }
 
+    protected int validateScreenIndex(int idx) {
+        return 0; // big-desktop, only one screen available 
+    }
+        
+    protected void getVirtualScreenOriginAndSize(Point virtualOrigin, Dimension virtualSize) {
+        virtualOrigin.setX(getOriginX0(screen_idx));
+        virtualOrigin.setY(getOriginY0(screen_idx));
+        virtualSize.setWidth(getWidthImpl0(screen_idx));
+        virtualSize.setHeight(getHeightImpl0(screen_idx));
+    }
+    
     // Native calls
+    private native int getOriginX0(int screen_idx);
+    private native int getOriginY0(int screen_idx);
     private native int getWidthImpl0(int scrn_idx);
-
     private native int getHeightImpl0(int scrn_idx);
 
     private native int[] getScreenMode0(int screen_index, int mode_index);
diff --git a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java
index 23206c2..a30aa13 100644
--- a/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java
+++ b/src/newt/classes/jogamp/newt/driver/windows/WindowsWindow.java
@@ -53,6 +53,7 @@ public class WindowsWindow extends WindowImpl {
 
     private long hmon;
     private long hdc;
+    private long hdc_old;
     private long windowHandleClose;
 
     static {
@@ -69,7 +70,19 @@ public class WindowsWindow extends WindowImpl {
         }
         hdc = GDI.GetDC(getWindowHandle());
         hmon = MonitorFromWindow0(getWindowHandle());
-        return ( 0 != hdc ) ? LOCK_SUCCESS : LOCK_SURFACE_NOT_READY;
+        
+        // return ( 0 == hdc ) ? LOCK_SURFACE_NOT_READY : ( hdc_old != hdc ) ? LOCK_SURFACE_CHANGED : LOCK_SUCCESS ;
+        if( 0 == hdc ) { 
+            return LOCK_SURFACE_NOT_READY;
+        }
+        if( hdc_old == hdc ) {
+            return LOCK_SUCCESS;
+        }
+        if(DEBUG_IMPLEMENTATION) {            
+            System.err.println("WindowsWindow: surface change "+toHexString(hdc_old)+" -> "+toHexString(hdc));
+            // Thread.dumpStack();
+        }
+        return LOCK_SURFACE_CHANGED;        
     }
 
     @Override
@@ -78,6 +91,7 @@ public class WindowsWindow extends WindowImpl {
             throw new InternalError("surface not acquired");
         }
         GDI.ReleaseDC(getWindowHandle(), hdc);
+        hdc_old = hdc;
         hdc=0;
     }
 
@@ -92,9 +106,9 @@ public class WindowsWindow extends WindowImpl {
             long _hmon = MonitorFromWindow0(getWindowHandle());
             if (hmon != _hmon) {
                 if(DEBUG_IMPLEMENTATION) {
-                    Exception e = new Exception("Info: Window Device Changed "+Thread.currentThread().getName()+
-                                                ", HMON "+toHexString(hmon)+" -> "+toHexString(_hmon));
-                    e.printStackTrace();
+                    System.err.println("Info: Window Device Changed "+Thread.currentThread().getName()+
+                                        ", HMON "+toHexString(hmon)+" -> "+toHexString(_hmon));
+                    // Thread.dumpStack();
                 }
                 hmon = _hmon;
                 return true;
@@ -115,7 +129,7 @@ public class WindowsWindow extends WindowImpl {
         final int flags = getReconfigureFlags(0, true) & 
                           ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ;
         setWindowHandle(CreateWindow0(display.getHInstance(), display.getWindowClassName(), display.getWindowClassName(),
-                                      getParentWindowHandle(), x, y, width, height, flags)); 
+                                      getParentWindowHandle(), getX(), getY(), getWidth(), getHeight(), autoPosition(), flags)); 
         if (getWindowHandle() == 0) {
             throw new NativeWindowException("Error creating window");
         }
@@ -149,6 +163,7 @@ public class WindowsWindow extends WindowImpl {
                 }
             }
             hdc = 0;
+            hdc_old = 0;
         }
         if(windowHandleClose != 0) {
             try {
@@ -174,12 +189,8 @@ public class WindowsWindow extends WindowImpl {
             final InsetsImmutable i = getInsets();
             
             // client position -> top-level window position
-            if(0<=x && 0<=y) {
-                x -= i.getLeftWidth() ;
-                y -= i.getTopHeight() ;
-                if( 0 > x ) { x = 0; }
-                if( 0 > y ) { y = 0; }
-            }
+            x -= i.getLeftWidth() ;
+            y -= i.getTopHeight() ;
             
             if(0<width && 0<height) {
                 // client size -> top-level window size
@@ -224,7 +235,7 @@ public class WindowsWindow extends WindowImpl {
             public void run() {
                 final Point p0 = getLocationOnScreenImpl(0, 0);
                 res[0] = Boolean.valueOf(confinePointer0(getWindowHandle(), confine, 
-                        p0.getX(), p0.getY(), p0.getX()+width, p0.getY()+height));
+                        p0.getX(), p0.getY(), p0.getX()+getWidth(), p0.getY()+getHeight()));
             }
         });
         return res[0].booleanValue();
@@ -287,7 +298,7 @@ public class WindowsWindow extends WindowImpl {
 
     private native long CreateWindow0(long hInstance, String wndClassName, String wndName,
                                       long parentWindowHandle,
-                                      int x, int y, int width, int height, int flags);
+                                      int x, int y, int width, int height, boolean autoPosition, int flags);
     private native long MonitorFromWindow0(long windowHandle);
     private native void reconfigureWindow0(long parentWindowHandle, long windowHandle,
                                            int x, int y, int width, int height, int flags);
diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java b/src/newt/classes/jogamp/newt/driver/x11/X11Display.java
index b3bc6e4..9464b97 100644
--- a/src/newt/classes/jogamp/newt/driver/x11/X11Display.java
+++ b/src/newt/classes/jogamp/newt/driver/x11/X11Display.java
@@ -37,7 +37,8 @@ package jogamp.newt.driver.x11;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.NativeWindowException;
 import javax.media.nativewindow.NativeWindowFactory;
-import javax.media.nativewindow.x11.X11GraphicsDevice;
+
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
 
 import jogamp.nativewindow.x11.X11Util;
 import jogamp.newt.DisplayImpl;
diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java b/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java
index 463c62e..93db854 100644
--- a/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java
+++ b/src/newt/classes/jogamp/newt/driver/x11/X11Screen.java
@@ -33,16 +33,20 @@
  */
 package jogamp.newt.driver.x11;
 
+import java.util.List;
+
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
+
 import jogamp.nativewindow.x11.X11Util;
 import jogamp.newt.DisplayImpl;
-import jogamp.newt.ScreenImpl;
 import jogamp.newt.DisplayImpl.DisplayRunnable;
+import jogamp.newt.ScreenImpl;
 
+import com.jogamp.nativewindow.x11.X11GraphicsDevice;
+import com.jogamp.nativewindow.x11.X11GraphicsScreen;
 import com.jogamp.newt.ScreenMode;
 import com.jogamp.newt.util.ScreenModeUtil;
-import java.util.List;
-
-import javax.media.nativewindow.x11.*;
 
 public class X11Screen extends ScreenImpl {
 
@@ -57,11 +61,7 @@ public class X11Screen extends ScreenImpl {
         // validate screen index
         Long handle = display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable<Long>() {
             public Long run(long dpy) {        
-                long handle = GetScreen0(dpy, screen_idx);
-                if(0 != handle) {
-                    setScreenSize(getWidth0(dpy, screen_idx), getHeight0(dpy, screen_idx));
-                }
-                return new Long(handle);
+                return new Long(GetScreen0(dpy, screen_idx));
             } } );        
         if (handle.longValue() == 0) {
             throw new RuntimeException("Error creating screen: " + screen_idx);
@@ -125,10 +125,12 @@ public class X11Screen extends ScreenImpl {
                 if(0>=res[0] || 0>=res[1]) {
                     throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+nres_index+"/"+nres_number);
                 }
-                int bpp = 32; // FIXME
                 int rate = nrates[nrate_index];
                 if(0>=rate) {
-                    throw new InternalError("invalid rate: "+rate+" at index "+nrate_index+"/"+nrates.length);
+                    rate = default_sm_rate;
+                    if(DEBUG) {
+                        System.err.println("Invalid rate: "+rate+" at index "+nrate_index+"/"+nrates.length+", using default: "+default_sm_rate);
+                    }
                 }
                 int rotation = nrotations[nrotation_index];
         
@@ -138,7 +140,7 @@ public class X11Screen extends ScreenImpl {
                 props[i++] = 0; // set later for verification of iterator
                 props[i++] = res[0]; // width
                 props[i++] = res[1]; // height
-                props[i++] = bpp;    // bpp
+                props[i++] = default_sm_bpp; // FIXME
                 props[i++] = res[2]; // widthmm
                 props[i++] = res[3]; // heightmm
                 props[i++] = rate;   // rate
@@ -176,38 +178,49 @@ public class X11Screen extends ScreenImpl {
     protected ScreenMode getCurrentScreenModeImpl() {
         return runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable<ScreenMode>() {
             public ScreenMode run(long dpy) {
-                int resNumber = getNumScreenModeResolutions0(dpy, screen_idx);
-                if(0==resNumber) {
-                    return null;
-                }
-                int resIdx = getCurrentScreenResolutionIndex0(dpy, screen_idx);
-                if(0>resIdx) {
-                    return null;
-                }
-                if(resIdx>=resNumber) {
-                    throw new RuntimeException("Invalid resolution index: ! "+resIdx+" < "+resNumber);
-                }
-                int[] res = getScreenModeResolution0(dpy, screen_idx, resIdx);
-                if(null==res || 0==res.length) {
+                long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx);
+                if(0 == screenConfigHandle) {
                     return null;
                 }
-                if(0>=res[0] || 0>=res[1]) {
-                    throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+resIdx+"/"+resNumber);
-                }
-                int rate = getCurrentScreenRate0(dpy, screen_idx);
-                if(0>rate) {
-                    return null;
-                }
-                int rot = getCurrentScreenRotation0(dpy, screen_idx);
-                if(0>rot) {
-                    return null;
+                int[] res;
+                int rate, rot;
+                try {                
+                    int resNumber = getNumScreenModeResolutions0(dpy, screen_idx);
+                    if(0==resNumber) {
+                        return null;
+                    }
+    
+                    int resIdx = getCurrentScreenResolutionIndex0(screenConfigHandle);
+                    if(0>resIdx) {
+                        return null;
+                    }
+                    if(resIdx>=resNumber) {
+                        throw new RuntimeException("Invalid resolution index: ! "+resIdx+" < "+resNumber);
+                    }
+                    res = getScreenModeResolution0(dpy, screen_idx, resIdx);
+                    if(null==res || 0==res.length) {
+                        return null;
+                    }
+                    if(0>=res[0] || 0>=res[1]) {
+                        throw new InternalError("invalid resolution: "+res[0]+"x"+res[1]+" for res idx "+resIdx+"/"+resNumber);
+                    }
+                    rate = getCurrentScreenRate0(screenConfigHandle);
+                    if(0>rate) {
+                        return null;
+                    }
+                    rot = getCurrentScreenRotation0(screenConfigHandle);
+                    if(0>rot) {
+                        return null;
+                    }
+                } finally {
+                     freeScreenConfiguration0(screenConfigHandle);
                 }
                 int[] props = new int[ScreenModeUtil.NUM_SCREEN_MODE_PROPERTIES_ALL];
                 int i = 0;
                 props[i++] = 0; // set later for verification of iterator
                 props[i++] = res[0]; // width
                 props[i++] = res[1]; // height
-                props[i++] = 32;     // FIXME: bpp
+                props[i++] = default_sm_bpp; // FIXME
                 props[i++] = res[2]; // widthmm
                 props[i++] = res[3]; // heightmm
                 props[i++] = rate;   // rate
@@ -227,21 +240,30 @@ public class X11Screen extends ScreenImpl {
         boolean done = runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable<Boolean>() {
             public Boolean run(long dpy) {
                 boolean done = false;
-                int resNumber = getNumScreenModeResolutions0(dpy, screen_idx);
-                int resIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx);
-                if(0>resIdx || resIdx>=resNumber) {
-                    throw new RuntimeException("Invalid resolution index: ! 0 < "+resIdx+" < "+resNumber+", screenMode["+screenModeIdx+"] "+screenMode);
+                long screenConfigHandle = getScreenConfiguration0(dpy, screen_idx);
+                if(0 == screenConfigHandle) {
+                    return Boolean.valueOf(done);
                 }
-        
-                final int f = screenMode.getMonitorMode().getRefreshRate();
-                final int r = screenMode.getRotation();
-                if( setCurrentScreenModeStart0(dpy, screen_idx, resIdx, f, r) ) {
-                    while(!done && System.currentTimeMillis()-t0 < SCREEN_MODE_CHANGE_TIMEOUT) {
-                        done = setCurrentScreenModePollEnd0(dpy, screen_idx, resIdx, f, r);
-                        if(!done) {
-                            try { Thread.sleep(10); } catch (InterruptedException e) { }
+                try {
+                    int resNumber = getNumScreenModeResolutions0(dpy, screen_idx);
+                    int resIdx = getScreenModesIdx2NativeIdx().get(screenModeIdx);
+                    if(0>resIdx || resIdx>=resNumber) {
+                        throw new RuntimeException("Invalid resolution index: ! 0 < "+resIdx+" < "+resNumber+", screenMode["+screenModeIdx+"] "+screenMode);
+                    }
+            
+                    final int f = screenMode.getMonitorMode().getRefreshRate();
+                    final int r = screenMode.getRotation();
+    
+                    if( setCurrentScreenModeStart0(dpy, screen_idx, screenConfigHandle, resIdx, f, r) ) {
+                        while(!done && System.currentTimeMillis()-t0 < SCREEN_MODE_CHANGE_TIMEOUT) {
+                            done = setCurrentScreenModePollEnd0(dpy, screen_idx, resIdx, f, r);
+                            if(!done) {
+                                try { Thread.sleep(10); } catch (InterruptedException e) { }
+                            }
                         }
                     }
+                } finally {
+                     freeScreenConfiguration0(screenConfigHandle);
                 }
                 return Boolean.valueOf(done);
             }            
@@ -254,6 +276,32 @@ public class X11Screen extends ScreenImpl {
         return done;
     }
 
+    private class XineramaEnabledQuery implements DisplayImpl.DisplayRunnable<Boolean> {
+        public Boolean run(long dpy) {        
+            return new Boolean(X11Util.XineramaIsEnabled(dpy)); 
+        }        
+    }
+    private XineramaEnabledQuery xineramaEnabledQuery = new XineramaEnabledQuery();
+    
+    protected int validateScreenIndex(final int idx) {
+        if(getDisplay().isNativeValid()) {
+            return runWithLockedDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx;
+        } else {
+            return runWithTempDisplayHandle( xineramaEnabledQuery ).booleanValue() ? 0 : idx;
+        }
+    }
+        
+    protected void getVirtualScreenOriginAndSize(final Point virtualOrigin, final Dimension virtualSize) {
+        display.runWithLockedDisplayHandle( new DisplayImpl.DisplayRunnable<Object>() {
+            public Object run(long dpy) {
+                virtualOrigin.setX(0);
+                virtualOrigin.setY(0);
+                virtualSize.setWidth(getWidth0(dpy, screen_idx));
+                virtualSize.setHeight(getHeight0(dpy, screen_idx));
+                return null;
+            } } );        
+    }    
+    
     //----------------------------------------------------------------------
     // Internals only
     //    
@@ -296,11 +344,14 @@ public class X11Screen extends ScreenImpl {
 
     private static native int[] getScreenModeRates0(long display, int screen_index, int mode_index);
 
-    private static native int getCurrentScreenResolutionIndex0(long display, int screen_index);
-    private static native int getCurrentScreenRate0(long display, int screen_index);
-    private static native int getCurrentScreenRotation0(long display, int screen_index);
+    private static native long getScreenConfiguration0(long display, int screen_index);
+    private static native void freeScreenConfiguration0(long screenConfiguration);
+    
+    private static native int getCurrentScreenResolutionIndex0(long screenConfiguration);
+    private static native int getCurrentScreenRate0(long screenConfiguration);
+    private static native int getCurrentScreenRotation0(long screenConfiguration);
 
     /** needs own Display connection for XRANDR event handling */
-    private static native boolean setCurrentScreenModeStart0(long display, int screen_index, int mode_index, int freq, int rot);
+    private static native boolean setCurrentScreenModeStart0(long display, int screen_index, long screenConfiguration, int mode_index, int freq, int rot);
     private static native boolean setCurrentScreenModePollEnd0(long display, int screen_index, int mode_index, int freq, int rot);
 }
diff --git a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java
index bfaf53f..143b94a 100644
--- a/src/newt/classes/jogamp/newt/driver/x11/X11Window.java
+++ b/src/newt/classes/jogamp/newt/driver/x11/X11Window.java
@@ -39,7 +39,7 @@ import jogamp.newt.DisplayImpl;
 import jogamp.newt.DisplayImpl.DisplayRunnable;
 import jogamp.newt.WindowImpl;
 import javax.media.nativewindow.*;
-import javax.media.nativewindow.x11.*;
+import javax.media.nativewindow.VisualIDHolder.VIDType;
 import javax.media.nativewindow.util.Insets;
 import javax.media.nativewindow.util.InsetsImmutable;
 import javax.media.nativewindow.util.Point;
@@ -64,7 +64,7 @@ public class X11Window extends WindowImpl {
         final X11Screen screen = (X11Screen) getScreen();
         final X11Display display = (X11Display) screen.getDisplay();
         final GraphicsConfigurationFactory factory = GraphicsConfigurationFactory.getFactory(display.getGraphicsDevice());
-        final X11GraphicsConfiguration cfg = (X11GraphicsConfiguration) factory.chooseGraphicsConfiguration(
+        final AbstractGraphicsConfiguration cfg = factory.chooseGraphicsConfiguration(
                 capsRequested, capsRequested, capabilitiesChooser, screen.getGraphicsScreen());
         if(DEBUG_IMPLEMENTATION) {
             System.err.println("X11Window.createNativeImpl() factory: "+factory+", chosen config: "+cfg);
@@ -72,14 +72,17 @@ public class X11Window extends WindowImpl {
         if (null == cfg) {
             throw new NativeWindowException("Error choosing GraphicsConfiguration creating window: "+this);
         }
+        final int visualID = cfg.getVisualID(VIDType.NATIVE);
+        if(VisualIDHolder.VID_UNDEFINED == visualID) {
+            throw new NativeWindowException("Chosen Configuration w/o native visual ID: "+cfg);
+        }
         setGraphicsConfiguration(cfg);
-        final long visualID = cfg.getVisualID();
         final int flags = getReconfigureFlags(0, true) & 
                           ( FLAG_IS_ALWAYSONTOP | FLAG_IS_UNDECORATED ) ;        
         setWindowHandle(CreateWindow0(getParentWindowHandle(),
                                display.getEDTHandle(), screen.getIndex(), visualID, 
                                display.getJavaObjectAtom(), display.getWindowDeleteAtom(), 
-                               x, y, width, height, flags));
+                               getX(), getY(), getWidth(), getHeight(), autoPosition(), flags));
         windowHandleClose = getWindowHandle();
         if (0 == windowHandleClose) {
             throw new NativeWindowException("Error creating window");
@@ -108,16 +111,16 @@ public class X11Window extends WindowImpl {
             System.err.println("X11Window reconfig: "+x+"/"+y+" "+width+"x"+height+", "+
                                getReconfigureFlagsAsString(null, flags));
         }
-        if(0 == ( FLAG_IS_UNDECORATED & flags) && 0<=x && 0<=y) {
+        if(0 == ( FLAG_IS_UNDECORATED & flags)) {
             final InsetsImmutable i = getInsets();         
             
             // client position -> top-level window position
             x -= i.getLeftWidth() ;
             y -= i.getTopHeight() ;
-            if( 0 > x ) { x = 0; }
-            if( 0 > y ) { y = 0; }            
-        }        
-        reconfigureWindow0( getDisplayEDTHandle(), getScreenIndex(), getParentWindowHandle(), getWindowHandle(),
+        }
+        final X11Display display = (X11Display) getScreen().getDisplay();
+        reconfigureWindow0( getDisplayEDTHandle(), getScreenIndex(), 
+                            getParentWindowHandle(), getWindowHandle(), display.getWindowDeleteAtom(),
                             x, y, width, height, flags);
 
         return true;
@@ -238,11 +241,11 @@ public class X11Window extends WindowImpl {
     protected static native boolean initIDs0();
     
     private native long CreateWindow0(long parentWindowHandle, long display, int screen_index, 
-                                            long visualID, long javaObjectAtom, long windowDeleteAtom, 
-                                            int x, int y, int width, int height, int flags); 
+                                      int visualID, long javaObjectAtom, long windowDeleteAtom, 
+                                      int x, int y, int width, int height, boolean autoPosition, int flags); 
     private native void CloseWindow0(long display, long windowHandle, long javaObjectAtom, long windowDeleteAtom);
     private native void reconfigureWindow0(long display, int screen_index, long parentWindowHandle, long windowHandle,
-                                           int x, int y, int width, int height, int flags);    
+                                           long windowDeleteAtom, int x, int y, int width, int height, int flags);    
     private native void requestFocus0(long display, long windowHandle, boolean force);
     
     private static native void setTitle0(long display, long windowHandle, String title);
diff --git a/src/newt/native/KDWindow.c b/src/newt/native/KDWindow.c
index 5f1affe..dc99913 100644
--- a/src/newt/native/KDWindow.c
+++ b/src/newt/native/KDWindow.c
@@ -114,8 +114,10 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_kd_KDDisplay_DispatchMessages
                 break;
             case KD_EVENT_WINDOW_CLOSE:
                 {
-                    DBG_PRINT( "event window close : src: %p\n", userData);
-                    (*env)->CallVoidMethod(env, javaWindow, windowDestroyNotifyID);
+                    jboolean closed;
+                    DBG_PRINT( "event window close : src: %p .. \n", userData);
+                    closed = (*env)->CallBooleanMethod(env, javaWindow, windowDestroyNotifyID, JNI_FALSE);
+                    DBG_PRINT( "event window close : src: %p, closed %d\n", userData, (int)closed);
                 }
                 break;
             case KD_EVENT_WINDOWPROPERTY_CHANGE:
@@ -189,7 +191,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_kd_KDWindow_initIDs
     windowCreatedID = (*env)->GetMethodID(env, clazz, "windowCreated", "(J)V");
     sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V");
     visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V");
-    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify",    "()V");
+    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z");
     sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V");
     sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V");
     if (windowCreatedID == NULL ||
@@ -256,7 +258,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_kd_KDWindow_RealizeWindow
     jint res = kdRealizeWindow(w, &nativeWindow);
     if(res) {
         fprintf(stderr, "[RealizeWindow] failed: 0x%X, 0x%X\n", res, kdGetError());
-        nativeWindow = NULL;
+        nativeWindow = 0;
     }
     DBG_PRINT( "[RealizeWindow] ok: %p\n", nativeWindow);
     return (jlong) (intptr_t) nativeWindow;
diff --git a/src/newt/native/KeyEvent.h b/src/newt/native/KeyEvent.h
index 1ead0f5..0f7b160 100644
--- a/src/newt/native/KeyEvent.h
+++ b/src/newt/native/KeyEvent.h
@@ -1,3 +1,30 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
 
 #ifndef _KEY_EVENT_H_
 #define _KEY_EVENT_H_
diff --git a/src/newt/native/MacWindow.m b/src/newt/native/MacWindow.m
index e39ff03..01cbd80 100644
--- a/src/newt/native/MacWindow.m
+++ b/src/newt/native/MacWindow.m
@@ -38,11 +38,16 @@
 
 #import "MouseEvent.h"
 #import "KeyEvent.h"
+#import "ScreenMode.h"
 
 #import <ApplicationServices/ApplicationServices.h>
 
 #import <stdio.h>
 
+#ifdef DBG_PERF
+    #include "timespec.h"
+#endif
+
 static const char * const ClazzNamePoint = "javax/media/nativewindow/util/Point";
 static const char * const ClazzAnyCstrName = "<init>";
 static const char * const ClazzNamePointCstrSignature = "(II)V";
@@ -237,6 +242,13 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacDisplay_stopNSApplicati
     [pool release];
 }
 
+static NSScreen * NewtScreen_getNSScreenByIndex(int screen_idx) {
+    NSArray *screens = [NSScreen screens];
+    if(screen_idx<0) screen_idx=0;
+    if(screen_idx>=[screens count]) screen_idx=0;
+    return (NSScreen *) [screens objectAtIndex: screen_idx];
+}
+
 /*
  * Class:     jogamp_newt_driver_macosx_MacScreen
  * Method:    getWidthImpl
@@ -247,10 +259,7 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getWidthImpl0
 {
     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
 
-    NSArray *screens = [NSScreen screens];
-    if(screen_idx<0) screen_idx=0;
-    if(screen_idx>=[screens count]) screen_idx=0;
-    NSScreen *screen = (NSScreen *) [screens objectAtIndex: screen_idx];
+    NSScreen *screen = NewtScreen_getNSScreenByIndex((int)screen_idx);
     NSRect rect = [screen frame];
 
     [pool release];
@@ -268,10 +277,7 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getHeightImpl0
 {
     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
 
-    NSArray *screens = [NSScreen screens];
-    if(screen_idx<0) screen_idx=0;
-    if(screen_idx>=[screens count]) screen_idx=0;
-    NSScreen *screen = (NSScreen *) [screens objectAtIndex: screen_idx];
+    NSScreen *screen = NewtScreen_getNSScreenByIndex((int)screen_idx);
     NSRect rect = [screen frame];
 
     [pool release];
@@ -279,6 +285,224 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getHeightImpl0
     return (jint) (rect.size.height);
 }
 
+static CGDirectDisplayID NewtScreen_getCGDirectDisplayIDByNSScreen(NSScreen *screen) {
+    // Mind: typedef uint32_t CGDirectDisplayID; - however, we assume it's 64bit on 64bit ?!
+    NSDictionary * dict = [screen deviceDescription];
+    NSNumber * val = (NSNumber *) [dict objectForKey: @"NSScreenNumber"];
+    // [NSNumber integerValue] returns NSInteger which is 32 or 64 bit native size
+    return (CGDirectDisplayID) [val integerValue];
+}
+
+/**
+ * Only in >= 10.6:
+ *   CGDisplayModeGetWidth(mode)
+ *   CGDisplayModeGetRefreshRate(mode)
+ *   CGDisplayModeGetHeight(mode)
+ */
+static long GetDictionaryLong(CFDictionaryRef theDict, const void* key) 
+{
+    long value = 0;
+    CFNumberRef numRef;
+    numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); 
+    if (numRef != NULL)
+        CFNumberGetValue(numRef, kCFNumberLongType, &value);    
+    return value;
+}
+#define CGDDGetModeWidth(mode) GetDictionaryLong((mode), kCGDisplayWidth)
+#define CGDDGetModeHeight(mode) GetDictionaryLong((mode), kCGDisplayHeight)
+#define CGDDGetModeRefreshRate(mode) GetDictionaryLong((mode), kCGDisplayRefreshRate)
+#define CGDDGetModeBitsPerPixel(mode) GetDictionaryLong((mode), kCGDisplayBitsPerPixel)
+
+// Duplicate each Mode by all possible rotations (4):
+// For each real-mode: [mode, 0], [mode, 90], [mode, 180], [mode, 270]
+#define ROTMODES_PER_REALMODE 4
+
+/*
+ * Class:     jogamp_newt_driver_macosx_MacScreen
+ * Method:    getScreenSizeMM0
+ * Signature: (I)[I
+ */
+JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenSizeMM0
+  (JNIEnv *env, jobject obj, jint scrn_idx)
+{
+    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+
+#ifdef DBG_PERF
+    struct timespec t0, t1, td;
+    long td_ms;
+    timespec_now(&t0);
+#endif
+
+    NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx);
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "MacScreen_getScreenSizeMM0.1: %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen);
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "MacScreen_getScreenSizeMM0.2: %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    CGSize screenDim = CGDisplayScreenSize(display);
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "MacScreen_getScreenSizeMM0.3: %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    jint prop[ 2 ];
+    prop[0] = (jint) screenDim.width;
+    prop[1] = (jint) screenDim.height;
+
+    jintArray properties = (*env)->NewIntArray(env, 2);
+    if (properties == NULL) {
+        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size 2");
+    }
+    (*env)->SetIntArrayRegion(env, properties, 0, 2, prop);
+    
+    [pool release];
+
+    return properties;
+}
+
+/*
+ * Class:     jogamp_newt_driver_macosx_MacScreen
+ * Method:    getScreenMode0
+ * Signature: (IIII)[I
+ */
+JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_macosx_MacScreen_getScreenMode0
+  (JNIEnv *env, jobject obj, jint scrn_idx, jint mode_idx, jint widthMM, jint heightMM)
+{
+    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+
+    int prop_num = NUM_SCREEN_MODE_PROPERTIES_ALL;
+    NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx);
+    CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen);
+
+    CFArrayRef availableModes = CGDisplayAvailableModes(display);
+    CFIndex numberOfAvailableModes = CFArrayGetCount(availableModes);
+    CFIndex numberOfAvailableModesRots = ROTMODES_PER_REALMODE * numberOfAvailableModes; 
+    CFDictionaryRef mode = NULL;
+    int currentCCWRot = (int)CGDisplayRotation(display);
+    jint ccwRot = 0;
+
+#ifdef VERBOSE_ON
+    if(0 >= mode_idx) {
+        // only for current mode (-1) and first mode (scanning)
+        DBG_PRINT( "getScreenMode0: scrn %d (%p, %p), mode %d, avail: %d/%d, current rot %d ccw\n",  
+            (int)scrn_idx, screen, (void*)(intptr_t)display, (int)mode_idx, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots, currentCCWRot);
+    }
+#endif
+
+    if(numberOfAvailableModesRots<=mode_idx) {
+        // n/a - end of modes
+        DBG_PRINT( "getScreenMode0: end of modes: mode %d, avail: %d/%d\n",
+            (int)mode_idx, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots);
+        [pool release];
+        return (*env)->NewIntArray(env, 0);
+    } else if(-1 < mode_idx) {
+        // only at initialization time, where index >= 0
+        prop_num++; // add 1st extra prop, mode_idx
+        mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, mode_idx / ROTMODES_PER_REALMODE);
+        ccwRot = mode_idx % ROTMODES_PER_REALMODE * 90;
+    } else {
+        // current mode
+        mode = CGDisplayCurrentMode(display);
+        ccwRot = currentCCWRot;
+    }
+    // mode = CGDisplayModeRetain(mode); // 10.6 on CGDisplayModeRef
+
+    int mWidth = CGDDGetModeWidth(mode);
+    int mHeight = CGDDGetModeHeight(mode);
+
+    // swap width and height, since OSX reflects rotated dimension, we don't
+    if ( 90 == currentCCWRot || 270 == currentCCWRot ) {
+        int tempWidth = mWidth;
+        mWidth = mHeight;
+        mHeight = tempWidth;
+    }
+
+    jint prop[ prop_num ];
+    int propIndex = 0;
+    int propIndexRes = 0;
+
+    if( -1 < mode_idx ) {
+        prop[propIndex++] = mode_idx;
+    }
+    prop[propIndex++] = 0; // set later for verification of iterator
+    propIndexRes = propIndex;
+    prop[propIndex++] = mWidth;
+    prop[propIndex++] = mHeight;
+    prop[propIndex++] = CGDDGetModeBitsPerPixel(mode);
+    prop[propIndex++] = widthMM;
+    prop[propIndex++] = heightMM;
+    prop[propIndex++] = CGDDGetModeRefreshRate(mode);
+    prop[propIndex++] = ccwRot;
+    prop[propIndex - NUM_SCREEN_MODE_PROPERTIES_ALL] = ( -1 < mode_idx ) ? propIndex-1 : propIndex ; // count == NUM_SCREEN_MODE_PROPERTIES_ALL
+
+    DBG_PRINT( "getScreenMode0: Mode %d/%d (%d): %dx%d, %d bpp, %dx%d mm, %d Hz, rot %d ccw\n",
+        (int)mode_idx, (int)numberOfAvailableModesRots, (int)numberOfAvailableModes, 
+        (int)prop[propIndexRes+0], (int)prop[propIndexRes+1], (int)prop[propIndexRes+2], 
+        (int)prop[propIndexRes+3], (int)prop[propIndexRes+4], (int)prop[propIndexRes+5], (int)prop[propIndexRes+6]);
+
+    jintArray properties = (*env)->NewIntArray(env, prop_num);
+    if (properties == NULL) {
+        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", prop_num);
+    }
+    (*env)->SetIntArrayRegion(env, properties, 0, prop_num, prop);
+    
+    // CGDisplayModeRelease(mode); // 10.6 on CGDisplayModeRef
+    [pool release];
+
+    return properties;
+}
+
+/*
+ * Class:     jogamp_newt_driver_macosx_MacScreen
+ * Method:    setScreenMode0
+ * Signature: (II)Z
+ */
+JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacScreen_setScreenMode0
+  (JNIEnv *env, jobject object, jint scrn_idx, jint mode_idx)
+{
+    jboolean res = JNI_TRUE;
+    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
+
+    NSScreen *screen = NewtScreen_getNSScreenByIndex((int)scrn_idx);
+    CGDirectDisplayID display = NewtScreen_getCGDirectDisplayIDByNSScreen(screen);
+
+    CFArrayRef availableModes = CGDisplayAvailableModes(display);
+#ifdef VERBOSE_ON
+    CFIndex numberOfAvailableModes = CFArrayGetCount(availableModes);
+    CFIndex numberOfAvailableModesRots = ROTMODES_PER_REALMODE * numberOfAvailableModes;
+#endif
+    CFDictionaryRef mode = (CFDictionaryRef)CFArrayGetValueAtIndex(availableModes, mode_idx / ROTMODES_PER_REALMODE);
+    // mode = CGDisplayModeRetain(mode); // 10.6 on CGDisplayModeRef
+
+    int ccwRot = mode_idx % ROTMODES_PER_REALMODE * 90;
+    DBG_PRINT( "setScreenMode0: scrn %d (%p, %p), mode %d, rot %d ccw, avail: %d/%d\n",  
+        (int)scrn_idx, screen, (void*)(intptr_t)display, (int)mode_idx, ccwRot, (int)numberOfAvailableModes, (int)numberOfAvailableModesRots);
+
+    if(ccwRot!=0) {
+        // FIXME: How to rotate the display/screen on OSX programmatically ?
+        DBG_PRINT( "setScreenMode0: Don't know how to rotate screen on OS X: rot %d ccw\n", ccwRot);
+        res = JNI_FALSE;
+    }
+    if(JNI_TRUE == res) {
+        CGError err = CGDisplaySwitchToMode(display, mode);
+        if(kCGErrorSuccess != err) {
+            DBG_PRINT( "setScreenMode0: SetMode failed: %d\n", (int)err);
+            res = JNI_FALSE;
+        }
+    }
+
+    // CGDisplayModeRelease(mode); // 10.6 on CGDisplayModeRef
+    [pool release];
+
+    return res;
+}
+
 /*
  * Class:     jogamp_newt_driver_macosx_MacWindow
  * Method:    initIDs
@@ -354,7 +578,8 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_createWindow0
                                                styleMask: (NSUInteger) styleMask
                                                backing: (NSBackingStoreType) bufferingType
                                                defer: NO
-                                               screen: myScreen];
+                                               screen: myScreen
+                                               isFullscreenWindow: fullscreen];
     [myWindow setReleasedWhenClosed: YES]; // default
     [myWindow setPreservesContentDuringLiveResize: NO];
 
@@ -421,9 +646,13 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_macosx_MacWindow_createWindow0
     [myView lockFocus];
     [myView unlockFocus];
 
+NS_DURING
     // concurrent view rendering
+    // Available >= 10.6 - Makes the menubar disapear
     [myWindow setAllowsConcurrentViewDrawing: YES];
     [myView setCanDrawConcurrently: YES];
+NS_HANDLER
+NS_ENDHANDLER
 
     // visible on front
     [myWindow orderFront: myWindow];
@@ -471,8 +700,23 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_close0
     NewtMacWindow* mWin = (NewtMacWindow*) ((intptr_t) window);
     NewtView* mView = (NewtView *)[mWin contentView];
     NSWindow* pWin = [mWin parentWindow];
-    DBG_PRINT( "windowClose.0 - %p,%d view %p,%d, parent %p\n", 
-        mWin, getRetainCount(mWin), mView, getRetainCount(mView), pWin);
+    BOOL destroyNotifySent = (NULL != mView) ? [mView getDestroyNotifySent] : false;
+
+    DBG_PRINT( "windowClose.0 - %p,%d, destroyNotifySent %d, view %p,%d, parent %p\n", 
+        mWin, getRetainCount(mWin), destroyNotifySent, mView, getRetainCount(mView), pWin);
+
+    [mWin setUnrealized];
+
+    if(NULL!=mView) {
+        // cleanup view
+        jobject javaWindowObject = [mView getJavaWindowObject];
+        [mView setDestroyNotifySent: true];
+        if(NULL!=javaWindowObject) {
+            DBG_PRINT( "windowClose.0: Clear global javaWindowObject reference (%p)\n", javaWindowObject);
+            (*env)->DeleteGlobalRef(env, javaWindowObject);
+            [mView setJavaWindowObject: NULL];
+        }
+    }
 
 NS_DURING
     if(NULL!=mView) {
@@ -480,8 +724,9 @@ NS_DURING
         if([mView isInFullScreenMode]) {
             [mView exitFullScreenModeWithOptions: NULL];
         }
-        [mWin setContentView: nil];
-        [mView release];
+        // Note: mWin's release will also release it's mView!
+        // [mWin setContentView: nil];
+        // [mView release];
     }
 NS_HANDLER
 NS_ENDHANDLER
@@ -494,10 +739,19 @@ NS_ENDHANDLER
     DBG_PRINT( "windowClose.1 - %p,%d view %p,%d, parent %p\n", 
         mWin, getRetainCount(mWin), mView, getRetainCount(mView), pWin);
 
-    [mWin close]; // performs release!
+    // Only release window, if release is not yet in process.
+    // E.g. destroyNotifySent:=true set by NewtMacWindow::windowWillClose(), i.e. window-close was clicked.
+    if(!destroyNotifySent) { 
+        // '[mWin close]' causes a crash at exit.
+        // This probably happens b/c it sends events to the main loop
+        // but our resources are gone ?!
+        // However, issuing a simple release seems to work quite well.
+        // [mWin release];
+        [mWin performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
+    }
 
-    DBG_PRINT( "windowClose.X - %p,%d view %p,%d, parent %p\n", 
-        mWin, getRetainCount(mWin), mView, getRetainCount(mView), pWin);
+    DBG_PRINT( "windowClose.X - %p,%d, released %d, view %p,%d, parent %p\n", 
+        mWin, getRetainCount(mWin), !destroyNotifySent, mView, getRetainCount(mView), pWin);
 
     [pool release];
 }
@@ -511,6 +765,9 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_lockSurface0
   (JNIEnv *env, jclass clazz, jlong window)
 {
     NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window);
+    if(NO == [mWin isRealized]) {
+        return JNI_FALSE;
+    }
     NewtView * mView = (NewtView *) [mWin contentView];
     return [mView softLock] == YES ? JNI_TRUE : JNI_FALSE;
     /** deadlocks, since we render independent of focus
@@ -549,10 +806,11 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocus0
     DBG_PRINT( "requestFocus - window: %p, force %d, hasFocus %d (START)\n", mWin, force, hasFocus);
 
     [mWin makeFirstResponder: nil];
-    // [mWin performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:YES];
-    // [mWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:YES];
-    [mWin orderFrontRegardless];
-    [mWin makeKeyWindow];
+    [mWin performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:YES];
+    [mWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:YES];
+    // This will occasionally cause a free of non allocated object crash:
+    // [mWin orderFrontRegardless];
+    // [mWin makeKeyWindow];
 
     DBG_PRINT( "requestFocus - window: %p, force %d (END)\n", mWin, force);
 
@@ -576,7 +834,9 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_requestFocusPare
 
     DBG_PRINT( "requestFocusParent0 - window: %p, parent: %p, hasFocus %d (START)\n", mWin, pWin, hasFocus );
     if(NULL != pWin) {
-        [pWin makeKeyWindow];
+        [pWin performSelectorOnMainThread:@selector(makeKeyWindow) withObject:nil waitUntilDone:YES];
+        // This will occasionally cause a free of non allocated object crash:
+        // [pWin makeKeyWindow];
     }
     DBG_PRINT( "requestFocusParent0 - window: %p, parent: %p (END)\n", mWin, pWin);
 
@@ -596,7 +856,9 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderFront0
 
     DBG_PRINT( "orderFront0 - window: %p (START)\n", win);
 
-    [win orderFrontRegardless];
+    [win performSelectorOnMainThread:@selector(orderFrontRegardless) withObject:nil waitUntilDone:YES];
+    // This will occasionally cause a free of non allocated object crash:
+    // [win orderFrontRegardless];
 
     DBG_PRINT( "orderFront0 - window: %p (END)\n", win);
 
@@ -618,9 +880,13 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_macosx_MacWindow_orderOut0
     DBG_PRINT( "orderOut0 - window: (parent %p) %p (START)\n", pWin, mWin);
 
     if(NULL == pWin) {
-        [mWin orderOut: mWin];
+        [mWin performSelectorOnMainThread:@selector(orderOut:) withObject:mWin waitUntilDone:YES];
+        // This will occasionally cause a free of non allocated object crash:
+        // [mWin orderOut: mWin];
     } else {
-        [mWin orderBack: mWin];
+        [mWin performSelectorOnMainThread:@selector(orderBack:) withObject:mWin waitUntilDone:YES];
+        // This will occasionally cause a free of non allocated object crash:
+        // [mWin orderBack: mWin];
     }
 
     DBG_PRINT( "orderOut0 - window: (parent %p) %p (END)\n", pWin, mWin);
@@ -815,10 +1081,11 @@ JNIEXPORT jobject JNICALL Java_jogamp_newt_driver_macosx_MacWindow_getLocationOn
  * Signature: (JZ)Z
  */
 JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_macosx_MacWindow_setPointerVisible0
-  (JNIEnv *env, jclass clazz, jlong window, jboolean mouseVisible)
+  (JNIEnv *env, jclass clazz, jlong window, jboolean hasFocus, jboolean mouseVisible)
 {
     NewtMacWindow *mWin = (NewtMacWindow*) ((intptr_t) window);
-    [mWin setMouseVisible: ( JNI_TRUE == mouseVisible ) ? YES : NO];
+    [mWin setMouseVisible: ( JNI_TRUE == mouseVisible ) ? YES : NO 
+                 hasFocus: ( JNI_TRUE == hasFocus ) ? YES : NO];
     return JNI_TRUE;
 }
 
diff --git a/src/newt/native/MouseEvent.h b/src/newt/native/MouseEvent.h
index e9c0476..59d63ce 100644
--- a/src/newt/native/MouseEvent.h
+++ b/src/newt/native/MouseEvent.h
@@ -1,3 +1,30 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
 
 #ifndef _MOUSE_EVENT_H_
 #define _MOUSE_EVENT_H_
diff --git a/src/newt/native/NewtCommon.h b/src/newt/native/NewtCommon.h
index 91fceb3..f5ca73b 100644
--- a/src/newt/native/NewtCommon.h
+++ b/src/newt/native/NewtCommon.h
@@ -1,3 +1,30 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
 
 #ifndef NEWT_COMMON_H
 #define NEWT_COMMON_H 1
@@ -12,6 +39,42 @@ jchar* NewtCommon_GetNullTerminatedStringChars(JNIEnv* env, jstring str);
 void NewtCommon_FatalError(JNIEnv *env, const char* msg, ...);
 void NewtCommon_throwNewRuntimeException(JNIEnv *env, const char* msg, ...);
 
+/**
+ *
+ * 1) Store jvmHandle and jvmVersion
+
+    JavaVM *jvmHandle = NULL;
+    int jvmVersion = 0;
+
+    if(0 != (*env)->GetJavaVM(env, &jvmHandle)) {
+        jvmHandle = NULL;
+    } else {
+        jvmVersion = (*env)->GetVersion(env);
+    }
+
+ *
+ * 2) Use current thread JNIEnv or attach current thread to JVM, generating new JNIEnv
+ *
+
+    int shallBeDetached = 0;
+    JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
+    if(NULL==env) {
+        DBG_PRINT("drawRect: null JNIEnv\n");
+        return;
+    }
+    
+ *
+ * 3) Use JNIEnv ..
+ *
+    .. your JNIEnv code here ..
+
+ *
+ * 4) Detach thread from JVM, if required
+ *
+    if (shallBeDetached) {
+        (*jvmHandle)->DetachCurrentThread(jvmHandle);
+    }
+ */
 JNIEnv* NewtCommon_GetJNIEnv (JavaVM * jvmHandle, int jvmVersion, int * shallBeDetached);
 
 #endif
diff --git a/src/newt/native/NewtMacWindow.h b/src/newt/native/NewtMacWindow.h
index eaece2c..c0912ad 100644
--- a/src/newt/native/NewtMacWindow.h
+++ b/src/newt/native/NewtMacWindow.h
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2009 Sun Microsystems, Inc. All Rights Reserved.
+ * Copyright (c) 2011 JogAmp Community. All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -64,6 +65,7 @@
 }
 
 - (id)initWithFrame:(NSRect)frameRect;
+- (void) release;
 - (void) dealloc;
 
 /* Set during event dispatching cycle */
@@ -103,10 +105,12 @@
 @interface NewtMacWindow : NSWindow 
 #endif
 {
+    BOOL isFullscreenWindow;
     BOOL mouseConfined;
     BOOL mouseVisible;
     BOOL mouseInside;
     BOOL cursorIsHidden;
+    BOOL realized;
     NSPoint lastInsideMousePosition;
 @public
     int cachedInsets[4]; // l, r, t, b
@@ -118,7 +122,12 @@
        styleMask: (NSUInteger) windowStyle
        backing: (NSBackingStoreType) bufferingType
        defer: (BOOL) deferCreation
-       screen:(NSScreen *)screen;
+       screen:(NSScreen *)screen
+       isFullscreenWindow:(BOOL)isfs;
+- (void) release;
+- (void) dealloc;
+- (void) setUnrealized;
+- (BOOL) isRealized;
 
 - (void) updateInsets: (JNIEnv*) env;
 - (void) attachToParent: (NSWindow*) parent;
@@ -129,17 +138,41 @@
 - (NSPoint) getLocationOnScreen: (NSPoint) p;
 - (NSPoint) screenPos2NewtClientWinPos: (NSPoint) p;
 
+- (BOOL) isMouseInside;
 - (void) cursorHide:(BOOL)v;
-- (void) setMouseVisible:(BOOL)v;
+- (void) setMouseVisible:(BOOL)v hasFocus:(BOOL)focus;
 - (void) setMouseConfined:(BOOL)v;
 - (void) setMousePosition:(NSPoint)p;
 
+- (void) sendKeyEvent: (NSEvent*) event eventType: (jint) evType;
+- (void) sendMouseEvent: (NSEvent*) event eventType: (jint) evType;
+- (void) focusChanged: (BOOL) gained;
+
 - (BOOL) becomeFirstResponder;
 - (BOOL) resignFirstResponder;
+- (BOOL) canBecomeKeyWindow;
 - (void) becomeKeyWindow;
 - (void) resignKeyWindow;
 - (void) windowDidBecomeKey: (NSNotification *) notification;
 - (void) windowDidResignKey: (NSNotification *) notification;
-- (void) focusChanged: (BOOL) gained;
+- (void) keyDown: (NSEvent*) theEvent;
+- (void) keyUp: (NSEvent*) theEvent;
+- (void) mouseEntered: (NSEvent*) theEvent;
+- (void) mouseExited: (NSEvent*) theEvent;
+- (void) mouseMoved: (NSEvent*) theEvent;
+- (void) scrollWheel: (NSEvent*) theEvent;
+- (void) mouseDown: (NSEvent*) theEvent;
+- (void) mouseDragged: (NSEvent*) theEvent;
+- (void) mouseUp: (NSEvent*) theEvent;
+- (void) rightMouseDown: (NSEvent*) theEvent;
+- (void) rightMouseDragged: (NSEvent*) theEvent;
+- (void) rightMouseUp: (NSEvent*) theEvent;
+- (void) otherMouseDown: (NSEvent*) theEvent;
+- (void) otherMouseUp: (NSEvent*) theEvent;
+- (void) windowDidResize: (NSNotification*) notification;
+- (void) windowDidMove: (NSNotification*) notification;
+- (BOOL) windowClosingImpl: (BOOL) force;
+- (BOOL) windowShouldClose: (id) sender;
+- (void) windowWillClose: (NSNotification*) notification;
 
 @end
diff --git a/src/newt/native/NewtMacWindow.m b/src/newt/native/NewtMacWindow.m
index ce41673..f914467 100644
--- a/src/newt/native/NewtMacWindow.m
+++ b/src/newt/native/NewtMacWindow.m
@@ -119,12 +119,25 @@ static jmethodID windowRepaintID = NULL;
     return [super initWithFrame:frameRect];
 }
 
+- (void) release
+{
+#ifdef VERBOSE_ON
+    NSLog(@"NewtView::release\n");
+    NSLog(@"%@",[NSThread callStackSymbols]);
+#endif
+    [super release];
+}
+
 - (void) dealloc
 {
     if(softLocked) {
         NSLog(@"NewtView::dealloc: softLock still hold @ dealloc!\n");
     }
     pthread_mutex_destroy(&softLockSync);
+#ifdef VERBOSE_ON
+    NSLog(@"NewtView::dealloc\n");
+    NSLog(@"%@",[NSThread callStackSymbols]);
+#endif
     [super dealloc];
 }
 
@@ -238,10 +251,14 @@ static jmethodID windowRepaintID = NULL;
     DBG_PRINT("*************** dirtyRect: %p %lf/%lf %lfx%lf\n", 
         javaWindowObject, dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);
 
+    if(NULL==javaWindowObject) {
+        DBG_PRINT("drawRect: null javaWindowObject\n");
+        return;
+    }
     int shallBeDetached = 0;
     JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
     if(NULL==env) {
-        DBG_PRINT("viewDidHide: null JNIEnv\n");
+        DBG_PRINT("drawRect: null JNIEnv\n");
         return;
     }
 
@@ -258,6 +275,10 @@ static jmethodID windowRepaintID = NULL;
 
 - (void) viewDidHide
 {
+    if(NULL==javaWindowObject) {
+        DBG_PRINT("viewDidHide: null javaWindowObject\n");
+        return;
+    }
     int shallBeDetached = 0;
     JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
     if(NULL==env) {
@@ -276,10 +297,14 @@ static jmethodID windowRepaintID = NULL;
 
 - (void) viewDidUnhide
 {
+    if(NULL==javaWindowObject) {
+        DBG_PRINT("viewDidUnhide: null javaWindowObject\n");
+        return;
+    }
     int shallBeDetached = 0;
     JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
     if(NULL==env) {
-        DBG_PRINT("viewDidHide: null JNIEnv\n");
+        DBG_PRINT("viewDidUnhide: null JNIEnv\n");
         return;
     }
 
@@ -312,7 +337,7 @@ static jmethodID windowRepaintID = NULL;
     insetsChangedID = (*env)->GetMethodID(env, clazz, "insetsChanged", "(ZIIII)V");
     positionChangedID = (*env)->GetMethodID(env, clazz, "positionChanged", "(ZII)V");
     focusChangedID = (*env)->GetMethodID(env, clazz, "focusChanged", "(ZZ)V");
-    windowDestroyNotifyID    = (*env)->GetMethodID(env, clazz, "windowDestroyNotify",    "()V");
+    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z");
     windowRepaintID = (*env)->GetMethodID(env, clazz, "windowRepaint", "(ZIIII)V");
     requestFocusID = (*env)->GetMethodID(env, clazz, "requestFocus", "(Z)V");
     if (enqueueMouseEventID && sendMouseEventID && enqueueKeyEventID && sendKeyEventID && sizeChangedID && visibleChangedID && insetsChangedID &&
@@ -328,12 +353,14 @@ static jmethodID windowRepaintID = NULL;
        backing: (NSBackingStoreType) bufferingType
        defer: (BOOL) deferCreation
        screen:(NSScreen *)screen
+       isFullscreenWindow:(BOOL)isfs
 {
     id res = [super initWithContentRect: contentRect
                     styleMask: windowStyle
                     backing: bufferingType
                     defer: deferCreation
                     screen: screen];
+    isFullscreenWindow = isfs;
     // Why is this necessary? Without it we don't get any of the
     // delegate methods like resizing and window movement.
     [self setDelegate: self];
@@ -345,9 +372,38 @@ static jmethodID windowRepaintID = NULL;
     mouseVisible = YES;
     mouseInside = NO;
     cursorIsHidden = NO;
+    realized = YES;
     return res;
 }
 
+- (void) release
+{
+#ifdef VERBOSE_ON
+    NSLog(@"NewtWindow::release\n");
+    NSLog(@"%@",[NSThread callStackSymbols]);
+#endif
+    [super release];
+}
+
+- (void) dealloc
+{
+#ifdef VERBOSE_ON
+    NSLog(@"NewtWindow::dealloc\n");
+    NSLog(@"%@",[NSThread callStackSymbols]);
+#endif
+    [super dealloc];
+}
+
+- (void) setUnrealized
+{
+    realized = NO;
+}
+
+- (BOOL) isRealized
+{
+    return realized;
+}
+
 - (void) updateInsets: (JNIEnv*) env
 {
     NSView* nsview = [self contentView];
@@ -389,8 +445,10 @@ static jmethodID windowRepaintID = NULL;
 {
     DBG_PRINT( "detachFromParent.1\n");
     [self setParentWindow: nil];
-    DBG_PRINT( "detachFromParent.2\n");
-    [parent removeChildWindow: self];
+    if(NULL != parent) {
+        DBG_PRINT( "detachFromParent.2\n");
+        [parent removeChildWindow: self];
+    }
     DBG_PRINT( "detachFromParent.X\n");
 }
 
@@ -463,15 +521,60 @@ static jmethodID windowRepaintID = NULL;
     // NSRect rS = [win convertRectFromScreen: r]; // 10.7
     NSPoint oS = [self convertScreenToBase: r.origin];
     oS.y = viewFrame.size.height - oS.y; // y-flip
-
     return oS;
 }
 
-- (BOOL) canBecomeKeyWindow
+- (BOOL) isMouseInside
 {
-    // Even if the window is borderless, we still want it to be able
-    // to become the key window to receive keyboard events
-    return YES;
+    NSView* view = [self contentView];
+    NSRect viewFrame = [view frame];
+    NSPoint l1 = [NSEvent mouseLocation];
+    NSPoint l0 = [self screenPos2NewtClientWinPos: l1];
+    return viewFrame.origin.x <= l0.x && l0.x < (viewFrame.origin.x+viewFrame.size.width) &&
+           viewFrame.origin.y <= l0.y && l0.y < (viewFrame.origin.y+viewFrame.size.height) ;
+}
+
+- (void) setMouseVisible:(BOOL)v hasFocus:(BOOL)focus
+{
+    mouseVisible = v;
+    mouseInside = [self isMouseInside];
+    DBG_PRINT( "setMouseVisible: confined %d, visible %d (current: %d), mouseInside %d, hasFocus %d\n", 
+        mouseConfined, mouseVisible, !cursorIsHidden, mouseInside, focus);
+    if(YES == focus && YES == mouseInside) {
+        [self cursorHide: !mouseVisible];
+    }
+}
+
+- (void) cursorHide:(BOOL)v
+{
+    DBG_PRINT( "cursorHide: %d -> %d\n", cursorIsHidden, v);
+    if(v) {
+        if(!cursorIsHidden) {
+            [NSCursor hide];
+            cursorIsHidden = YES;
+        }
+    } else {
+        if(cursorIsHidden) {
+            [NSCursor unhide];
+            cursorIsHidden = NO;
+        }
+    }
+}
+
+- (void) setMouseConfined:(BOOL)v
+{
+    mouseConfined = v;
+    DBG_PRINT( "setMouseConfined: confined %d, visible %d\n", mouseConfined, mouseVisible);
+}
+
+- (void) setMousePosition:(NSPoint)p
+{
+    NSScreen* screen = [self screen];
+    NSRect screenRect = [screen frame];
+
+    CGPoint pt = { p.x, screenRect.size.height - p.y }; // y-flip (CG is top-left origin)
+    CGEventRef ev = CGEventCreateMouseEvent (NULL, kCGEventMouseMoved, pt, kCGMouseButtonLeft);
+    CGEventPost (kCGHIDEventTap, ev);
 }
 
 static jint mods2JavaMods(NSUInteger mods)
@@ -538,17 +641,6 @@ static jint mods2JavaMods(NSUInteger mods)
     }
 }
 
-- (void) keyDown: (NSEvent*) theEvent
-{
-    [self sendKeyEvent: theEvent eventType: EVENT_KEY_PRESSED];
-}
-
-- (void) keyUp: (NSEvent*) theEvent
-{
-    [self sendKeyEvent: theEvent eventType: EVENT_KEY_RELEASED];
-    [self sendKeyEvent: theEvent eventType: EVENT_KEY_TYPED];
-}
-
 - (void) sendMouseEvent: (NSEvent*) event eventType: (jint) evType
 {
     NSView* nsview = [self contentView];
@@ -624,53 +716,100 @@ static jint mods2JavaMods(NSUInteger mods)
     }
 }
 
-- (void) setMouseVisible:(BOOL)v
+- (void) focusChanged: (BOOL) gained
 {
-    mouseVisible = v;
-    DBG_PRINT( "setMouseVisible: confined %d, visible %d\n", mouseConfined, mouseVisible);
-    if(YES == mouseInside) {
-        [self cursorHide: !mouseVisible];
+    DBG_PRINT( "focusChanged: gained %d\n", gained);
+    NSView* nsview = [self contentView];
+    if( ! [nsview isMemberOfClass:[NewtView class]] ) {
+        return;
+    }
+    NewtView* view = (NewtView *) nsview;
+    jobject javaWindowObject = [view getJavaWindowObject];
+    if (javaWindowObject == NULL) {
+        DBG_PRINT("focusChanged: null javaWindowObject\n");
+        return;
+    }
+    int shallBeDetached = 0;
+    JavaVM *jvmHandle = [view getJVMHandle];
+    JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, [view getJVMVersion], &shallBeDetached);
+    if(NULL==env) {
+        DBG_PRINT("focusChanged: null JNIEnv\n");
+        return;
+    }
+
+    (*env)->CallVoidMethod(env, javaWindowObject, focusChangedID, JNI_FALSE, (gained == YES) ? JNI_TRUE : JNI_FALSE);
+
+    if (shallBeDetached) {
+        (*jvmHandle)->DetachCurrentThread(jvmHandle);
     }
 }
 
-- (void) cursorHide:(BOOL)v
+- (BOOL) becomeFirstResponder
 {
-    if(v) {
-        if(!cursorIsHidden) {
-            [NSCursor hide];
-            cursorIsHidden = YES;
-        }
-    } else {
-        if(cursorIsHidden) {
-            [NSCursor unhide];
-            cursorIsHidden = NO;
-        }
+    DBG_PRINT( "*************** becomeFirstResponder\n");
+    return [super becomeFirstResponder];
+}
+
+- (BOOL) resignFirstResponder
+{
+    DBG_PRINT( "*************** resignFirstResponder\n");
+    return [super resignFirstResponder];
+}
+
+- (BOOL) canBecomeKeyWindow
+{
+    // Even if the window is borderless, we still want it to be able
+    // to become the key window to receive keyboard events
+    return YES;
+}
+
+- (void) becomeKeyWindow
+{
+    DBG_PRINT( "*************** becomeKeyWindow\n");
+    [super becomeKeyWindow];
+}
+
+- (void) resignKeyWindow
+{
+    DBG_PRINT( "*************** resignKeyWindow: isFullscreen %d\n", (int)isFullscreenWindow);
+    if(!isFullscreenWindow) {
+        [super resignKeyWindow];
     }
 }
 
-- (void) setMouseConfined:(BOOL)v
+- (void) windowDidBecomeKey: (NSNotification *) notification
 {
-    mouseConfined = v;
-    DBG_PRINT( "setMouseConfined: confined %d, visible %d\n", mouseConfined, mouseVisible);
+    DBG_PRINT( "*************** windowDidBecomeKey\n");
+    mouseInside = [self isMouseInside];
+    if(YES == mouseInside) {
+        [self cursorHide: !mouseVisible];
+    }
+    [self focusChanged: YES];
 }
 
-- (void) setMousePosition:(NSPoint)p
+- (void) windowDidResignKey: (NSNotification *) notification
 {
-    NSScreen* screen = [self screen];
-    NSRect screenRect = [screen frame];
+    DBG_PRINT( "*************** windowDidResignKey\n");
+    // Implicit mouse exit by OS X
+    [self focusChanged: NO];
+}
 
-    CGPoint pt = { p.x, screenRect.size.height - p.y }; // y-flip (CG is top-left origin)
-    CGEventRef ev = CGEventCreateMouseEvent (NULL, kCGEventMouseMoved, pt, kCGMouseButtonLeft);
-    CGEventPost (kCGHIDEventTap, ev);
-    NSPoint l0 = [NSEvent mouseLocation];
-    [self screenPos2NewtClientWinPos: l0];
+- (void) keyDown: (NSEvent*) theEvent
+{
+    [self sendKeyEvent: theEvent eventType: EVENT_KEY_PRESSED];
+}
+
+- (void) keyUp: (NSEvent*) theEvent
+{
+    [self sendKeyEvent: theEvent eventType: EVENT_KEY_RELEASED];
+    [self sendKeyEvent: theEvent eventType: EVENT_KEY_TYPED];
 }
 
 - (void) mouseEntered: (NSEvent*) theEvent
 {
     DBG_PRINT( "mouseEntered: confined %d, visible %d\n", mouseConfined, mouseVisible);
     mouseInside = YES;
-    [self setMouseVisible: mouseVisible];
+    [self cursorHide: !mouseVisible];
     if(NO == mouseConfined) {
         [self sendMouseEvent: theEvent eventType: EVENT_MOUSE_ENTERED];
     }
@@ -814,8 +953,19 @@ static jint mods2JavaMods(NSUInteger mods)
     }
 }
 
+- (BOOL)windowShouldClose: (id) sender
+{
+    return [self windowClosingImpl: NO];
+}
+
 - (void)windowWillClose: (NSNotification*) notification
 {
+    [self windowClosingImpl: YES];
+}
+
+- (BOOL) windowClosingImpl: (BOOL) force
+{
+    jboolean closed = JNI_FALSE;
     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
 
     [self cursorHide: NO];
@@ -841,86 +991,22 @@ static jint mods2JavaMods(NSUInteger mods)
             return;
         }
 
-        [view setDestroyNotifySent: true];
-        (*env)->CallVoidMethod(env, javaWindowObject, windowDestroyNotifyID);
-        // Can't issue call here - locked window state, done from Java method
-
-        // EOL ..
-        (*env)->DeleteGlobalRef(env, javaWindowObject);
-        [view setJavaWindowObject: NULL];
+        [view setDestroyNotifySent: true]; // earmark assumption of being closed
+        closed = (*env)->CallBooleanMethod(env, javaWindowObject, windowDestroyNotifyID, force ? JNI_TRUE : JNI_FALSE);
+        if(!force && !closed) {
+            // not closed on java side, not force -> clear flag
+            [view setDestroyNotifySent: false];
+        }
 
         if (shallBeDetached) {
             (*jvmHandle)->DetachCurrentThread(jvmHandle);
         }
-        DBG_PRINT( "*************** windowWillClose.X: %p\n", (void *)(intptr_t)javaWindowObject);
+        DBG_PRINT( "*************** windowWillClose.X: %p, closed %d\n", (void *)(intptr_t)javaWindowObject, (int)closed);
     } else {
         DBG_PRINT( "*************** windowWillClose (skip)\n");
     }
     [pool release];
-}
-
-- (BOOL) becomeFirstResponder
-{
-    DBG_PRINT( "*************** becomeFirstResponder\n");
-    return [super becomeFirstResponder];
-}
-
-- (BOOL) resignFirstResponder
-{
-    DBG_PRINT( "*************** resignFirstResponder\n");
-    return [super resignFirstResponder];
-}
-
-- (void) becomeKeyWindow
-{
-    DBG_PRINT( "*************** becomeKeyWindow\n");
-    [super becomeKeyWindow];
-}
-
-- (void) resignKeyWindow
-{
-    DBG_PRINT( "*************** resignKeyWindow\n");
-    [super resignKeyWindow];
-}
-
-- (void) windowDidBecomeKey: (NSNotification *) notification
-{
-    DBG_PRINT( "*************** windowDidBecomeKey\n");
-    [self focusChanged: YES];
-}
-
-- (void) windowDidResignKey: (NSNotification *) notification
-{
-    DBG_PRINT( "*************** windowDidResignKey\n");
-    [self focusChanged: NO];
-}
-
-- (void) focusChanged: (BOOL) gained
-{
-    DBG_PRINT( "focusChanged: gained %d\n", gained);
-    NSView* nsview = [self contentView];
-    if( ! [nsview isMemberOfClass:[NewtView class]] ) {
-        return;
-    }
-    NewtView* view = (NewtView *) nsview;
-    jobject javaWindowObject = [view getJavaWindowObject];
-    if (javaWindowObject == NULL) {
-        DBG_PRINT("focusChanged: null javaWindowObject\n");
-        return;
-    }
-    int shallBeDetached = 0;
-    JavaVM *jvmHandle = [view getJVMHandle];
-    JNIEnv* env = NewtCommon_GetJNIEnv(jvmHandle, [view getJVMVersion], &shallBeDetached);
-    if(NULL==env) {
-        DBG_PRINT("focusChanged: null JNIEnv\n");
-        return;
-    }
-
-    (*env)->CallVoidMethod(env, javaWindowObject, focusChangedID, JNI_FALSE, (gained == YES) ? JNI_TRUE : JNI_FALSE);
-
-    if (shallBeDetached) {
-        (*jvmHandle)->DetachCurrentThread(jvmHandle);
-    }
+    return JNI_TRUE == closed ? YES : NO ;
 }
 
 @end
diff --git a/src/newt/native/ScreenMode.h b/src/newt/native/ScreenMode.h
index 0a760d5..bb78291 100644
--- a/src/newt/native/ScreenMode.h
+++ b/src/newt/native/ScreenMode.h
@@ -1,4 +1,32 @@
 /**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+/**
  * WARNING: must be synced with com.jogamp.newt.util.ScreenModeUtil#streamIn*(int[])
  */
 
diff --git a/src/newt/native/Window.h b/src/newt/native/Window.h
index 865746b..4755c4f 100644
--- a/src/newt/native/Window.h
+++ b/src/newt/native/Window.h
@@ -1,3 +1,30 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
 
 #ifndef _WINDOW_H_
 #define _WINDOW_H_
diff --git a/src/newt/native/WindowEvent.h b/src/newt/native/WindowEvent.h
index 05491b4..3dc6ba9 100644
--- a/src/newt/native/WindowEvent.h
+++ b/src/newt/native/WindowEvent.h
@@ -1,3 +1,30 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
 
 #ifndef _WINDOW_EVENT_H_
 #define _WINDOW_EVENT_H_
diff --git a/src/newt/native/WindowsWindow.c b/src/newt/native/WindowsWindow.c
index 9b97895..6d9c04d 100644
--- a/src/newt/native/WindowsWindow.c
+++ b/src/newt/native/WindowsWindow.c
@@ -810,7 +810,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
     //    Java::DestroyWindow(wnd) _or_ window-close-button -> 
     //     WM_CLOSE -> Java::windowDestroyNotify -> W_DESTROY
     case WM_CLOSE:
-        (*env)->CallVoidMethod(env, window, windowDestroyNotifyID);
+        (*env)->CallBooleanMethod(env, window, windowDestroyNotifyID, JNI_FALSE);
         break;
 
     case WM_DESTROY:
@@ -869,7 +869,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_PRESSED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 1, (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -878,7 +878,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_RELEASED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 1, (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -889,7 +889,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_PRESSED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 2, (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -898,7 +898,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_RELEASED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 2, (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -909,7 +909,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_PRESSED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 3, (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -918,7 +918,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_RELEASED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 3,  (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -927,7 +927,7 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         (*env)->CallVoidMethod(env, window, sendMouseEventID,
                                (jint) EVENT_MOUSE_MOVED,
                                GetModifiers(),
-                               (jint) LOWORD(lParam), (jint) HIWORD(lParam),
+                               (jint) GET_X_LPARAM(lParam), (jint) GET_Y_LPARAM(lParam),
                                (jint) 0,  (jint) 0);
         useDefWindowProc = 1;
         break;
@@ -973,8 +973,8 @@ static LRESULT CALLBACK wndProc(HWND wnd, UINT message,
         break;
 
     case WM_MOVE:
-        DBG_PRINT("*** WindowsWindow: WM_MOVE window %p, %d/%d\n", wnd, (int)LOWORD(lParam), (int)HIWORD(lParam));
-        (*env)->CallVoidMethod(env, window, positionChangedID, JNI_FALSE, (jint)LOWORD(lParam), (jint)HIWORD(lParam));
+        DBG_PRINT("*** WindowsWindow: WM_MOVE window %p, %d/%d\n", wnd, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
+        (*env)->CallVoidMethod(env, window, positionChangedID, JNI_FALSE, (jint)GET_X_LPARAM(lParam), (jint)GET_Y_LPARAM(lParam));
         useDefWindowProc = 1;
         break;
 
@@ -1041,13 +1041,47 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_windows_WindowsDisplay_DispatchMe
 
 /*
  * Class:     jogamp_newt_driver_windows_WindowsScreen
+ * Method:    getOriginX0
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginX0
+  (JNIEnv *env, jobject obj, jint scrn_idx)
+{
+    if( GetSystemMetrics( SM_CMONITORS) > 1) {
+        return (jint)GetSystemMetrics(SM_XVIRTUALSCREEN);
+    } else {
+        return 0;
+    }
+}
+
+/*
+ * Class:     jogamp_newt_driver_windows_WindowsScreen
+ * Method:    getOriginY0
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getOriginY0
+  (JNIEnv *env, jobject obj, jint scrn_idx)
+{
+    if( GetSystemMetrics( SM_CMONITORS ) > 1) {
+        return (jint)GetSystemMetrics(SM_YVIRTUALSCREEN);
+    } else {
+        return 0;
+    }
+}
+
+/*
+ * Class:     jogamp_newt_driver_windows_WindowsScreen
  * Method:    getWidthImpl
  * Signature: (I)I
  */
 JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getWidthImpl0
   (JNIEnv *env, jobject obj, jint scrn_idx)
 {
-    return (jint)GetSystemMetrics(SM_CXSCREEN);
+    if( GetSystemMetrics( SM_CMONITORS) > 1) {
+        return (jint)GetSystemMetrics(SM_CXVIRTUALSCREEN);
+    } else {
+        return (jint)GetSystemMetrics(SM_CXSCREEN);
+    }
 }
 
 /*
@@ -1058,7 +1092,11 @@ JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getWidthImp
 JNIEXPORT jint JNICALL Java_jogamp_newt_driver_windows_WindowsScreen_getHeightImpl0
   (JNIEnv *env, jobject obj, jint scrn_idx)
 {
-    return (jint)GetSystemMetrics(SM_CYSCREEN);
+    if( GetSystemMetrics( SM_CMONITORS ) > 1) {
+        return (jint)GetSystemMetrics(SM_CYVIRTUALSCREEN);
+    } else {
+        return (jint)GetSystemMetrics(SM_CYSCREEN);
+    }
 }
 
 static int NewtScreen_RotationNativeCCW2NewtCCW(JNIEnv *env, int native) {
@@ -1259,7 +1297,7 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_initIDs
     positionChangedID = (*env)->GetMethodID(env, clazz, "positionChanged", "(ZII)V");
     focusChangedID = (*env)->GetMethodID(env, clazz, "focusChanged", "(ZZ)V");
     visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V");
-    windowDestroyNotifyID    = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "()V");
+    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z");
     windowRepaintID = (*env)->GetMethodID(env, clazz, "windowRepaint", "(ZIIII)V");
     enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIII)V");
     sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V");
@@ -1310,9 +1348,6 @@ static void NewtWindow_setVisiblePosSize(HWND hwnd, BOOL atop, BOOL visible,
     } else {
         flags = SWP_NOACTIVATE | SWP_NOZORDER;
     }
-    if(0>x || 0>y) {
-        flags |= SWP_NOMOVE;
-    }
     if(0>=width || 0>=height ) {
         flags |= SWP_NOSIZE;
     }
@@ -1338,7 +1373,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind
   (JNIEnv *env, jobject obj, 
    jlong hInstance, jstring jWndClassName, jstring jWndName, 
    jlong parent,
-   jint jx, jint jy, jint defaultWidth, jint defaultHeight, jint flags)
+   jint jx, jint jy, jint defaultWidth, jint defaultHeight, jboolean autoPosition, jint flags)
 {
     HWND parentWindow = (HWND) (intptr_t) parent;
     const TCHAR* wndClassName = NULL;
@@ -1367,7 +1402,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind
         windowStyle |= WS_POPUP | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX;
     } else {
         windowStyle |= WS_OVERLAPPEDWINDOW;
-        if(0>_x || 0>_y) {
+        if(JNI_TRUE == autoPosition) {
             // user didn't requested specific position, use WM default
             _x = CW_USEDEFAULT;
             _y = 0;
@@ -1380,9 +1415,9 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind
                           (HINSTANCE) (intptr_t) hInstance,
                           NULL);
 
-    DBG_PRINT("*** WindowsWindow: CreateWindow thread 0x%X, parent %p, window %p, %d/%d %dx%d, undeco %d, alwaysOnTop %d\n", 
+    DBG_PRINT("*** WindowsWindow: CreateWindow thread 0x%X, parent %p, window %p, %d/%d %dx%d, undeco %d, alwaysOnTop %d, autoPosition %d\n", 
         (int)GetCurrentThreadId(), parentWindow, window, x, y, width, height,
-        TST_FLAG_IS_UNDECORATED(flags), TST_FLAG_IS_ALWAYSONTOP(flags));
+        TST_FLAG_IS_UNDECORATED(flags), TST_FLAG_IS_ALWAYSONTOP(flags), autoPosition);
 
     if (NULL == window) {
         int lastError = (int) GetLastError();
@@ -1402,7 +1437,6 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind
         {
             RECT rc;
             RECT * insets;
-            BOOL userPos = 0<=x && 0<=y ;
 
             ShowWindow(window, SW_SHOW);
 
@@ -1410,12 +1444,12 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_windows_WindowsWindow_CreateWind
             insets = UpdateInsets(env, wud->jinstance, window);
             (*env)->CallVoidMethod(env, wud->jinstance, visibleChangedID, JNI_FALSE, JNI_TRUE);
 
-            if(!userPos) {
+            if(JNI_TRUE == autoPosition) {
                 GetWindowRect(window, &rc);
                 x = rc.left + insets->left; // client coords
                 y = rc.top + insets->top;   // client coords
             }
-            DBG_PRINT("*** WindowsWindow: CreateWindow client: %d/%d %dx%d (is user-pos %d)\n", x, y, width, height, userPos);
+            DBG_PRINT("*** WindowsWindow: CreateWindow client: %d/%d %dx%d (autoPosition %d)\n", x, y, width, height, autoPosition);
 
             x -= insets->left; // top-level
             y -= insets->top;  // top-level
diff --git a/src/newt/classes/jogamp/newt/driver/android/MD.java b/src/newt/native/X11Common.h
similarity index 54%
copy from src/newt/classes/jogamp/newt/driver/android/MD.java
copy to src/newt/native/X11Common.h
index 06f7872..cefef69 100644
--- a/src/newt/classes/jogamp/newt/driver/android/MD.java
+++ b/src/newt/native/X11Common.h
@@ -25,41 +25,56 @@
  * authors and should not be interpreted as representing official policies, either expressed
  * or implied, of JogAmp Community.
  */
-package jogamp.newt.driver.android;
 
-import java.util.List;
+#ifndef _X11COMMON_H_
+#define _X11COMMON_H_
 
-import javax.media.opengl.GLDrawableFactory;
-import javax.media.opengl.GLProfile;
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
 
-import com.jogamp.common.GlueGenVersion;
-import com.jogamp.common.os.Platform;
-import com.jogamp.common.util.VersionUtil;
-import com.jogamp.opengl.JoglVersion;
+#include <gluegen_stdint.h>
+
+#include <unistd.h>
+#include <errno.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <X11/keysym.h>
+#include <X11/Xatom.h>
+
+#include <X11/extensions/Xrandr.h>
+
+#include "jogamp_newt_driver_x11_X11Screen.h"
+#include "jogamp_newt_driver_x11_X11Display.h"
+#include "jogamp_newt_driver_x11_X11Window.h"
+
+#include "Window.h"
+#include "MouseEvent.h"
+#include "InputEvent.h"
+#include "KeyEvent.h"
+#include "WindowEvent.h"
+#include "ScreenMode.h"
+
+#include "NewtCommon.h"
+
+// #define VERBOSE_ON 1
+
+#ifdef VERBOSE_ON
+    #define DBG_PRINT(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) 
+#else
+    #define DBG_PRINT(...)
+#endif
+
+extern jclass X11NewtWindowClazz;
+extern jmethodID insetsChangedID;
+extern jmethodID visibleChangedID;
+
+jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning);
+
+void NewtDisplay_displayDispatchErrorHandlerEnable(int onoff, JNIEnv * env);
+Status NewtWindows_getRootAndParent (Display *dpy, Window w, Window * root_return, Window * parent_return);
+Status NewtWindows_updateInsets(JNIEnv *env, jobject jwindow, Display *dpy, Window window, int *left, int *right, int *top, int *bottom);
+
+#endif /* _X11COMMON_H_ */
 
-public class MD {
-   public static final String TAG = "JogAmp.NEWT";
-   
-   public static String getInfo() { 
-       
-        StringBuffer sb = new StringBuffer();
-        
-        sb.append(VersionUtil.getPlatformInfo()).append(Platform.NEWLINE)
-              .append(GlueGenVersion.getInstance()).append(Platform.NEWLINE)
-              .append(JoglVersion.getInstance()).append(Platform.NEWLINE)
-              .append(Platform.NEWLINE);
-              
-        final GLDrawableFactory factory = GLDrawableFactory.getEGLFactory();
-        final List/*<GLCapabilitiesImmutable>*/ availCaps = factory.getAvailableCapabilities(null);
-        for(int i=0; i<availCaps.size(); i++) {
-            sb.append(availCaps.get(i)).append(Platform.NEWLINE);
-        }
-       
-       return sb.toString();       
-   }
-   
-    public static void main(String args[]) {
-        
-        System.err.println(getInfo());
-    }
-}
diff --git a/src/newt/native/X11Display.c b/src/newt/native/X11Display.c
new file mode 100644
index 0000000..88ac0df
--- /dev/null
+++ b/src/newt/native/X11Display.c
@@ -0,0 +1,663 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+#include "X11Common.h"
+
+#define USE_SENDIO_DIRECT 1
+
+jclass X11NewtWindowClazz = NULL;
+jmethodID insetsChangedID = NULL;
+jmethodID visibleChangedID = NULL;
+
+static const char * const ClazzNameX11NewtWindow = "jogamp/newt/driver/x11/X11Window";
+
+static jmethodID displayCompletedID = NULL;
+
+static jmethodID sizeChangedID = NULL;
+static jmethodID positionChangedID = NULL;
+static jmethodID focusChangedID = NULL;
+static jmethodID reparentNotifyID = NULL;
+static jmethodID windowDestroyNotifyID = NULL;
+static jmethodID windowRepaintID = NULL;
+static jmethodID enqueueMouseEventID = NULL;
+static jmethodID sendMouseEventID = NULL;
+static jmethodID enqueueKeyEventID = NULL;
+static jmethodID sendKeyEventID = NULL;
+static jmethodID requestFocusID = NULL;
+
+static JavaVM *jvmHandle = NULL;
+static int jvmVersion = 0;
+
+static void setupJVMVars(JNIEnv * env) {
+    if(0 != (*env)->GetJavaVM(env, &jvmHandle)) {
+        jvmHandle = NULL;
+    }
+    jvmVersion = (*env)->GetVersion(env);
+}
+
+static XErrorHandler origErrorHandler = NULL ;
+
+static int displayDispatchErrorHandler(Display *dpy, XErrorEvent *e)
+{
+    fprintf(stderr, "Warning: NEWT X11 Error: DisplayDispatch %p, Code 0x%X, errno %s\n", dpy, e->error_code, strerror(errno));
+    
+    if (e->error_code == BadAtom) {
+        fprintf(stderr, "         BadAtom (%p): Atom probably already removed\n", (void*)e->resourceid);
+    } else if (e->error_code == BadWindow) {
+        fprintf(stderr, "         BadWindow (%p): Window probably already removed\n", (void*)e->resourceid);
+    } else {
+        int shallBeDetached = 0;
+        JNIEnv *jniEnv = NULL;
+        const char * errStr = strerror(errno);
+
+        fprintf(stderr, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s\n", dpy, e->error_code, errStr);
+
+        jniEnv = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
+        if(NULL==jniEnv) {
+            fprintf(stderr, "NEWT X11 Error: null JNIEnv");
+            return;
+        }
+
+        NewtCommon_throwNewRuntimeException(jniEnv, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s", 
+                                            dpy, e->error_code, errStr);
+
+        if (shallBeDetached) {
+            (*jvmHandle)->DetachCurrentThread(jvmHandle);
+        }
+    }
+
+    return 0;
+}
+
+void NewtDisplay_displayDispatchErrorHandlerEnable(int onoff, JNIEnv * env) {
+    if(onoff) {
+        if(NULL==origErrorHandler) {
+            setupJVMVars(env);
+            origErrorHandler = XSetErrorHandler(displayDispatchErrorHandler);
+        }
+    } else {
+        if(NULL!=origErrorHandler) {
+            XSetErrorHandler(origErrorHandler);
+            origErrorHandler = NULL;
+        }
+    }
+}
+
+/**
+ * Keycode
+ */
+
+#define IS_WITHIN(k,a,b) ((a)<=(k)&&(k)<=(b))
+
+static jint X11KeySym2NewtVKey(KeySym keySym) {
+    if(IS_WITHIN(keySym,XK_F1,XK_F12)) 
+        return (keySym-XK_F1)+J_VK_F1;
+    if(IS_WITHIN(keySym,XK_KP_0,XK_KP_9)) 
+        return (keySym-XK_KP_0)+J_VK_NUMPAD0;
+
+    switch(keySym) {
+        case XK_Return:
+        case XK_KP_Enter:
+            return J_VK_ENTER;
+        case XK_BackSpace:
+            return J_VK_BACK_SPACE;
+        case XK_Tab:
+        case XK_KP_Tab:
+        case XK_ISO_Left_Tab:
+            return J_VK_TAB;
+        case XK_Cancel:
+            return J_VK_CANCEL;
+        case XK_Clear:
+            return J_VK_CLEAR;
+        case XK_Shift_L:
+        case XK_Shift_R:
+            return J_VK_SHIFT;
+        case XK_Control_L:
+        case XK_Control_R:
+            return J_VK_CONTROL;
+        case XK_Alt_L:
+        case XK_Alt_R:
+            return J_VK_ALT;
+        case XK_Pause:
+            return J_VK_PAUSE;
+        case XK_Caps_Lock:
+            return J_VK_CAPS_LOCK;
+        case XK_Escape:
+            return J_VK_ESCAPE;
+        case XK_space:
+        case XK_KP_Space:
+            return J_VK_SPACE;
+        case XK_Page_Up:
+        case XK_KP_Page_Up:
+            return J_VK_PAGE_UP;
+        case XK_Page_Down:
+        case XK_KP_Page_Down:
+            return J_VK_PAGE_DOWN;
+        case XK_End:
+        case XK_KP_End:
+            return J_VK_END;
+        case XK_Home:
+        case XK_KP_Home:
+            return J_VK_HOME;
+        case XK_Left:
+        case XK_KP_Left:
+            return J_VK_LEFT;
+        case XK_Up:
+        case XK_KP_Up:
+            return J_VK_UP;
+        case XK_Right:
+        case XK_KP_Right:
+            return J_VK_RIGHT;
+        case XK_Down:
+        case XK_KP_Down:
+            return J_VK_DOWN;
+        case XK_KP_Multiply:
+            return J_VK_MULTIPLY;
+        case XK_KP_Add:
+            return J_VK_ADD;
+        case XK_KP_Separator:
+            return J_VK_SEPARATOR;
+        case XK_KP_Subtract:
+            return J_VK_SUBTRACT;
+        case XK_KP_Decimal:
+            return J_VK_DECIMAL;
+        case XK_KP_Divide:
+            return J_VK_DIVIDE;
+        case XK_Delete:
+        case XK_KP_Delete:
+            return J_VK_DELETE;
+        case XK_Num_Lock:
+            return J_VK_NUM_LOCK;
+        case XK_Scroll_Lock:
+            return J_VK_SCROLL_LOCK;
+        case XK_Print:
+            return J_VK_PRINTSCREEN;
+        case XK_Insert:
+        case XK_KP_Insert:
+            return J_VK_INSERT;
+        case XK_Help:
+            return J_VK_HELP;
+    }
+    return keySym;
+}
+
+static jint X11InputState2NewtModifiers(unsigned int xstate) {
+    jint modifiers = 0;
+    if ((ControlMask & xstate) != 0) {
+        modifiers |= EVENT_CTRL_MASK;
+    }
+    if ((ShiftMask & xstate) != 0) {
+        modifiers |= EVENT_SHIFT_MASK;
+    }
+    if ((Mod1Mask & xstate) != 0) {
+        modifiers |= EVENT_ALT_MASK;
+    }
+    if ((Button1Mask & xstate) != 0) {
+        modifiers |= EVENT_BUTTON1_MASK;
+    }
+    if ((Button2Mask & xstate) != 0) {
+        modifiers |= EVENT_BUTTON2_MASK;
+    }
+    if ((Button3Mask & xstate) != 0) {
+        modifiers |= EVENT_BUTTON3_MASK;
+    }
+
+    return modifiers;
+}
+
+
+/**
+ * Keycode
+ */
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Display
+ * Method:    initIDs
+ * Signature: (Z)Z
+ */
+JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0
+  (JNIEnv *env, jclass clazz)
+{
+    jclass c;
+
+    NewtCommon_init(env);
+
+    if(NULL==X11NewtWindowClazz) {
+        c = (*env)->FindClass(env, ClazzNameX11NewtWindow);
+        if(NULL==c) {
+            NewtCommon_FatalError(env, "NEWT X11Window: can't find %s", ClazzNameX11NewtWindow);
+        }
+        X11NewtWindowClazz = (jclass)(*env)->NewGlobalRef(env, c);
+        (*env)->DeleteLocalRef(env, c);
+        if(NULL==X11NewtWindowClazz) {
+            NewtCommon_FatalError(env, "NEWT X11Window: can't use %s", ClazzNameX11NewtWindow);
+        }
+    }
+
+    displayCompletedID = (*env)->GetMethodID(env, clazz, "displayCompleted", "(JJ)V");
+    insetsChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "insetsChanged", "(ZIIII)V");
+    sizeChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sizeChanged", "(ZIIZ)V");
+    positionChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "positionChanged", "(ZII)V");
+    focusChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "focusChanged", "(ZZ)V");
+    visibleChangedID = (*env)->GetMethodID(env, X11NewtWindowClazz, "visibleChanged", "(ZZ)V");
+    reparentNotifyID = (*env)->GetMethodID(env, X11NewtWindowClazz, "reparentNotify", "(J)V");
+    windowDestroyNotifyID = (*env)->GetMethodID(env, X11NewtWindowClazz, "windowDestroyNotify", "(Z)Z");
+    windowRepaintID = (*env)->GetMethodID(env, X11NewtWindowClazz, "windowRepaint", "(ZIIII)V");
+    enqueueMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "enqueueMouseEvent", "(ZIIIIII)V");
+    sendMouseEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sendMouseEvent", "(IIIIII)V");
+    enqueueKeyEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "enqueueKeyEvent", "(ZIIIC)V");
+    sendKeyEventID = (*env)->GetMethodID(env, X11NewtWindowClazz, "sendKeyEvent", "(IIIC)V");
+    requestFocusID = (*env)->GetMethodID(env, X11NewtWindowClazz, "requestFocus", "(Z)V");
+
+    if (displayCompletedID == NULL ||
+        insetsChangedID == NULL ||
+        sizeChangedID == NULL ||
+        positionChangedID == NULL ||
+        focusChangedID == NULL ||
+        visibleChangedID == NULL ||
+        reparentNotifyID == NULL ||
+        windowDestroyNotifyID == NULL ||
+        windowRepaintID == NULL ||
+        enqueueMouseEventID == NULL ||
+        sendMouseEventID == NULL ||
+        enqueueKeyEventID == NULL ||
+        sendKeyEventID == NULL ||
+        requestFocusID == NULL) {
+        return JNI_FALSE;
+    }
+
+
+    return JNI_TRUE;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Display
+ * Method:    CompleteDisplay
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_CompleteDisplay0
+  (JNIEnv *env, jobject obj, jlong display)
+{
+    Display * dpy = (Display *)(intptr_t)display;
+    jlong javaObjectAtom;
+    jlong windowDeleteAtom;
+
+    if(dpy==NULL) {
+        NewtCommon_FatalError(env, "invalid display connection..");
+    }
+
+    javaObjectAtom = (jlong) XInternAtom(dpy, "NEWT_JAVA_OBJECT", False);
+    if(None==javaObjectAtom) {
+        NewtCommon_throwNewRuntimeException(env, "could not create Atom NEWT_JAVA_OBJECT, bail out!");
+        return;
+    }
+
+    windowDeleteAtom = (jlong) XInternAtom(dpy, "WM_DELETE_WINDOW", False);
+    if(None==windowDeleteAtom) {
+        NewtCommon_throwNewRuntimeException(env, "could not create Atom WM_DELETE_WINDOW, bail out!");
+        return;
+    }
+
+    // XSetCloseDownMode(dpy, RetainTemporary); // Just a try ..
+
+    DBG_PRINT("X11: X11Display_completeDisplay dpy %p\n", dpy);
+
+    (*env)->CallVoidMethod(env, obj, displayCompletedID, javaObjectAtom, windowDeleteAtom);
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Display
+ * Method:    DisplayRelease0
+ * Signature: (JJJ)V
+ */
+JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DisplayRelease0
+  (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom)
+{
+    Display * dpy = (Display *)(intptr_t)display;
+    Atom wm_javaobject_atom = (Atom)javaObjectAtom;
+    Atom wm_delete_atom = (Atom)windowDeleteAtom;
+
+    if(dpy==NULL) {
+        NewtCommon_FatalError(env, "invalid display connection..");
+    }
+
+    // nothing to do to free the atoms !
+    (void) wm_javaobject_atom;
+    (void) wm_delete_atom;
+
+    XSync(dpy, True); // discard all pending events
+    DBG_PRINT("X11: X11Display_DisplayRelease dpy %p\n", dpy);
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Display
+ * Method:    DispatchMessages
+ * Signature: (JIJJ)V
+ */
+JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0
+  (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom)
+{
+    Display * dpy = (Display *) (intptr_t) display;
+    Atom wm_delete_atom = (Atom)windowDeleteAtom;
+    int num_events = 100;
+
+    if ( NULL == dpy ) {
+        return;
+    }
+
+    // Periodically take a break
+    while( num_events > 0 ) {
+        jobject jwindow = NULL;
+        XEvent evt;
+        KeySym keySym = 0;
+        jint modifiers = 0;
+        char keyChar = 0;
+        char text[255];
+
+        // XEventsQueued(dpy, X):
+        //   QueuedAlready                 : No I/O Flush or system call  doesn't work on some cards (eg ATI) ?) 
+        //   QueuedAfterFlush == XPending(): I/O Flush only if no already queued events are available
+        //   QueuedAfterReading            : QueuedAlready + if queue==0, attempt to read more ..
+        if ( 0 >= XPending(dpy) ) {
+            // DBG_PRINT( "X11: DispatchMessages 0x%X - Leave 1\n", dpy); 
+            return;
+        }
+
+        XNextEvent(dpy, &evt);
+        num_events--;
+
+        if( 0==evt.xany.window ) {
+            NewtCommon_throwNewRuntimeException(env, "event window NULL, bail out!");
+            return ;
+        }
+
+        if(dpy!=evt.xany.display) {
+            NewtCommon_throwNewRuntimeException(env, "wrong display, bail out!");
+            return ;
+        }
+
+        // DBG_PRINT( "X11: DispatchMessages dpy %p, win %p, Event %d\n", (void*)dpy, (void*)evt.xany.window, (int)evt.type);
+
+        NewtDisplay_displayDispatchErrorHandlerEnable(1, env);
+
+        jwindow = getJavaWindowProperty(env, dpy, evt.xany.window, javaObjectAtom,
+        #ifdef VERBOSE_ON
+                True
+        #else
+                False
+        #endif
+            );
+
+        NewtDisplay_displayDispatchErrorHandlerEnable(0, env);
+
+        if(NULL==jwindow) {
+            fprintf(stderr, "Warning: NEWT X11 DisplayDispatch %p, Couldn't handle event %d for X11 window %p\n", 
+                (void*)dpy, evt.type, (void*)evt.xany.window);
+            continue;
+        }
+ 
+        switch(evt.type) {
+            case KeyRelease:
+            case KeyPress:
+                if(XLookupString(&evt.xkey,text,255,&keySym,0)==1) {
+                    KeySym lower_return = 0, upper_return = 0;
+                    keyChar=text[0];
+                    XConvertCase(keySym, &lower_return, &upper_return);
+                    // always return upper case, set modifier masks (SHIFT, ..)
+                    keySym = X11KeySym2NewtVKey(upper_return);
+                } else {
+                    keyChar=0;
+                    keySym = X11KeySym2NewtVKey(keySym);
+                }
+                modifiers = X11InputState2NewtModifiers(evt.xkey.state);
+                break;
+
+            case ButtonPress:
+            case ButtonRelease:
+            case MotionNotify:
+                modifiers = X11InputState2NewtModifiers(evt.xbutton.state);
+                break;
+
+            default:
+                break;
+        }
+
+        switch(evt.type) {
+            case ButtonPress:
+                (*env)->CallVoidMethod(env, jwindow, requestFocusID, JNI_FALSE);
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_PRESSED, 
+                                      modifiers,
+                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_PRESSED, 
+                                      modifiers,
+                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
+                #endif
+                break;
+            case ButtonRelease:
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_RELEASED, 
+                                      modifiers,
+                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_RELEASED, 
+                                      modifiers,
+                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
+                #endif
+                break;
+            case MotionNotify:
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, 
+                                      modifiers,
+                                      (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); 
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_MOVED, 
+                                      modifiers,
+                                      (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); 
+                #endif
+                break;
+            case EnterNotify:
+                DBG_PRINT( "X11: event . EnterNotify call %p %d/%d\n", (void*)evt.xcrossing.window, evt.xcrossing.x, evt.xcrossing.y);
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_ENTERED, 
+                                      modifiers,
+                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_ENTERED, 
+                                      modifiers,
+                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
+                #endif
+                break;
+            case LeaveNotify:
+                DBG_PRINT( "X11: event . LeaveNotify call %p %d/%d\n", (void*)evt.xcrossing.window, evt.xcrossing.x, evt.xcrossing.y);
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_EXITED, 
+                                      modifiers,
+                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_EXITED, 
+                                      modifiers,
+                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
+                #endif
+                break;
+            case KeyPress:
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_PRESSED, 
+                                      modifiers, keySym, (jchar) -1);
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_PRESSED, 
+                                      modifiers, keySym, (jchar) -1);
+                #endif
+
+                break;
+            case KeyRelease:
+                #ifdef USE_SENDIO_DIRECT
+                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_RELEASED, 
+                                      modifiers, keySym, (jchar) -1);
+
+                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_TYPED, 
+                                      modifiers, keySym, (jchar) keyChar);
+                #else
+                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_RELEASED, 
+                                      modifiers, keySym, (jchar) -1);
+
+                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_TYPED, 
+                                      modifiers, keySym, (jchar) keyChar);
+                #endif
+
+                break;
+            case DestroyNotify:
+                DBG_PRINT( "X11: event . DestroyNotify call %p, parent %p, child-event: %d\n", 
+                    (void*)evt.xdestroywindow.window, (void*)evt.xdestroywindow.event, evt.xdestroywindow.window != evt.xdestroywindow.event);
+                if ( evt.xdestroywindow.window == evt.xdestroywindow.event ) {
+                    // ignore child destroy notification
+                }
+                break;
+            case CreateNotify:
+                DBG_PRINT( "X11: event . CreateNotify call %p, parent %p, child-event: 1\n", 
+                    (void*)evt.xcreatewindow.window, (void*) evt.xcreatewindow.parent);
+                break;
+            case ConfigureNotify:
+                DBG_PRINT( "X11: event . ConfigureNotify call %p (parent %p, above %p) %d/%d %dx%d %d, child-event: %d\n", 
+                            (void*)evt.xconfigure.window, (void*)evt.xconfigure.event, (void*)evt.xconfigure.above,
+                            evt.xconfigure.x, evt.xconfigure.y, evt.xconfigure.width, evt.xconfigure.height, 
+                            evt.xconfigure.override_redirect, evt.xconfigure.window != evt.xconfigure.event);
+                if ( evt.xconfigure.window == evt.xconfigure.event ) {
+                    // ignore child window change notification
+                    {
+                        // update insets
+                        int left, right, top, bottom;
+                        NewtWindows_updateInsets(env, jwindow, dpy, evt.xany.window, &left, &right, &top, &bottom);
+                    }
+                    (*env)->CallVoidMethod(env, jwindow, sizeChangedID, JNI_FALSE,
+                                            (jint) evt.xconfigure.width, (jint) evt.xconfigure.height, JNI_FALSE);
+                    (*env)->CallVoidMethod(env, jwindow, positionChangedID, JNI_FALSE,
+                                            (jint) evt.xconfigure.x, (jint) evt.xconfigure.y);
+                }
+                break;
+            case ClientMessage:
+                if (evt.xclient.send_event==True && evt.xclient.data.l[0]==wm_delete_atom) { // windowDeleteAtom
+                    jboolean closed;
+                    DBG_PRINT( "X11: event . ClientMessage call %p type 0x%X ..\n", 
+                        (void*)evt.xclient.window, (unsigned int)evt.xclient.message_type);
+                    closed = (*env)->CallBooleanMethod(env, jwindow, windowDestroyNotifyID, JNI_FALSE);
+                    DBG_PRINT( "X11: event . ClientMessage call %p type 0x%X, closed: %d\n", 
+                        (void*)evt.xclient.window, (unsigned int)evt.xclient.message_type, (int)closed);
+                    // Called by Window.java: CloseWindow(); 
+                    num_events = 0; // end loop in case of destroyed display
+                }
+                break;
+
+            case FocusIn:
+                DBG_PRINT( "X11: event . FocusIn call %p\n", (void*)evt.xvisibility.window);
+                (*env)->CallVoidMethod(env, jwindow, focusChangedID, JNI_FALSE, JNI_TRUE);
+                break;
+
+            case FocusOut:
+                DBG_PRINT( "X11: event . FocusOut call %p\n", (void*)evt.xvisibility.window);
+                (*env)->CallVoidMethod(env, jwindow, focusChangedID, JNI_FALSE, JNI_FALSE);
+                break;
+
+            case Expose:
+                DBG_PRINT( "X11: event . Expose call %p %d/%d %dx%d count %d\n", (void*)evt.xexpose.window,
+                    evt.xexpose.x, evt.xexpose.y, evt.xexpose.width, evt.xexpose.height, evt.xexpose.count);
+
+                if (evt.xexpose.count == 0 && evt.xexpose.width > 0 && evt.xexpose.height > 0) {
+                    (*env)->CallVoidMethod(env, jwindow, windowRepaintID, JNI_FALSE,
+                        evt.xexpose.x, evt.xexpose.y, evt.xexpose.width, evt.xexpose.height);
+                }
+                break;
+
+            case MapNotify:
+                DBG_PRINT( "X11: event . MapNotify call Event %p, Window %p, override_redirect %d, child-event: %d\n", 
+                    (void*)evt.xmap.event, (void*)evt.xmap.window, (int)evt.xmap.override_redirect,
+                    evt.xmap.event!=evt.xmap.window);
+                if( evt.xmap.event == evt.xmap.window ) {
+                    // ignore child window notification
+                    {
+                        // update insets
+                        int left, right, top, bottom;
+                        NewtWindows_updateInsets(env, jwindow, dpy, evt.xany.window, &left, &right, &top, &bottom);
+                    }
+                    (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_TRUE);
+                }
+                break;
+
+            case UnmapNotify:
+                DBG_PRINT( "X11: event . UnmapNotify call Event %p, Window %p, from_configure %d, child-event: %d\n", 
+                    (void*)evt.xunmap.event, (void*)evt.xunmap.window, (int)evt.xunmap.from_configure,
+                    evt.xunmap.event!=evt.xunmap.window);
+                if( evt.xunmap.event == evt.xunmap.window ) {
+                    // ignore child window notification
+                    (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_FALSE);
+                }
+                break;
+
+            case ReparentNotify:
+                {
+                    jlong parentResult; // 0 if root, otherwise proper value
+                    Window winRoot, winTopParent;
+                    #ifdef VERBOSE_ON
+                        Window oldParentRoot, oldParentTopParent;
+                        Window parentRoot, parentTopParent;
+                        if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.event, &oldParentRoot, &oldParentTopParent) ) {
+                            oldParentRoot=0; oldParentTopParent = 0;
+                        }
+                        if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.parent, &parentRoot, &parentTopParent) ) {
+                            parentRoot=0; parentTopParent = 0;
+                        }
+                    #endif
+                    if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.window, &winRoot, &winTopParent) ) {
+                        winRoot=0; winTopParent = 0;
+                    }
+                    if(evt.xreparent.parent == winRoot) {
+                        parentResult = 0; // our java indicator for root window
+                    } else {
+                        parentResult = (jlong) (intptr_t) evt.xreparent.parent;
+                    }
+                    #ifdef VERBOSE_ON
+                        DBG_PRINT( "X11: event . ReparentNotify: call %d/%d OldParent %p (root %p, top %p), NewParent %p (root %p, top %p), Window %p (root %p, top %p)\n", 
+                            evt.xreparent.x, evt.xreparent.y, 
+                            (void*)evt.xreparent.event, (void*)oldParentRoot, (void*)oldParentTopParent,
+                            (void*)evt.xreparent.parent, (void*)parentRoot, (void*)parentTopParent,
+                            (void*)evt.xreparent.window, (void*)winRoot, (void*)winTopParent);
+                    #endif
+                    (*env)->CallVoidMethod(env, jwindow, reparentNotifyID, (jlong)evt.xreparent.parent);
+                }
+                break;
+
+            // unhandled events .. yet ..
+
+            default:
+                DBG_PRINT("X11: event . unhandled %d 0x%X call %p\n", (int)evt.type, (unsigned int)evt.type, (void*)evt.xunmap.window);
+        }
+    }
+}
+
+
diff --git a/src/newt/native/X11Screen.c b/src/newt/native/X11Screen.c
new file mode 100644
index 0000000..698eed8
--- /dev/null
+++ b/src/newt/native/X11Screen.c
@@ -0,0 +1,491 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+// #define VERBOSE_ON 1
+// #define DBG_PERF 1
+
+#include "X11Common.h"
+
+#ifdef DBG_PERF
+    #include "timespec.h"
+#endif
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    GetScreen
+ * Signature: (JI)J
+ */
+JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_GetScreen0
+  (JNIEnv *env, jclass clazz, jlong display, jint screen_index)
+{
+    Display * dpy = (Display *)(intptr_t)display;
+    Screen  * scrn= NULL;
+
+    DBG_PRINT("X11: X11Screen_GetScreen0 dpy %p START\n", dpy);
+
+    if(dpy==NULL) {
+        NewtCommon_FatalError(env, "invalid display connection..");
+    }
+
+    scrn = ScreenOfDisplay(dpy, screen_index);
+    if(scrn==NULL) {
+        fprintf(stderr, "couldn't get screen idx %d\n", screen_index);
+    }
+    DBG_PRINT("X11: X11Screen_GetScreen0 idx %d -> scrn %p DONE\n", screen_index, scrn);
+    return (jlong) (intptr_t) scrn;
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getWidth0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
+{
+    Display * dpy = (Display *) (intptr_t) display;
+    return (jint) DisplayWidth( dpy, scrn_idx);
+}
+
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getHeight0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
+{
+    Display * dpy = (Display *) (intptr_t) display;
+    return (jint) DisplayHeight( dpy, scrn_idx);
+}
+
+static int showedRandRVersion = 0;
+
+static Bool NewtScreen_getRANDRVersion(Display *dpy, int *major, int *minor) {
+    if( 0 == XRRQueryVersion(dpy, major, minor) ) {
+        return False;
+    }
+    if(0 == showedRandRVersion) {
+        DBG_PRINT("X11 RandR Version %d.%d\n", *major, *minor);
+        showedRandRVersion = 1;
+    }
+    return True;
+}
+
+static Bool NewtScreen_hasRANDR(Display *dpy) {
+    int major, minor;
+    return NewtScreen_getRANDRVersion(dpy, &major, &minor);
+}
+
+static int NewtScreen_XRotation2Degree(JNIEnv *env, int xrotation) {
+    int rot;
+    if(xrotation == RR_Rotate_0) {
+      rot = 0;
+    }
+    else if(xrotation == RR_Rotate_90) {
+      rot = 90;
+    }
+    else if(xrotation == RR_Rotate_180) {
+      rot = 180;
+    }
+    else if(xrotation == RR_Rotate_270) {
+      rot = 270;
+    } else {
+      NewtCommon_throwNewRuntimeException(env, "invalid native rotation: %d", xrotation);
+    }
+    return rot;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getAvailableScreenModeRotations0
+ * Signature: (JI)I
+ */
+JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getAvailableScreenModeRotations0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    Window root = RootWindow(dpy, (int)scrn_idx);
+    int num_rotations = 0;
+    Rotation cur_rotation, rotations_supported;
+    int rotations[4];
+    int major, minor;
+
+    if(False == NewtScreen_getRANDRVersion(dpy, &major, &minor)) {
+        fprintf(stderr, "RANDR not available\n");
+        return (*env)->NewIntArray(env, 0);
+    }
+
+    rotations_supported = XRRRotations (dpy, (int)scrn_idx, &cur_rotation);
+
+    if(0 != (rotations_supported & RR_Rotate_0)) {
+      rotations[num_rotations++] = 0;
+    }
+    if(0 != (rotations_supported & RR_Rotate_90)) {
+      rotations[num_rotations++] = 90;
+    }
+    if(0 != (rotations_supported & RR_Rotate_180)) {
+      rotations[num_rotations++] = 180;
+    }
+    if(0 != (rotations_supported & RR_Rotate_270)) {
+      rotations[num_rotations++] = 270;
+    }
+    
+    jintArray properties = NULL;
+
+    if(num_rotations>0) {
+        properties = (*env)->NewIntArray(env, num_rotations);
+        if (properties == NULL) {
+            NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", num_rotations);
+        }
+        
+        // move from the temp structure to the java structure
+        (*env)->SetIntArrayRegion(env, properties, 0, num_rotations, rotations);
+    }
+        
+    return properties;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getNumScreenModeResolution0
+ * Signature: (JI)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+#ifdef DBG_PERF
+    struct timespec t0, t1, td;
+    long td_ms;
+    timespec_now(&t0);
+#endif
+    
+    if(False == NewtScreen_hasRANDR(dpy)) {
+        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0: RANDR not available\n");
+        return 0;
+    }
+
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "X11Screen_getNumScreenModeResolution0.1: %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    int num_sizes;   
+    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
+    
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "X11Screen_getNumScreenModeResolution0.2 (XRRSizes): %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    DBG_PRINT("getNumScreenModeResolutions0: %p:%d -> %d\n", dpy, (int)scrn_idx, num_sizes);
+
+    return num_sizes;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getScreenModeResolutions0
+ * Signature: (JII)[I
+ */
+JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    
+    if(False == NewtScreen_hasRANDR(dpy)) {
+        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0: RANDR not available\n");
+        return (*env)->NewIntArray(env, 0);
+    }
+
+    int num_sizes;   
+    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
+
+    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
+        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
+    }
+ 
+    // Fill the properties in temp jint array
+    int propIndex = 0;
+    jint prop[4];
+    
+    prop[propIndex++] = xrrs[(int)resMode_idx].width; 
+    prop[propIndex++] = xrrs[(int)resMode_idx].height;
+    prop[propIndex++] = xrrs[(int)resMode_idx].mwidth; 
+    prop[propIndex++] = xrrs[(int)resMode_idx].mheight;
+    
+    jintArray properties = (*env)->NewIntArray(env, 4);
+    if (properties == NULL) {
+        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", 4);
+    }
+    
+    // move from the temp structure to the java structure
+    (*env)->SetIntArrayRegion(env, properties, 0, 4, prop);
+    
+    return properties;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getScreenModeRates0
+ * Signature: (JII)[I
+ */
+JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0
+  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    
+    if(False == NewtScreen_hasRANDR(dpy)) {
+        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0: RANDR not available\n");
+        return (*env)->NewIntArray(env, 0);
+    }
+
+    int num_sizes;   
+    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
+
+    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
+        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
+    }
+ 
+    int num_rates;
+    short *rates = XRRRates(dpy, (int)scrn_idx, (int)resMode_idx, &num_rates);
+ 
+    jint prop[num_rates];
+    int i;
+    for(i=0; i<num_rates; i++) {
+        prop[i] = (int) rates[i];
+        /** fprintf(stderr, "rate[%d, %d, %d/%d]: %d\n", (int)scrn_idx, resMode_idx, i, num_rates, prop[i]); */
+    }
+    
+    jintArray properties = (*env)->NewIntArray(env, num_rates);
+    if (properties == NULL) {
+        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", num_rates);
+    }
+    
+    // move from the temp structure to the java structure
+    (*env)->SetIntArrayRegion(env, properties, 0, num_rates, prop);
+    
+    return properties;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getScreenConfiguration0
+ * Signature: (JI)J
+ */
+JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenConfiguration0
+  (JNIEnv *env, jclass clazz, jlong display, jint screen_idx) 
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    Window root = RootWindow(dpy, (int)screen_idx);
+#ifdef DBG_PERF
+    struct timespec t0, t1, td;
+    long td_ms;
+    timespec_now(&t0);
+#endif
+
+    if(False == NewtScreen_hasRANDR(dpy)) {
+        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenConfiguration0: RANDR not available\n");
+        return 0;
+    }
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "X11Screen_getScreenConfiguration0.1: %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    // get current resolutions and frequencies
+    XRRScreenConfiguration  *conf = XRRGetScreenInfo(dpy, root);
+#ifdef DBG_PERF
+    timespec_now(&t1); timespec_subtract(&td, &t1, &t0); td_ms = timespec_milliseconds(&td);
+    fprintf(stderr, "X11Screen_getScreenConfiguration0.2 (XRRGetScreenInfo): %ld ms\n", td_ms); fflush(NULL);
+#endif
+
+    return (jlong) (intptr_t) conf;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    freeScreenConfiguration0
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Screen_freeScreenConfiguration0
+  (JNIEnv *env, jclass clazz, jlong screenConfiguration) 
+{
+    XRRFreeScreenConfigInfo( (XRRScreenConfiguration *) (intptr_t) screenConfiguration );
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getCurrentScreenRate0
+ * Signature: (J)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRate0
+  (JNIEnv *env, jclass clazz, jlong screenConfiguration) 
+{
+    XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration;
+    
+    short original_rate = XRRConfigCurrentRate(conf);
+    DBG_PRINT("getCurrentScreenRate0: %d\n", (int)original_rate);
+
+    return (jint) original_rate;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getCurrentScreenRotation0
+ * Signature: (J)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRotation0
+  (JNIEnv *env, jclass clazz, jlong screenConfiguration)
+{
+    XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration;
+    Rotation rotation;
+
+    XRRConfigCurrentConfiguration(conf, &rotation);
+
+    return NewtScreen_XRotation2Degree(env, rotation);
+}
+
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    getCurrentScreenResolutionIndex0
+ * Signature: (J)I
+ */
+JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenResolutionIndex0
+  (JNIEnv *env, jclass clazz, jlong screenConfiguration)
+{
+   XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration;
+  
+   short original_rate = XRRConfigCurrentRate(conf);
+   
+   Rotation original_rotation;
+   SizeID original_size_id = XRRConfigCurrentConfiguration(conf, &original_rotation);
+   
+   DBG_PRINT("getCurrentScreenResolutionIndex0: %d\n", (int)original_size_id);
+   return (jint)original_size_id; 
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    setCurrentScreenModeStart0
+ * Signature: (JIJIII)Z
+ */
+JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModeStart0
+  (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jlong screenConfiguration, jint resMode_idx, jint freq, jint rotation)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    XRRScreenConfiguration *conf = (XRRScreenConfiguration *) (intptr_t) screenConfiguration;
+    Window root = RootWindow(dpy, (int)screen_idx);
+
+    int num_sizes;   
+    XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions
+    int rot;
+    
+    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
+        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
+    }
+
+    switch(rotation) {
+        case   0:
+            rot = RR_Rotate_0; 
+            break;
+        case  90:
+            rot = RR_Rotate_90; 
+            break;
+        case 180:
+            rot = RR_Rotate_180; 
+            break;
+        case 270:
+            rot = RR_Rotate_270; 
+            break;
+        default:
+            NewtCommon_throwNewRuntimeException(env, "Invalid rotation: %d", rotation);
+    }
+    
+    DBG_PRINT("X11Screen.setCurrentScreenMode0: CHANGED TO %d: %d x %d PIXELS, %d Hz, %d degree\n", 
+        resMode_idx, xrrs[resMode_idx].width, xrrs[resMode_idx].height, (int)freq, rotation);
+
+    XRRSelectInput (dpy, root, RRScreenChangeNotifyMask);
+
+    XSync(dpy, False);
+    XRRSetScreenConfigAndRate(dpy, conf, root, (int)resMode_idx, rot, (short)freq, CurrentTime);   
+    XSync(dpy, False);
+
+    return JNI_TRUE;
+}
+
+/*
+ * Class:     jogamp_newt_driver_x11_X11Screen
+ * Method:    setCurrentScreenModePollEnd0
+ * Signature: (J)Z
+ */
+JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0
+  (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation)
+{
+    Display *dpy = (Display *) (intptr_t) display;
+    int randr_event_base, randr_error_base;
+    XEvent evt;
+    XRRScreenChangeNotifyEvent * scn_event = (XRRScreenChangeNotifyEvent *) &evt;
+
+    if(False == NewtScreen_hasRANDR(dpy)) {
+        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0: RANDR not available\n");
+        return JNI_FALSE;
+    }
+
+    int num_sizes;   
+    XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions
+    XRRScreenConfiguration *conf;
+    
+    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
+        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
+    }
+
+    XRRQueryExtension(dpy, &randr_event_base, &randr_error_base);
+
+    int done = 0;
+    int rot;
+    do {
+        if ( 0 >= XEventsQueued(dpy, QueuedAfterFlush) ) {
+            return;
+        }
+        XNextEvent(dpy, &evt);
+
+        switch (evt.type - randr_event_base) {
+            case RRScreenChangeNotify:
+                rot = NewtScreen_XRotation2Degree(env, (int)scn_event->rotation);
+                DBG_PRINT( "XRANDR: event . RRScreenChangeNotify call %p (root %p) resIdx %d rot %d %dx%d\n", 
+                            (void*)scn_event->window, (void*)scn_event->root, 
+                            (int)scn_event->size_index, rot, 
+                            scn_event->width, scn_event->height);
+                // done = scn_event->size_index == resMode_idx; // not reliable ..
+                done = rot == rotation && 
+                       scn_event->width == xrrs[resMode_idx].width && 
+                       scn_event->height == xrrs[resMode_idx].height;
+                break;
+            default:
+                DBG_PRINT("RANDR: event . unhandled %d 0x%X call %p\n", (int)evt.type, (int)evt.type, (void*)evt.xany.window);
+        }
+        XRRUpdateConfiguration(&evt);
+    } while(!done);
+
+    XSync(dpy, False);
+
+}
+
diff --git a/src/newt/native/X11Window.c b/src/newt/native/X11Window.c
index 3613f00..0f93b3e 100644
--- a/src/newt/native/X11Window.c
+++ b/src/newt/native/X11Window.c
@@ -32,40 +32,9 @@
  * 
  */
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-
-#include <gluegen_stdint.h>
-
-#include <unistd.h>
-#include <errno.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/keysym.h>
-#include <X11/Xatom.h>
-
-#include <X11/extensions/Xrandr.h>
-
-#include "jogamp_newt_driver_x11_X11Screen.h"
-#include "jogamp_newt_driver_x11_X11Display.h"
-#include "jogamp_newt_driver_x11_X11Window.h"
-
-#include "Window.h"
-#include "MouseEvent.h"
-#include "InputEvent.h"
-#include "KeyEvent.h"
-#include "WindowEvent.h"
-#include "ScreenMode.h"
-
-#include "NewtCommon.h"
-
-// #define VERBOSE_ON 1
+#include "X11Common.h"
 
 #ifdef VERBOSE_ON
-    #define DBG_PRINT(...) fprintf(stderr, __VA_ARGS__); fflush(stderr) 
-
     #define DUMP_VISUAL_INFO(a,b) _dumpVisualInfo((a),(b))
 
     static void _dumpVisualInfo(const char * msg, XVisualInfo *pVisualQuery) {
@@ -90,315 +59,12 @@
 
 #else
 
-    #define DBG_PRINT(...)
-
     #define DUMP_VISUAL_INFO(a,b)
 
 #endif
 
-/**
- * Keycode
- */
-
-#define IS_WITHIN(k,a,b) ((a)<=(k)&&(k)<=(b))
-
-static jint X11KeySym2NewtVKey(KeySym keySym) {
-    if(IS_WITHIN(keySym,XK_F1,XK_F12)) 
-        return (keySym-XK_F1)+J_VK_F1;
-    if(IS_WITHIN(keySym,XK_KP_0,XK_KP_9)) 
-        return (keySym-XK_KP_0)+J_VK_NUMPAD0;
-
-    switch(keySym) {
-        case XK_Return:
-        case XK_KP_Enter:
-            return J_VK_ENTER;
-        case XK_BackSpace:
-            return J_VK_BACK_SPACE;
-        case XK_Tab:
-        case XK_KP_Tab:
-        case XK_ISO_Left_Tab:
-            return J_VK_TAB;
-        case XK_Cancel:
-            return J_VK_CANCEL;
-        case XK_Clear:
-            return J_VK_CLEAR;
-        case XK_Shift_L:
-        case XK_Shift_R:
-            return J_VK_SHIFT;
-        case XK_Control_L:
-        case XK_Control_R:
-            return J_VK_CONTROL;
-        case XK_Alt_L:
-        case XK_Alt_R:
-            return J_VK_ALT;
-        case XK_Pause:
-            return J_VK_PAUSE;
-        case XK_Caps_Lock:
-            return J_VK_CAPS_LOCK;
-        case XK_Escape:
-            return J_VK_ESCAPE;
-        case XK_space:
-        case XK_KP_Space:
-            return J_VK_SPACE;
-        case XK_Page_Up:
-        case XK_KP_Page_Up:
-            return J_VK_PAGE_UP;
-        case XK_Page_Down:
-        case XK_KP_Page_Down:
-            return J_VK_PAGE_DOWN;
-        case XK_End:
-        case XK_KP_End:
-            return J_VK_END;
-        case XK_Home:
-        case XK_KP_Home:
-            return J_VK_HOME;
-        case XK_Left:
-        case XK_KP_Left:
-            return J_VK_LEFT;
-        case XK_Up:
-        case XK_KP_Up:
-            return J_VK_UP;
-        case XK_Right:
-        case XK_KP_Right:
-            return J_VK_RIGHT;
-        case XK_Down:
-        case XK_KP_Down:
-            return J_VK_DOWN;
-        case XK_KP_Multiply:
-            return J_VK_MULTIPLY;
-        case XK_KP_Add:
-            return J_VK_ADD;
-        case XK_KP_Separator:
-            return J_VK_SEPARATOR;
-        case XK_KP_Subtract:
-            return J_VK_SUBTRACT;
-        case XK_KP_Decimal:
-            return J_VK_DECIMAL;
-        case XK_KP_Divide:
-            return J_VK_DIVIDE;
-        case XK_Delete:
-        case XK_KP_Delete:
-            return J_VK_DELETE;
-        case XK_Num_Lock:
-            return J_VK_NUM_LOCK;
-        case XK_Scroll_Lock:
-            return J_VK_SCROLL_LOCK;
-        case XK_Print:
-            return J_VK_PRINTSCREEN;
-        case XK_Insert:
-        case XK_KP_Insert:
-            return J_VK_INSERT;
-        case XK_Help:
-            return J_VK_HELP;
-    }
-    return keySym;
-}
-
-static jint X11InputState2NewtModifiers(unsigned int xstate) {
-    jint modifiers = 0;
-    if ((ControlMask & xstate) != 0) {
-        modifiers |= EVENT_CTRL_MASK;
-    }
-    if ((ShiftMask & xstate) != 0) {
-        modifiers |= EVENT_SHIFT_MASK;
-    }
-    if ((Mod1Mask & xstate) != 0) {
-        modifiers |= EVENT_ALT_MASK;
-    }
-    if ((Button1Mask & xstate) != 0) {
-        modifiers |= EVENT_BUTTON1_MASK;
-    }
-    if ((Button2Mask & xstate) != 0) {
-        modifiers |= EVENT_BUTTON2_MASK;
-    }
-    if ((Button3Mask & xstate) != 0) {
-        modifiers |= EVENT_BUTTON3_MASK;
-    }
-
-    return modifiers;
-}
-
 #define X11_MOUSE_EVENT_MASK (ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask)
 
-static const char * const ClazzNameNewtWindow = "com/jogamp/newt/Window";
-
-static jclass    newtWindowClz=NULL;
-
-static jmethodID insetsChangedID = NULL;
-static jmethodID sizeChangedID = NULL;
-static jmethodID positionChangedID = NULL;
-static jmethodID focusChangedID = NULL;
-static jmethodID visibleChangedID = NULL;
-static jmethodID reparentNotifyID = NULL;
-static jmethodID windowDestroyNotifyID = NULL;
-static jmethodID windowRepaintID = NULL;
-static jmethodID enqueueMouseEventID = NULL;
-static jmethodID sendMouseEventID = NULL;
-static jmethodID enqueueKeyEventID = NULL;
-static jmethodID sendKeyEventID = NULL;
-static jmethodID requestFocusID = NULL;
-
-static jmethodID displayCompletedID = NULL;
-
-
-/**
- * Display
- */
-
-static JavaVM *jvmHandle = NULL;
-static int jvmVersion = 0;
-
-static void setupJVMVars(JNIEnv * env) {
-    if(0 != (*env)->GetJavaVM(env, &jvmHandle)) {
-        jvmHandle = NULL;
-    }
-    jvmVersion = (*env)->GetVersion(env);
-}
-
-static XErrorHandler origErrorHandler = NULL ;
-
-static int displayDispatchErrorHandler(Display *dpy, XErrorEvent *e)
-{
-    fprintf(stderr, "Warning: NEWT X11 Error: DisplayDispatch %p, Code 0x%X, errno %s\n", dpy, e->error_code, strerror(errno));
-    
-    if (e->error_code == BadAtom) {
-        fprintf(stderr, "         BadAtom (%p): Atom probably already removed\n", (void*)e->resourceid);
-    } else if (e->error_code == BadWindow) {
-        fprintf(stderr, "         BadWindow (%p): Window probably already removed\n", (void*)e->resourceid);
-    } else {
-        int shallBeDetached = 0;
-        JNIEnv *jniEnv = NULL;
-        const char * errStr = strerror(errno);
-
-        fprintf(stderr, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s\n", dpy, e->error_code, errStr);
-
-        jniEnv = NewtCommon_GetJNIEnv(jvmHandle, jvmVersion, &shallBeDetached);
-        if(NULL==jniEnv) {
-            fprintf(stderr, "NEWT X11 Error: null JNIEnv");
-            return;
-        }
-
-        NewtCommon_throwNewRuntimeException(jniEnv, "Info: NEWT X11 Error: Display %p, Code 0x%X, errno %s", 
-                                            dpy, e->error_code, errStr);
-
-        if (shallBeDetached) {
-            (*jvmHandle)->DetachCurrentThread(jvmHandle);
-        }
-    }
-
-    return 0;
-}
-
-static void displayDispatchErrorHandlerEnable(int onoff, JNIEnv * env) {
-    if(onoff) {
-        if(NULL==origErrorHandler) {
-            setupJVMVars(env);
-            origErrorHandler = XSetErrorHandler(displayDispatchErrorHandler);
-        }
-    } else {
-        if(NULL!=origErrorHandler) {
-            XSetErrorHandler(origErrorHandler);
-            origErrorHandler = NULL;
-        }
-    }
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Display
- * Method:    initIDs
- * Signature: (Z)Z
- */
-JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Display_initIDs0
-  (JNIEnv *env, jclass clazz)
-{
-    jclass c;
-
-    NewtCommon_init(env);
-
-    displayCompletedID = (*env)->GetMethodID(env, clazz, "displayCompleted", "(JJ)V");
-    if (displayCompletedID == NULL) {
-        return JNI_FALSE;
-    }
-
-    if(NULL==newtWindowClz) {
-        c = (*env)->FindClass(env, ClazzNameNewtWindow);
-        if(NULL==c) {
-            NewtCommon_FatalError(env, "NEWT X11Window: can't find %s", ClazzNameNewtWindow);
-        }
-        newtWindowClz = (jclass)(*env)->NewGlobalRef(env, c);
-        (*env)->DeleteLocalRef(env, c);
-        if(NULL==newtWindowClz) {
-            NewtCommon_FatalError(env, "NEWT X11Window: can't use %s", ClazzNameNewtWindow);
-        }
-    }
-
-    return JNI_TRUE;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Display
- * Method:    CompleteDisplay
- * Signature: (J)V
- */
-JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_CompleteDisplay0
-  (JNIEnv *env, jobject obj, jlong display)
-{
-    Display * dpy = (Display *)(intptr_t)display;
-    jlong javaObjectAtom;
-    jlong windowDeleteAtom;
-
-    if(dpy==NULL) {
-        NewtCommon_FatalError(env, "invalid display connection..");
-    }
-
-    javaObjectAtom = (jlong) XInternAtom(dpy, "NEWT_JAVA_OBJECT", False);
-    if(None==javaObjectAtom) {
-        NewtCommon_throwNewRuntimeException(env, "could not create Atom NEWT_JAVA_OBJECT, bail out!");
-        return;
-    }
-
-    windowDeleteAtom = (jlong) XInternAtom(dpy, "WM_DELETE_WINDOW", False);
-    if(None==windowDeleteAtom) {
-        NewtCommon_throwNewRuntimeException(env, "could not create Atom WM_DELETE_WINDOW, bail out!");
-        return;
-    }
-
-    // XSetCloseDownMode(dpy, RetainTemporary); // Just a try ..
-
-    DBG_PRINT("X11: X11Display_completeDisplay dpy %p\n", dpy);
-
-    (*env)->CallVoidMethod(env, obj, displayCompletedID, javaObjectAtom, windowDeleteAtom);
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Display
- * Method:    DisplayRelease0
- * Signature: (JJJ)V
- */
-JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DisplayRelease0
-  (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom)
-{
-    Display * dpy = (Display *)(intptr_t)display;
-    Atom wm_javaobject_atom = (Atom)javaObjectAtom;
-    Atom wm_delete_atom = (Atom)windowDeleteAtom;
-
-    if(dpy==NULL) {
-        NewtCommon_FatalError(env, "invalid display connection..");
-    }
-
-    // nothing to do to free the atoms !
-    (void) wm_javaobject_atom;
-    (void) wm_delete_atom;
-
-    XSync(dpy, True); // discard all pending events
-    DBG_PRINT("X11: X11Display_DisplayRelease dpy %p\n", dpy);
-}
-
-
-/**
- * Window
- */
-
 static int putPtrIn32Long(unsigned long * dst, uintptr_t src) {
     int i=0;
         dst[i++] = (unsigned long) ( ( src >>  0 ) & 0xFFFFFFFF ) ;
@@ -431,7 +97,7 @@ static void setJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlon
                                      (unsigned char *)&jogl_java_object_data, nitems_32);
 }
 
-static jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning) {
+jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, jlong javaObjectAtom, Bool showWarning) {
     Atom actual_type;
     int actual_format;
     int nitems_32 = ( sizeof(uintptr_t) == 8 ) ? 2 : 1 ;
@@ -469,7 +135,7 @@ static jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, j
     XFree(jogl_java_object_data_pp);
 
 #ifdef VERBOSE_ON
-    if(JNI_FALSE == (*env)->IsInstanceOf(env, jwindow, newtWindowClz)) {
+    if(JNI_FALSE == (*env)->IsInstanceOf(env, jwindow, X11NewtWindowClazz)) {
         NewtCommon_throwNewRuntimeException(env, "fetched Atom NEWT_JAVA_OBJECT window is not a NEWT Window: javaWindow 0x%X !", jwindow);
     }
 #endif
@@ -477,7 +143,7 @@ static jobject getJavaWindowProperty(JNIEnv *env, Display *dpy, Window window, j
 }
 
 /** @return zero if fails, non zero if OK */
-static Status NewtWindows_getRootAndParent (Display *dpy, Window w, Window * root_return, Window * parent_return) {
+Status NewtWindows_getRootAndParent (Display *dpy, Window w, Window * root_return, Window * parent_return) {
     Window *children_return=NULL;
     unsigned int nchildren_return=0;
 
@@ -503,16 +169,21 @@ static Window NewtWindows_getParent (Display *dpy, Window w) {
     }
     return 0; // Error
 }
-static Status NewtWindows_getParentPosition (Display *dpy, Window w, int *x_return, int *y_return) {
+static void NewtWindows_setCWAbove(Display *dpy, Window w) {
+    XWindowChanges xwc;
+    memset(&xwc, 0, sizeof(XWindowChanges));
+    xwc.stack_mode = Above;
+    XConfigureWindow(dpy, w, CWStackMode, &xwc);
+    XSync(dpy, False);
+}
+static Status NewtWindows_getWindowPositionRelative2Parent (Display *dpy, Window w, int *x_return, int *y_return) {
     Window root_return;
     unsigned int width_return, height_return;
     unsigned int border_width_return;
     unsigned int depth_return;
-    Window parent = NewtWindows_getParent(dpy, w);
 
-    if(0 != parent) {
-        XGetGeometry(dpy, parent, &root_return, x_return, y_return, &width_return, 
-                               &height_return, &border_width_return, &depth_return);
+    if(0 !=  XGetGeometry(dpy, w, &root_return, x_return, y_return, &width_return, 
+                                  &height_return, &border_width_return, &depth_return)) {
         return 1; // OK
     }
     return 0; // Error
@@ -558,52 +229,6 @@ static Status NewtWindows_getFrameExtends(Display *dpy, Window window, int *left
 
     return 1; // Ok
 }
-static Status NewtWindows_updateInsets(JNIEnv *env, jobject jwindow, Display *dpy, Window window, int *left, int *right, int *top, int *bottom) {
-    if(0 != NewtWindows_getFrameExtends(dpy, window, left, right, top, bottom)) {
-        DBG_PRINT( "NewtWindows_updateInsets: insets by _NET_FRAME_EXTENTS [ l %d, r %d, t %d, b %d ]\n",
-            *left, *right, *top, *bottom);
-        (*env)->CallVoidMethod(env, jwindow, insetsChangedID, JNI_FALSE, *left, *right, *top, *bottom);
-        return 1; // OK
-    } else if(0 != NewtWindows_getParentPosition (dpy, window, left, top)) {
-        *right = *left; *bottom = *left;
-        DBG_PRINT( "NewtWindows_updateInsets: insets by parent position [ l %d, r %d, t %d, b %d ]\n",
-            *left, *right, *top, *bottom);
-        (*env)->CallVoidMethod(env, jwindow, insetsChangedID, JNI_FALSE, *left, *right, *top, *bottom);
-        return 1; // OK
-    }
-    return 0; // Error
-}
-
-static void NewtWindows_setCWAbove(Display *dpy, Window w) {
-    XWindowChanges xwc;
-    memset(&xwc, 0, sizeof(XWindowChanges));
-    xwc.stack_mode = Above;
-    XConfigureWindow(dpy, w, CWStackMode, &xwc);
-    XSync(dpy, False);
-}
-
-static void NewtWindows_requestFocus (JNIEnv *env, jobject window, Display *dpy, Window w, jboolean force) {
-    XWindowAttributes xwa;
-    Window focus_return;
-    int revert_to_return;
-
-    XGetInputFocus(dpy, &focus_return, &revert_to_return);
-    DBG_PRINT( "X11: requestFocus dpy %p,win %p, force %d, hasFocus %d\n", dpy, (void*)w, force, focus_return==w);
-
-    if( JNI_TRUE==force || focus_return!=w) {
-        DBG_PRINT( "X11: XRaiseWindow dpy %p, win %p\n", dpy, (void*)w);
-        XRaiseWindow(dpy, w);
-        NewtWindows_setCWAbove(dpy, w);
-        // Avoid 'BadMatch' errors from XSetInputFocus, ie if window is not viewable
-        XGetWindowAttributes(dpy, w, &xwa);
-        if(xwa.map_state == IsViewable) {
-            DBG_PRINT( "X11: XSetInputFocus dpy %p,win %pd\n", dpy, (void*)w);
-            XSetInputFocus(dpy, w, RevertToParent, CurrentTime);
-        }
-    }
-    DBG_PRINT( "X11: requestFocus dpy %p,win %p, force %d - FIN\n", dpy, (void*)w, force);
-    XSync(dpy, False);
-}
 
 #define DECOR_USE_MWM 1     // works for known WMs
 // #define DECOR_USE_EWMH 1 // haven't seen this to work (NORMAL->POPUP, never gets undecorated)
@@ -641,6 +266,29 @@ static void NewtWindows_setDecorations (Display *dpy, Window w, Bool decorated)
     XSync(dpy, False);
 }
 
+static Bool NewtWindows_hasDecorations (Display *dpy, Window w) {
+    Bool decor = False;
+
+#ifdef DECOR_USE_MWM
+    Atom _MOTIF_WM_HINTS = XInternAtom( dpy, "_MOTIF_WM_HINTS", False );
+    unsigned char *wm_data;
+    Atom wm_type;
+    int wm_format;
+    unsigned long wm_nitems, wm_bytes_after;
+ 
+    if( Success == XGetWindowProperty(dpy, w, _MOTIF_WM_HINTS, 0, PROP_MWM_HINTS_ELEMENTS, False, AnyPropertyType, 
+                                      &wm_type, &wm_format, &wm_nitems, &wm_bytes_after, &wm_data) ) {
+        if(wm_type != None) {
+            // unsigned long mwmhints[PROP_MWM_HINTS_ELEMENTS] = { MWM_HINTS_DECORATIONS, 0, decorated, 0, 0 }; // flags, functions, decorations, input_mode, status
+            unsigned long *hints = (unsigned long *) wm_data;
+            decor = ( 0 != (hints[0] & MWM_HINTS_DECORATIONS) ) && ( 0 != hints[2] );
+        }
+    }
+#endif
+
+    return decor;
+}
+
 static void NewtWindows_setNormalWindowEWMH (Display *dpy, Window w) {
     Atom _NET_WM_WINDOW_TYPE = XInternAtom( dpy, "_NET_WM_WINDOW_TYPE", False );
     Atom types[1]={0};
@@ -764,751 +412,54 @@ static Bool NewtWindows_setFullscreenEWMH (Display *dpy, Window root, Window w,
     return res;
 }
 
-#define USE_SENDIO_DIRECT 1
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Display
- * Method:    DispatchMessages
- * Signature: (JIJJ)V
- */
-JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Display_DispatchMessages0
-  (JNIEnv *env, jobject obj, jlong display, jlong javaObjectAtom, jlong windowDeleteAtom)
-{
-    Display * dpy = (Display *) (intptr_t) display;
-    Atom wm_delete_atom = (Atom)windowDeleteAtom;
-    int num_events = 100;
-
-    if ( NULL == dpy ) {
-        return;
-    }
-
-    // Periodically take a break
-    while( num_events > 0 ) {
-        jobject jwindow = NULL;
-        XEvent evt;
-        KeySym keySym = 0;
-        jint modifiers = 0;
-        char keyChar = 0;
-        char text[255];
-
-        // XEventsQueued(dpy, X):
-        //   QueuedAlready                 : No I/O Flush or system call  doesn't work on some cards (eg ATI) ?) 
-        //   QueuedAfterFlush == XPending(): I/O Flush only if no already queued events are available
-        //   QueuedAfterReading            : QueuedAlready + if queue==0, attempt to read more ..
-        if ( 0 >= XPending(dpy) ) {
-            // DBG_PRINT( "X11: DispatchMessages 0x%X - Leave 1\n", dpy); 
-            return;
-        }
-
-        XNextEvent(dpy, &evt);
-        num_events--;
-
-        if( 0==evt.xany.window ) {
-            NewtCommon_throwNewRuntimeException(env, "event window NULL, bail out!");
-            return ;
-        }
-
-        if(dpy!=evt.xany.display) {
-            NewtCommon_throwNewRuntimeException(env, "wrong display, bail out!");
-            return ;
-        }
-
-        // DBG_PRINT( "X11: DispatchMessages dpy %p, win %p, Event %d\n", (void*)dpy, (void*)evt.xany.window, (int)evt.type);
-
-        displayDispatchErrorHandlerEnable(1, env);
-
-        jwindow = getJavaWindowProperty(env, dpy, evt.xany.window, javaObjectAtom,
-        #ifdef VERBOSE_ON
-                True
-        #else
-                False
-        #endif
-            );
-
-        displayDispatchErrorHandlerEnable(0, env);
 
-        if(NULL==jwindow) {
-            fprintf(stderr, "Warning: NEWT X11 DisplayDispatch %p, Couldn't handle event %d for X11 window %p\n", 
-                (void*)dpy, evt.type, (void*)evt.xany.window);
-            continue;
-        }
- 
-        switch(evt.type) {
-            case KeyRelease:
-            case KeyPress:
-                if(XLookupString(&evt.xkey,text,255,&keySym,0)==1) {
-                    KeySym lower_return = 0, upper_return = 0;
-                    keyChar=text[0];
-                    XConvertCase(keySym, &lower_return, &upper_return);
-                    // always return upper case, set modifier masks (SHIFT, ..)
-                    keySym = X11KeySym2NewtVKey(upper_return);
-                } else {
-                    keyChar=0;
-                    keySym = X11KeySym2NewtVKey(keySym);
-                }
-                modifiers = X11InputState2NewtModifiers(evt.xkey.state);
-                break;
-
-            case ButtonPress:
-            case ButtonRelease:
-            case MotionNotify:
-                modifiers = X11InputState2NewtModifiers(evt.xbutton.state);
-                break;
-
-            default:
-                break;
-        }
-
-        switch(evt.type) {
-            case ButtonPress:
-                (*env)->CallVoidMethod(env, jwindow, requestFocusID, JNI_FALSE);
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_PRESSED, 
-                                      modifiers,
-                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_PRESSED, 
-                                      modifiers,
-                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
-                #endif
-                break;
-            case ButtonRelease:
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_RELEASED, 
-                                      modifiers,
-                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_RELEASED, 
-                                      modifiers,
-                                      (jint) evt.xbutton.x, (jint) evt.xbutton.y, (jint) evt.xbutton.button, 0 /*rotation*/);
-                #endif
-                break;
-            case MotionNotify:
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_MOVED, 
-                                      modifiers,
-                                      (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); 
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_MOVED, 
-                                      modifiers,
-                                      (jint) evt.xmotion.x, (jint) evt.xmotion.y, (jint) 0, 0 /*rotation*/); 
-                #endif
-                break;
-            case EnterNotify:
-                DBG_PRINT( "X11: event . EnterNotify call %p %d/%d\n", (void*)evt.xcrossing.window, evt.xcrossing.x, evt.xcrossing.y);
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_ENTERED, 
-                                      modifiers,
-                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_ENTERED, 
-                                      modifiers,
-                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
-                #endif
-                break;
-            case LeaveNotify:
-                DBG_PRINT( "X11: event . LeaveNotify call %p %d/%d\n", (void*)evt.xcrossing.window, evt.xcrossing.x, evt.xcrossing.y);
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendMouseEventID, (jint) EVENT_MOUSE_EXITED, 
-                                      modifiers,
-                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueMouseEventID, JNI_FALSE, (jint) EVENT_MOUSE_EXITED, 
-                                      modifiers,
-                                      (jint) evt.xcrossing.x, (jint) evt.xcrossing.y, (jint) 0, 0 /*rotation*/); 
-                #endif
-                break;
-            case KeyPress:
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_PRESSED, 
-                                      modifiers, keySym, (jchar) -1);
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_PRESSED, 
-                                      modifiers, keySym, (jchar) -1);
-                #endif
-
-                break;
-            case KeyRelease:
-                #ifdef USE_SENDIO_DIRECT
-                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_RELEASED, 
-                                      modifiers, keySym, (jchar) -1);
-
-                (*env)->CallVoidMethod(env, jwindow, sendKeyEventID, (jint) EVENT_KEY_TYPED, 
-                                      modifiers, keySym, (jchar) keyChar);
-                #else
-                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_RELEASED, 
-                                      modifiers, keySym, (jchar) -1);
-
-                (*env)->CallVoidMethod(env, jwindow, enqueueKeyEventID, JNI_FALSE, (jint) EVENT_KEY_TYPED, 
-                                      modifiers, keySym, (jchar) keyChar);
-                #endif
-
-                break;
-            case DestroyNotify:
-                DBG_PRINT( "X11: event . DestroyNotify call %p, parent %p, child-event: %d\n", 
-                    (void*)evt.xdestroywindow.window, (void*)evt.xdestroywindow.event, evt.xdestroywindow.window != evt.xdestroywindow.event);
-                if ( evt.xdestroywindow.window == evt.xdestroywindow.event ) {
-                    // ignore child destroy notification
-                }
-                break;
-            case CreateNotify:
-                DBG_PRINT( "X11: event . CreateNotify call %p, parent %p, child-event: 1\n", 
-                    (void*)evt.xcreatewindow.window, (void*) evt.xcreatewindow.parent);
-                break;
-            case ConfigureNotify:
-                DBG_PRINT( "X11: event . ConfigureNotify call %p (parent %p, above %p) %d/%d %dx%d %d, child-event: %d\n", 
-                            (void*)evt.xconfigure.window, (void*)evt.xconfigure.event, (void*)evt.xconfigure.above,
-                            evt.xconfigure.x, evt.xconfigure.y, evt.xconfigure.width, evt.xconfigure.height, 
-                            evt.xconfigure.override_redirect, evt.xconfigure.window != evt.xconfigure.event);
-                if ( evt.xconfigure.window == evt.xconfigure.event ) {
-                    // ignore child window change notification
-                    {
-                        // update insets
-                        int left, right, top, bottom;
-                        NewtWindows_updateInsets(env, jwindow, dpy, evt.xany.window, &left, &right, &top, &bottom);
-                    }
-                    (*env)->CallVoidMethod(env, jwindow, sizeChangedID, JNI_FALSE,
-                                            (jint) evt.xconfigure.width, (jint) evt.xconfigure.height, JNI_FALSE);
-                    (*env)->CallVoidMethod(env, jwindow, positionChangedID, JNI_FALSE,
-                                            (jint) evt.xconfigure.x, (jint) evt.xconfigure.y);
-                }
-                break;
-            case ClientMessage:
-                if (evt.xclient.send_event==True && evt.xclient.data.l[0]==wm_delete_atom) { // windowDeleteAtom
-                    DBG_PRINT( "X11: event . ClientMessage call %p type 0x%X !!!\n", 
-                        (void*)evt.xclient.window, (unsigned int)evt.xclient.message_type);
-                    (*env)->CallVoidMethod(env, jwindow, windowDestroyNotifyID);
-                    // Called by Window.java: CloseWindow(); 
-                    num_events = 0; // end loop in case of destroyed display
-                }
-                break;
-
-            case FocusIn:
-                DBG_PRINT( "X11: event . FocusIn call %p\n", (void*)evt.xvisibility.window);
-                (*env)->CallVoidMethod(env, jwindow, focusChangedID, JNI_FALSE, JNI_TRUE);
-                break;
-
-            case FocusOut:
-                DBG_PRINT( "X11: event . FocusOut call %p\n", (void*)evt.xvisibility.window);
-                (*env)->CallVoidMethod(env, jwindow, focusChangedID, JNI_FALSE, JNI_FALSE);
-                break;
-
-            case Expose:
-                DBG_PRINT( "X11: event . Expose call %p %d/%d %dx%d count %d\n", (void*)evt.xexpose.window,
-                    evt.xexpose.x, evt.xexpose.y, evt.xexpose.width, evt.xexpose.height, evt.xexpose.count);
-
-                if (evt.xexpose.count == 0 && evt.xexpose.width > 0 && evt.xexpose.height > 0) {
-                    (*env)->CallVoidMethod(env, jwindow, windowRepaintID, JNI_FALSE,
-                        evt.xexpose.x, evt.xexpose.y, evt.xexpose.width, evt.xexpose.height);
-                }
-                break;
-
-            case MapNotify:
-                DBG_PRINT( "X11: event . MapNotify call Event %p, Window %p, override_redirect %d, child-event: %d\n", 
-                    (void*)evt.xmap.event, (void*)evt.xmap.window, (int)evt.xmap.override_redirect,
-                    evt.xmap.event!=evt.xmap.window);
-                if( evt.xmap.event == evt.xmap.window ) {
-                    // ignore child window notification
-                    {
-                        // update insets
-                        int left, right, top, bottom;
-                        NewtWindows_updateInsets(env, jwindow, dpy, evt.xany.window, &left, &right, &top, &bottom);
-                    }
-                    (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_TRUE);
-                }
-                break;
-
-            case UnmapNotify:
-                DBG_PRINT( "X11: event . UnmapNotify call Event %p, Window %p, from_configure %d, child-event: %d\n", 
-                    (void*)evt.xunmap.event, (void*)evt.xunmap.window, (int)evt.xunmap.from_configure,
-                    evt.xunmap.event!=evt.xunmap.window);
-                if( evt.xunmap.event == evt.xunmap.window ) {
-                    // ignore child window notification
-                    (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_FALSE);
-                }
-                break;
-
-            case ReparentNotify:
-                {
-                    jlong parentResult; // 0 if root, otherwise proper value
-                    Window winRoot, winTopParent;
-                    #ifdef VERBOSE_ON
-                        Window oldParentRoot, oldParentTopParent;
-                        Window parentRoot, parentTopParent;
-                        if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.event, &oldParentRoot, &oldParentTopParent) ) {
-                            oldParentRoot=0; oldParentTopParent = 0;
-                        }
-                        if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.parent, &parentRoot, &parentTopParent) ) {
-                            parentRoot=0; parentTopParent = 0;
-                        }
-                    #endif
-                    if( 0 == NewtWindows_getRootAndParent(dpy, evt.xreparent.window, &winRoot, &winTopParent) ) {
-                        winRoot=0; winTopParent = 0;
-                    }
-                    if(evt.xreparent.parent == winRoot) {
-                        parentResult = 0; // our java indicator for root window
-                    } else {
-                        parentResult = (jlong) (intptr_t) evt.xreparent.parent;
-                    }
-                    #ifdef VERBOSE_ON
-                        DBG_PRINT( "X11: event . ReparentNotify: call %d/%d OldParent %p (root %p, top %p), NewParent %p (root %p, top %p), Window %p (root %p, top %p)\n", 
-                            evt.xreparent.x, evt.xreparent.y, 
-                            (void*)evt.xreparent.event, (void*)oldParentRoot, (void*)oldParentTopParent,
-                            (void*)evt.xreparent.parent, (void*)parentRoot, (void*)parentTopParent,
-                            (void*)evt.xreparent.window, (void*)winRoot, (void*)winTopParent);
-                    #endif
-                    (*env)->CallVoidMethod(env, jwindow, reparentNotifyID, (jlong)evt.xreparent.parent);
-                }
-                break;
-
-            // unhandled events .. yet ..
-
-            default:
-                DBG_PRINT("X11: event . unhandled %d 0x%X call %p\n", (int)evt.type, (unsigned int)evt.type, (void*)evt.xunmap.window);
-        }
-    }
-}
-
-
-/**
- * Screen
- */
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    GetScreen
- * Signature: (JI)J
- */
-JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Screen_GetScreen0
-  (JNIEnv *env, jclass clazz, jlong display, jint screen_index)
-{
-    Display * dpy = (Display *)(intptr_t)display;
-    Screen  * scrn= NULL;
-
-    DBG_PRINT("X11: X11Screen_GetScreen0 dpy %p START\n", dpy);
-
-    if(dpy==NULL) {
-        NewtCommon_FatalError(env, "invalid display connection..");
-    }
-
-    scrn = ScreenOfDisplay(dpy, screen_index);
-    if(scrn==NULL) {
-        fprintf(stderr, "couldn't get screen idx %d\n", screen_index);
-    }
-    DBG_PRINT("X11: X11Screen_GetScreen0 idx %d -> scrn %p DONE\n", screen_index, scrn);
-    return (jlong) (intptr_t) scrn;
-}
-
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getWidth0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-    Display * dpy = (Display *) (intptr_t) display;
-    return (jint) XDisplayWidth( dpy, scrn_idx);
-}
-
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getHeight0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-    Display * dpy = (Display *) (intptr_t) display;
-    return (jint) XDisplayHeight( dpy, scrn_idx);
-}
-
-
-static Bool NewtScreen_getRANDRVersion(Display *dpy, int *major, int *minor) {
-    if( 0 == XRRQueryVersion(dpy, major, minor) ) {
-        return False;
-    }
-    return True;
-}
-
-static Bool NewtScreen_hasRANDR(Display *dpy) {
-    int major, minor;
-    return NewtScreen_getRANDRVersion(dpy, &major, &minor);
-}
-
-static int NewtScreen_XRotation2Degree(JNIEnv *env, int xrotation) {
-    int rot;
-    if(xrotation == RR_Rotate_0) {
-      rot = 0;
-    }
-    else if(xrotation == RR_Rotate_90) {
-      rot = 90;
-    }
-    else if(xrotation == RR_Rotate_180) {
-      rot = 180;
-    }
-    else if(xrotation == RR_Rotate_270) {
-      rot = 270;
-    } else {
-      NewtCommon_throwNewRuntimeException(env, "invalid native rotation: %d", xrotation);
-    }
-    return rot;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getAvailableScreenModeRotations0
- * Signature: (JI)I
- */
-JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getAvailableScreenModeRotations0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    int num_rotations = 0;
-    Rotation cur_rotation, rotations_supported;
-    int rotations[4];
-    int major, minor;
-
-    if(False == NewtScreen_getRANDRVersion(dpy, &major, &minor)) {
-        fprintf(stderr, "RANDR not available\n");
-        return (*env)->NewIntArray(env, 0);
-    }
-
-    rotations_supported = XRRRotations (dpy, (int)scrn_idx, &cur_rotation);
-
-    if(0 != (rotations_supported & RR_Rotate_0)) {
-      rotations[num_rotations++] = 0;
-    }
-    if(0 != (rotations_supported & RR_Rotate_90)) {
-      rotations[num_rotations++] = 90;
-    }
-    if(0 != (rotations_supported & RR_Rotate_180)) {
-      rotations[num_rotations++] = 180;
-    }
-    if(0 != (rotations_supported & RR_Rotate_270)) {
-      rotations[num_rotations++] = 270;
+Status NewtWindows_updateInsets(JNIEnv *env, jobject jwindow, Display *dpy, Window window, int *left, int *right, int *top, int *bottom) {
+    if(0 != NewtWindows_getFrameExtends(dpy, window, left, right, top, bottom)) {
+        DBG_PRINT( "NewtWindows_updateInsets: insets by _NET_FRAME_EXTENTS [ l %d, r %d, t %d, b %d ]\n",
+            *left, *right, *top, *bottom);
+        (*env)->CallVoidMethod(env, jwindow, insetsChangedID, JNI_FALSE, *left, *right, *top, *bottom);
+        return 1; // OK
     }
-    
-    jintArray properties = NULL;
 
-    if(num_rotations>0) {
-        properties = (*env)->NewIntArray(env, num_rotations);
-        if (properties == NULL) {
-            NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", num_rotations);
+    Bool hasDecor = NewtWindows_hasDecorations (dpy, window);
+    if(hasDecor) {
+        // The following logic only works if window is top-level _and_ the WM
+        // has 'decorated' our client window w/ another parent window _within_ the actual 'framed' window.
+        Window parent = NewtWindows_getParent(dpy, window);
+        if(0 != NewtWindows_getWindowPositionRelative2Parent (dpy, parent, left, top)) {
+            *right = *left; *bottom = *top;
+            DBG_PRINT( "NewtWindows_updateInsets: insets by parent position [ l %d, r %d, t %d, b %d ]\n",
+                *left, *right, *top, *bottom);
+            (*env)->CallVoidMethod(env, jwindow, insetsChangedID, JNI_FALSE, *left, *right, *top, *bottom);
+            return 1; // OK
         }
-        
-        // move from the temp structure to the java structure
-        (*env)->SetIntArrayRegion(env, properties, 0, num_rotations, rotations);
-    }
-        
-    return properties;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getNumScreenModeResolution0
- * Signature: (JI)I
- */
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getNumScreenModeResolutions0: RANDR not available\n");
-        return 0;
-    }
-
-    int num_sizes;   
-    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
-    
-    DBG_PRINT("getNumScreenModeResolutions0: %d\n", num_sizes);
-
-    return num_sizes;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getScreenModeResolutions0
- * Signature: (JII)[I
- */
-JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeResolution0: RANDR not available\n");
-        return (*env)->NewIntArray(env, 0);
-    }
-
-    int num_sizes;   
-    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
-
-    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
-        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
-    }
- 
-    // Fill the properties in temp jint array
-    int propIndex = 0;
-    jint prop[4];
-    
-    prop[propIndex++] = xrrs[(int)resMode_idx].width; 
-    prop[propIndex++] = xrrs[(int)resMode_idx].height;
-    prop[propIndex++] = xrrs[(int)resMode_idx].mwidth; 
-    prop[propIndex++] = xrrs[(int)resMode_idx].mheight;
-    
-    jintArray properties = (*env)->NewIntArray(env, 4);
-    if (properties == NULL) {
-        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", 4);
-    }
-    
-    // move from the temp structure to the java structure
-    (*env)->SetIntArrayRegion(env, properties, 0, 4, prop);
-    
-    return properties;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getScreenModeRates0
- * Signature: (JII)[I
- */
-JNIEXPORT jintArray JNICALL Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx, jint resMode_idx)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getScreenModeRates0: RANDR not available\n");
-        return (*env)->NewIntArray(env, 0);
-    }
-
-    int num_sizes;   
-    XRRScreenSize *xrrs = XRRSizes(dpy, (int)scrn_idx, &num_sizes); //get possible screen resolutions
-
-    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
-        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
     }
- 
-    int num_rates;
-    short *rates = XRRRates(dpy, (int)scrn_idx, (int)resMode_idx, &num_rates);
- 
-    jint prop[num_rates];
-    int i;
-    for(i=0; i<num_rates; i++) {
-        prop[i] = (int) rates[i];
-        /** fprintf(stderr, "rate[%d, %d, %d/%d]: %d\n", (int)scrn_idx, resMode_idx, i, num_rates, prop[i]); */
-    }
-    
-    jintArray properties = (*env)->NewIntArray(env, num_rates);
-    if (properties == NULL) {
-        NewtCommon_throwNewRuntimeException(env, "Could not allocate int array of size %d", num_rates);
-    }
-    
-    // move from the temp structure to the java structure
-    (*env)->SetIntArrayRegion(env, properties, 0, num_rates, prop);
-    
-    return properties;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getCurrentScreenRate0
- * Signature: (JI)I
- */
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRate0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx) 
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRate0: RANDR not available\n");
-        return -1;
-    }
-
-    // get current resolutions and frequencies
-    XRRScreenConfiguration  *conf = XRRGetScreenInfo(dpy, root);
-    short original_rate = XRRConfigCurrentRate(conf);
-
-    //free
-    XRRFreeScreenConfigInfo(conf);
-    
-    DBG_PRINT("getCurrentScreenRate0: %d\n", (int)original_rate);
-
-    return (jint) original_rate;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getCurrentScreenRotation0
- * Signature: (JI)I
- */
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRotation0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)scrn_idx);
-    
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenRotation0: RANDR not available\n");
-        return -1;
-    }
-
-    //get current resolutions and frequencies
-    XRRScreenConfiguration  *conf = XRRGetScreenInfo(dpy, root);
-    
-    Rotation rotation;
-    XRRConfigCurrentConfiguration(conf, &rotation);
-
-    //free
-    XRRFreeScreenConfigInfo(conf);
-    
-    return NewtScreen_XRotation2Degree(env, rotation);
-}
-
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    getCurrentScreenResolutionIndex0
- * Signature: (JI)I
- */
-JNIEXPORT jint JNICALL Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenResolutionIndex0
-  (JNIEnv *env, jclass clazz, jlong display, jint scrn_idx)
-{
-   Display *dpy = (Display *) (intptr_t) display;
-   Window root = RootWindow(dpy, (int)scrn_idx);
-  
-   if(False == NewtScreen_hasRANDR(dpy)) {
-       DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_getCurrentScreenResolutionIndex0: RANDR not available\n");
-       return -1;
-   }
-
-   // get current resolutions and frequency configuration
-   XRRScreenConfiguration  *conf = XRRGetScreenInfo(dpy, root);
-   short original_rate = XRRConfigCurrentRate(conf);
-   
-   Rotation original_rotation;
-   SizeID original_size_id = XRRConfigCurrentConfiguration(conf, &original_rotation);
-   
-   //free
-   XRRFreeScreenConfigInfo(conf);
-   
-   DBG_PRINT("getCurrentScreenResolutionIndex0: %d\n", (int)original_size_id);
-   return (jint)original_size_id;   
+    DBG_PRINT( "NewtWindows_updateInsets: cannot determine insets - hasDecor %d\n", hasDecor);
+    return 0; // Error
 }
 
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    setCurrentScreenModeStart0
- * Signature: (JIIII)Z
- */
-JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModeStart0
-  (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    Window root = RootWindow(dpy, (int)screen_idx);
-
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModeStart0: RANDR not available\n");
-        return JNI_FALSE;
-    }
-
-    int num_sizes;   
-    XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions
-    XRRScreenConfiguration *conf;
-    int rot;
-    
-    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
-        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
-    }
-
-    conf = XRRGetScreenInfo(dpy, root);
-   
-    switch(rotation) {
-        case   0:
-            rot = RR_Rotate_0; 
-            break;
-        case  90:
-            rot = RR_Rotate_90; 
-            break;
-        case 180:
-            rot = RR_Rotate_180; 
-            break;
-        case 270:
-            rot = RR_Rotate_270; 
-            break;
-        default:
-            NewtCommon_throwNewRuntimeException(env, "Invalid rotation: %d", rotation);
-    }
-    
-    DBG_PRINT("X11Screen.setCurrentScreenMode0: CHANGED TO %d: %d x %d PIXELS, %d Hz, %d degree\n", 
-        resMode_idx, xrrs[resMode_idx].width, xrrs[resMode_idx].height, (int)freq, rotation);
-
-    XRRSelectInput (dpy, root, RRScreenChangeNotifyMask);
-
-    XSync(dpy, False);
-    XRRSetScreenConfigAndRate(dpy, conf, root, (int)resMode_idx, rot, (short)freq, CurrentTime);   
-    XSync(dpy, False);
+static void NewtWindows_requestFocus (JNIEnv *env, jobject window, Display *dpy, Window w, jboolean force) {
+    XWindowAttributes xwa;
+    Window focus_return;
+    int revert_to_return;
 
-    //free
-    XRRFreeScreenConfigInfo(conf);
     XSync(dpy, False);
+    XGetInputFocus(dpy, &focus_return, &revert_to_return);
+    DBG_PRINT( "X11: requestFocus dpy %p,win %p, force %d, hasFocus %d\n", dpy, (void*)w, force, focus_return==w);
 
-    return JNI_TRUE;
-}
-
-/*
- * Class:     jogamp_newt_driver_x11_X11Screen
- * Method:    setCurrentScreenModePollEnd0
- * Signature: (J)Z
- */
-JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0
-  (JNIEnv *env, jclass clazz, jlong display, jint screen_idx, jint resMode_idx, jint freq, jint rotation)
-{
-    Display *dpy = (Display *) (intptr_t) display;
-    int randr_event_base, randr_error_base;
-    XEvent evt;
-    XRRScreenChangeNotifyEvent * scn_event = (XRRScreenChangeNotifyEvent *) &evt;
-
-    if(False == NewtScreen_hasRANDR(dpy)) {
-        DBG_PRINT("Java_jogamp_newt_driver_x11_X11Screen_setCurrentScreenModePollEnd0: RANDR not available\n");
-        return JNI_FALSE;
-    }
-
-    int num_sizes;   
-    XRRScreenSize *xrrs = XRRSizes(dpy, (int)screen_idx, &num_sizes); //get possible screen resolutions
-    XRRScreenConfiguration *conf;
-    
-    if( 0 > resMode_idx || resMode_idx >= num_sizes ) {
-        NewtCommon_throwNewRuntimeException(env, "Invalid resolution index: ! 0 < %d < %d", resMode_idx, num_sizes);
-    }
-
-    XRRQueryExtension(dpy, &randr_event_base, &randr_error_base);
-
-    int done = 0;
-    int rot;
-    do {
-        if ( 0 >= XEventsQueued(dpy, QueuedAfterFlush) ) {
-            return;
-        }
-        XNextEvent(dpy, &evt);
-
-        switch (evt.type - randr_event_base) {
-            case RRScreenChangeNotify:
-                rot = NewtScreen_XRotation2Degree(env, (int)scn_event->rotation);
-                DBG_PRINT( "XRANDR: event . RRScreenChangeNotify call %p (root %p) resIdx %d rot %d %dx%d\n", 
-                            (void*)scn_event->window, (void*)scn_event->root, 
-                            (int)scn_event->size_index, rot, 
-                            scn_event->width, scn_event->height);
-                // done = scn_event->size_index == resMode_idx; // not reliable ..
-                done = rot == rotation && 
-                       scn_event->width == xrrs[resMode_idx].width && 
-                       scn_event->height == xrrs[resMode_idx].height;
-                break;
-            default:
-                DBG_PRINT("RANDR: event . unhandled %d 0x%X call %p\n", (int)evt.type, (int)evt.type, (void*)evt.xany.window);
+    if( JNI_TRUE==force || focus_return!=w) {
+        DBG_PRINT( "X11: XRaiseWindow dpy %p, win %p\n", dpy, (void*)w);
+        XRaiseWindow(dpy, w);
+        NewtWindows_setCWAbove(dpy, w);
+        // Avoid 'BadMatch' errors from XSetInputFocus, ie if window is not viewable
+        XGetWindowAttributes(dpy, w, &xwa);
+        DBG_PRINT( "X11: XSetInputFocus dpy %p,win %p, isViewable %d\n", dpy, (void*)w, (xwa.map_state == IsViewable));
+        if(xwa.map_state == IsViewable) {
+            XSetInputFocus(dpy, w, RevertToParent, CurrentTime);
         }
-        XRRUpdateConfiguration(&evt);
-    } while(!done);
-
+    }
+    DBG_PRINT( "X11: requestFocus dpy %p,win %p, force %d - FIN\n", dpy, (void*)w, force);
     XSync(dpy, False);
-
 }
 
 /**
@@ -1523,35 +474,6 @@ JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Screen_setCurrentScree
 JNIEXPORT jboolean JNICALL Java_jogamp_newt_driver_x11_X11Window_initIDs0
   (JNIEnv *env, jclass clazz)
 {
-    insetsChangedID = (*env)->GetMethodID(env, clazz, "insetsChanged", "(ZIIII)V");
-    sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZIIZ)V");
-    positionChangedID = (*env)->GetMethodID(env, clazz, "positionChanged", "(ZII)V");
-    focusChangedID = (*env)->GetMethodID(env, clazz, "focusChanged", "(ZZ)V");
-    visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(ZZ)V");
-    reparentNotifyID = (*env)->GetMethodID(env, clazz, "reparentNotify", "(J)V");
-    windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "()V");
-    windowRepaintID = (*env)->GetMethodID(env, clazz, "windowRepaint", "(ZIIII)V");
-    enqueueMouseEventID = (*env)->GetMethodID(env, clazz, "enqueueMouseEvent", "(ZIIIIII)V");
-    sendMouseEventID = (*env)->GetMethodID(env, clazz, "sendMouseEvent", "(IIIIII)V");
-    enqueueKeyEventID = (*env)->GetMethodID(env, clazz, "enqueueKeyEvent", "(ZIIIC)V");
-    sendKeyEventID = (*env)->GetMethodID(env, clazz, "sendKeyEvent", "(IIIC)V");
-    requestFocusID = (*env)->GetMethodID(env, clazz, "requestFocus", "(Z)V");
-
-    if (insetsChangedID == NULL ||
-        sizeChangedID == NULL ||
-        positionChangedID == NULL ||
-        focusChangedID == NULL ||
-        visibleChangedID == NULL ||
-        reparentNotifyID == NULL ||
-        windowDestroyNotifyID == NULL ||
-        windowRepaintID == NULL ||
-        enqueueMouseEventID == NULL ||
-        sendMouseEventID == NULL ||
-        enqueueKeyEventID == NULL ||
-        sendKeyEventID == NULL ||
-        requestFocusID == NULL) {
-        return JNI_FALSE;
-    }
     return JNI_TRUE;
 }
 
@@ -1566,14 +488,12 @@ static Bool WaitForUnmapNotify( Display *dpy, XEvent *event, XPointer arg ) {
 static void NewtWindows_setPosSize(Display *dpy, Window w, jint x, jint y, jint width, jint height) {
     if(width>0 && height>0 || x>=0 && y>=0) { // resize/position if requested
         XWindowChanges xwc;
-        int flags = 0;
+        int flags = CWX | CWY;
 
         memset(&xwc, 0, sizeof(XWindowChanges));
-        if(0<=x && 0<=y) {
-            flags |= CWX | CWY;
-            xwc.x=x;
-            xwc.y=y;
-        }
+        xwc.x=x;
+        xwc.y=y;
+
         if(0<width && 0<height) {
             flags |= CWWidth | CWHeight;
             xwc.width=width;
@@ -1587,13 +507,12 @@ static void NewtWindows_setPosSize(Display *dpy, Window w, jint x, jint y, jint
 /*
  * Class:     jogamp_newt_driver_x11_X11Window
  * Method:    CreateWindow
- * Signature: (JJIJIIII)J
  */
 JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0
   (JNIEnv *env, jobject obj, jlong parent, jlong display, jint screen_index, 
-                             jlong visualID, 
+                             jint visualID, 
                              jlong javaObjectAtom, jlong windowDeleteAtom, 
-                             jint x, jint y, jint width, jint height, int flags)
+                             jint x, jint y, jint width, jint height, jboolean autoPosition, int flags)
 {
     Display * dpy = (Display *)(intptr_t)display;
     Atom wm_delete_atom = (Atom)windowDeleteAtom;
@@ -1629,29 +548,27 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0
     if(0==windowParent) {
         windowParent = root;
     }
-    DBG_PRINT( "X11: CreateWindow dpy %p, parent %p, %x/%d %dx%d, undeco %d, alwaysOnTop %d\n", 
-        (void*)dpy, (void*)windowParent, x, y, width, height,
-        TST_FLAG_IS_UNDECORATED(flags), TST_FLAG_IS_ALWAYSONTOP(flags));
+    DBG_PRINT( "X11: CreateWindow dpy %p, screen %d, visualID 0x%X, parent %p, %d/%d %dx%d, undeco %d, alwaysOnTop %d, autoPosition %d\n", 
+        (void*)dpy, scrn_idx, (int)visualID, (void*)windowParent, x, y, width, height,
+        TST_FLAG_IS_UNDECORATED(flags), TST_FLAG_IS_ALWAYSONTOP(flags), autoPosition);
 
     // try given VisualID on screen
     memset(&visualTemplate, 0, sizeof(XVisualInfo));
     visualTemplate.screen = scrn_idx;
     visualTemplate.visualid = (VisualID)visualID;
     pVisualQuery = XGetVisualInfo(dpy, VisualIDMask|VisualScreenMask, &visualTemplate,&n);
-    DUMP_VISUAL_INFO("Given VisualID,ScreenIdx", pVisualQuery);
+    DUMP_VISUAL_INFO("Given VisualID", pVisualQuery);
     if(pVisualQuery!=NULL) {
         visual   = pVisualQuery->visual;
         depth    = pVisualQuery->depth;
-        visualID = (jlong)pVisualQuery->visualid;
+        visualID = (jint)pVisualQuery->visualid;
         XFree(pVisualQuery);
         pVisualQuery=NULL;
     }
-    DBG_PRINT( "X11: [CreateWindow] trying given (dpy %p, screen %d, visualID: %d, parent %p) found: %p\n", 
-        dpy, scrn_idx, (int)visualID, (void*)windowParent, visual);
+    DBG_PRINT( "X11: [CreateWindow] found visual: %p\n", visual);
 
-    if (visual==NULL)
-    { 
-        NewtCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID, bail out!");
+    if (visual==NULL) { 
+        NewtCommon_throwNewRuntimeException(env, "could not query Visual by given VisualID 0x%X, bail out!", (int)visualID);
         return 0;
     } 
 
@@ -1681,7 +598,7 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0
 
     {
         int _x = x, _y = y; // pos for CreateWindow, might be tweaked
-        if(0>_x || 0>_y) {
+        if(JNI_TRUE == autoPosition) {
             // user didn't requested specific position, use WM default
             _x = 0;
             _y = 0;
@@ -1714,29 +631,28 @@ JNIEXPORT jlong JNICALL Java_jogamp_newt_driver_x11_X11Window_CreateWindow0
     // we can pre-map the window here to be able to gather the insets and position.
     {
         XEvent event;
-        int left, right, top, bottom;
-        Bool userPos = 0<=x && 0<=y ;
+        int left=0, right=0, top=0, bottom=0;
 
         XMapWindow(dpy, window);
         XIfEvent( dpy, &event, WaitForMapNotify, (XPointer) window ); // wait to get proper insets values
 
+        XSync(dpy, False);
+
         // send insets before visibility, allowing java code a proper sync point!
         NewtWindows_updateInsets(env, jwindow, dpy, window, &left, &right, &top, &bottom);
         (*env)->CallVoidMethod(env, jwindow, visibleChangedID, JNI_FALSE, JNI_TRUE);
 
-        if(!userPos) {
+        if(JNI_TRUE == autoPosition) {
             // get position from WM
             int dest_x, dest_y;
             Window child;
             XTranslateCoordinates(dpy, window, windowParent, 0, 0, &dest_x, &dest_y, &child);
             x = (int)dest_x; y = (int)dest_y;
         }
-        DBG_PRINT("X11: [CreateWindow]: client: %d/%d %dx%d (is user-pos %d)\n", x, y, width, height, userPos);
+        DBG_PRINT("X11: [CreateWindow]: client: %d/%d %dx%d (autoPosition %d)\n", x, y, width, height, autoPosition);
 
         x -= left; // top-level
         y -= top;  // top-level
-        if(0>x) { x = 0; }
-        if(0>y) { y = 0; }
         DBG_PRINT("X11: [CreateWindow]: top-level: %d/%d\n", x, y);
         NewtWindows_setPosSize(dpy, window, x, y, width, height);
 
@@ -1799,17 +715,28 @@ static Bool WaitForReparentNotify( Display *dpy, XEvent *event, XPointer arg ) {
 }
 #endif
 
+/**
+ * KDE cause lost input focus in fullscreen mode.
+ * Using 'XGrabKeyboard(..)' would prevent the loss,
+ * but also would disable WM task switcher etc.
+ *
+ * #define FS_GRAB_KEYBOARD 1
+ *
+ */
+
 /*
  * Class:     jogamp_newt_driver_x11_X11Window
  * Method:    reconfigureWindow0
  * Signature: (JIJJIIIII)V
  */
 JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
-  (JNIEnv *env, jobject obj, jlong jdisplay, jint screen_index, jlong jparent, jlong jwindow, 
+  (JNIEnv *env, jobject obj, jlong jdisplay, jint screen_index,
+   jlong jparent, jlong jwindow, jlong windowDeleteAtom,
    jint x, jint y, jint width, jint height, jint flags)
 {
     Display * dpy = (Display *) (intptr_t) jdisplay;
     Window w = (Window)jwindow;
+    Atom wm_delete_atom = (Atom)windowDeleteAtom;
     Window root = RootWindow(dpy, screen_index);
     Window parent = (0!=jparent)?(Window)jparent:root;
     XEvent event;
@@ -1819,15 +746,18 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
     if( TST_FLAG_CHANGE_FULLSCREEN(flags) ) {
         fsEWMHFlags |= _NET_WM_FULLSCREEN;
         if( TST_FLAG_IS_FULLSCREEN(flags) ) {
-            fsEWMHFlags |= _NET_WM_ABOVE; // fs & above on
+            if( TST_FLAG_IS_ALWAYSONTOP(flags) ) {
+                fsEWMHFlags |= _NET_WM_ABOVE; // fs on,  above on
+            } // else { }                     // fs on,  above off
         } else if( !TST_FLAG_IS_ALWAYSONTOP(flags) ) {
-            fsEWMHFlags |= _NET_WM_ABOVE; // fs & above off
-        } /* else { } */                  // fs off, keep above
-    } else if( TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) {
-        fsEWMHFlags |= _NET_WM_ABOVE; // toggle above only
+            fsEWMHFlags |= _NET_WM_ABOVE;     // fs off, above off
+        } // else { }                         // fs off, above on
+    }
+    if( TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) {
+        fsEWMHFlags |= _NET_WM_ABOVE;         // toggle above
     }
 
-    displayDispatchErrorHandlerEnable(1, env);
+    NewtDisplay_displayDispatchErrorHandlerEnable(1, env);
 
     DBG_PRINT( "X11: reconfigureWindow0 dpy %p, scrn %d, parent %p/%p, win %p, %d/%d %dx%d, parentChange %d, hasParent %d, decorationChange %d, undecorated %d, fullscreenChange %d, fullscreen %d, alwaysOnTopChange %d, alwaysOnTop %d, visibleChange %d, visible %d, tempInvisible %d, fsEWMHFlags %d\n",
         (void*)dpy, screen_index, (void*) jparent, (void*)parent, (void*)w,
@@ -1845,7 +775,18 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
         ( TST_FLAG_CHANGE_FULLSCREEN(flags) || TST_FLAG_CHANGE_ALWAYSONTOP(flags) ) ) {
         Bool enable = TST_FLAG_CHANGE_FULLSCREEN(flags) ? TST_FLAG_IS_FULLSCREEN(flags) : TST_FLAG_IS_ALWAYSONTOP(flags) ;
         if( NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, enable) ) {
-            displayDispatchErrorHandlerEnable(0, env);
+            NewtDisplay_displayDispatchErrorHandlerEnable(0, env);
+            #ifdef FS_GRAB_KEYBOARD
+            if(TST_FLAG_CHANGE_FULLSCREEN(flags)) {
+                if(TST_FLAG_IS_FULLSCREEN(flags)) {
+                    XGrabKeyboard(dpy, w, True, GrabModeAsync, GrabModeAsync, CurrentTime);
+                } else {
+                    XUngrabKeyboard(dpy, CurrentTime);
+                }
+            } else if(TST_FLAG_CHANGE_ALWAYSONTOP(flags) && !TST_FLAG_IS_ALWAYSONTOP(flags)) {
+                XUngrabKeyboard(dpy, CurrentTime);
+            }
+            #endif
             return;
         }
     }
@@ -1860,6 +801,9 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
     if( fsEWMHFlags && ( ( TST_FLAG_CHANGE_FULLSCREEN(flags)  && !TST_FLAG_IS_FULLSCREEN(flags) ) || 
                          ( TST_FLAG_CHANGE_ALWAYSONTOP(flags) && !TST_FLAG_IS_ALWAYSONTOP(flags) ) ) ) { // FS off
         NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, False);
+        #ifdef FS_GRAB_KEYBOARD
+        XUngrabKeyboard(dpy, CurrentTime);
+        #endif
     }
 
     if( TST_FLAG_CHANGE_PARENTING(flags) && !TST_FLAG_HAS_PARENT(flags) ) {
@@ -1868,6 +812,7 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
         XReparentWindow( dpy, w, parent, x, y ); // actual reparent call
         // XIfEvent( dpy, &event, WaitForReparentNotify, (XPointer) w );
         XSync(dpy, False);
+        XSetWMProtocols(dpy, w, &wm_delete_atom, 1); // windowDeleteAtom
     }
 
     if( TST_FLAG_CHANGE_DECORATION(flags) ) {
@@ -1907,9 +852,14 @@ JNIEXPORT void JNICALL Java_jogamp_newt_driver_x11_X11Window_reconfigureWindow0
     if( fsEWMHFlags && ( ( TST_FLAG_CHANGE_FULLSCREEN(flags)  && TST_FLAG_IS_FULLSCREEN(flags) ) || 
                          ( TST_FLAG_CHANGE_ALWAYSONTOP(flags) && TST_FLAG_IS_ALWAYSONTOP(flags) ) ) ) { // FS on
         NewtWindows_setFullscreenEWMH(dpy, root, w, fsEWMHFlags, isVisible, True);
+        #ifdef FS_GRAB_KEYBOARD
+        if(TST_FLAG_CHANGE_FULLSCREEN(flags) && TST_FLAG_IS_FULLSCREEN(flags)) {
+            XGrabKeyboard(dpy, w, True, GrabModeAsync, GrabModeAsync, CurrentTime);
+        }
+        #endif
     }
 
-    displayDispatchErrorHandlerEnable(0, env);
+    NewtDisplay_displayDispatchErrorHandlerEnable(0, env);
 
     DBG_PRINT( "X11: reconfigureWindow0 X\n");
 }
diff --git a/src/test/native/displayMultiple01.c b/src/test-native/displayMultiple01.c
similarity index 100%
rename from src/test/native/displayMultiple01.c
rename to src/test-native/displayMultiple01.c
diff --git a/src/test/native/displayMultiple02.c b/src/test-native/displayMultiple02.c
similarity index 100%
rename from src/test/native/displayMultiple02.c
rename to src/test-native/displayMultiple02.c
diff --git a/src/test-native/ffmpeg/api-example.c b/src/test-native/ffmpeg/api-example.c
new file mode 100644
index 0000000..970a90e
--- /dev/null
+++ b/src/test-native/ffmpeg/api-example.c
@@ -0,0 +1,479 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of Libav.
+ *
+ * Libav is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * Libav is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Libav; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * libavcodec API use example.
+ *
+ * @example libavcodec/api-example.c
+ * Note that this library only handles codecs (mpeg, mpeg4, etc...),
+ * not file formats (avi, vob, etc...). See library 'libavformat' for the
+ * format handling
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef HAVE_AV_CONFIG_H
+#undef HAVE_AV_CONFIG_H
+#endif
+
+#include "libavcodec/avcodec.h"
+#include "libavutil/mathematics.h"
+#include "libavutil/samplefmt.h"
+
+#define INBUF_SIZE 4096
+#define AUDIO_INBUF_SIZE 20480
+#define AUDIO_REFILL_THRESH 4096
+
+/*
+ * Audio encoding example
+ */
+static void audio_encode_example(const char *filename)
+{
+    AVCodec *codec;
+    AVCodecContext *c= NULL;
+    int frame_size, i, j, out_size, outbuf_size;
+    FILE *f;
+    short *samples;
+    float t, tincr;
+    uint8_t *outbuf;
+
+    printf("Audio encoding\n");
+
+    /* find the MP2 encoder */
+    codec = avcodec_find_encoder(CODEC_ID_MP2);
+    if (!codec) {
+        fprintf(stderr, "codec not found\n");
+        exit(1);
+    }
+
+    c = avcodec_alloc_context3(codec);
+
+    /* put sample parameters */
+    c->bit_rate = 64000;
+    c->sample_rate = 44100;
+    c->channels = 2;
+
+    /* open it */
+    if (avcodec_open(c, codec) < 0) {
+        fprintf(stderr, "could not open codec\n");
+        exit(1);
+    }
+
+    /* the codec gives us the frame size, in samples */
+    frame_size = c->frame_size;
+    samples = malloc(frame_size * 2 * c->channels);
+    outbuf_size = 10000;
+    outbuf = malloc(outbuf_size);
+
+    f = fopen(filename, "wb");
+    if (!f) {
+        fprintf(stderr, "could not open %s\n", filename);
+        exit(1);
+    }
+
+    /* encode a single tone sound */
+    t = 0;
+    tincr = 2 * M_PI * 440.0 / c->sample_rate;
+    for(i=0;i<200;i++) {
+        for(j=0;j<frame_size;j++) {
+            samples[2*j] = (int)(sin(t) * 10000);
+            samples[2*j+1] = samples[2*j];
+            t += tincr;
+        }
+        /* encode the samples */
+        out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
+        fwrite(outbuf, 1, out_size, f);
+    }
+    fclose(f);
+    free(outbuf);
+    free(samples);
+
+    avcodec_close(c);
+    av_free(c);
+}
+
+/*
+ * Audio decoding.
+ */
+static void audio_decode_example(const char *outfilename, const char *filename)
+{
+    AVCodec *codec;
+    AVCodecContext *c= NULL;
+    int len;
+    FILE *f, *outfile;
+    uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
+    AVPacket avpkt;
+    AVFrame *decoded_frame = NULL;
+
+    av_init_packet(&avpkt);
+
+    printf("Audio decoding\n");
+
+    /* find the mpeg audio decoder */
+    codec = avcodec_find_decoder(CODEC_ID_MP2);
+    if (!codec) {
+        fprintf(stderr, "codec not found\n");
+        exit(1);
+    }
+
+    c = avcodec_alloc_context3(codec);
+
+    /* open it */
+    if (avcodec_open(c, codec) < 0) {
+        fprintf(stderr, "could not open codec\n");
+        exit(1);
+    }
+
+    f = fopen(filename, "rb");
+    if (!f) {
+        fprintf(stderr, "could not open %s\n", filename);
+        exit(1);
+    }
+    outfile = fopen(outfilename, "wb");
+    if (!outfile) {
+        av_free(c);
+        exit(1);
+    }
+
+    /* decode until eof */
+    avpkt.data = inbuf;
+    avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
+
+    while (avpkt.size > 0) {
+        int got_frame = 0;
+
+        if (!decoded_frame) {
+            if (!(decoded_frame = avcodec_alloc_frame())) {
+                fprintf(stderr, "out of memory\n");
+                exit(1);
+            }
+        } else
+            avcodec_get_frame_defaults(decoded_frame);
+
+        len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
+        if (len < 0) {
+            fprintf(stderr, "Error while decoding\n");
+            exit(1);
+        }
+        if (got_frame) {
+            /* if a frame has been decoded, output it */
+            int data_size = av_samples_get_buffer_size(NULL, c->channels,
+                                                       decoded_frame->nb_samples,
+                                                       c->sample_fmt, 1);
+            fwrite(decoded_frame->data[0], 1, data_size, outfile);
+        }
+        avpkt.size -= len;
+        avpkt.data += len;
+        if (avpkt.size < AUDIO_REFILL_THRESH) {
+            /* Refill the input buffer, to avoid trying to decode
+             * incomplete frames. Instead of this, one could also use
+             * a parser, or use a proper container format through
+             * libavformat. */
+            memmove(inbuf, avpkt.data, avpkt.size);
+            avpkt.data = inbuf;
+            len = fread(avpkt.data + avpkt.size, 1,
+                        AUDIO_INBUF_SIZE - avpkt.size, f);
+            if (len > 0)
+                avpkt.size += len;
+        }
+    }
+
+    fclose(outfile);
+    fclose(f);
+
+    avcodec_close(c);
+    av_free(c);
+    av_free(decoded_frame);
+}
+
+/*
+ * Video encoding example
+ */
+static void video_encode_example(const char *filename)
+{
+    AVCodec *codec;
+    AVCodecContext *c= NULL;
+    int i, out_size, size, x, y, outbuf_size;
+    FILE *f;
+    AVFrame *picture;
+    uint8_t *outbuf, *picture_buf;
+
+    printf("Video encoding\n");
+
+    /* find the mpeg1 video encoder */
+    codec = avcodec_find_encoder(CODEC_ID_MPEG1VIDEO);
+    if (!codec) {
+        fprintf(stderr, "codec not found\n");
+        exit(1);
+    }
+
+    c = avcodec_alloc_context3(codec);
+    picture= avcodec_alloc_frame();
+
+    /* put sample parameters */
+    c->bit_rate = 400000;
+    /* resolution must be a multiple of two */
+    c->width = 352;
+    c->height = 288;
+    /* frames per second */
+    c->time_base= (AVRational){1,25};
+    c->gop_size = 10; /* emit one intra frame every ten frames */
+    c->max_b_frames=1;
+    c->pix_fmt = PIX_FMT_YUV420P;
+
+    /* open it */
+    if (avcodec_open(c, codec) < 0) {
+        fprintf(stderr, "could not open codec\n");
+        exit(1);
+    }
+
+    f = fopen(filename, "wb");
+    if (!f) {
+        fprintf(stderr, "could not open %s\n", filename);
+        exit(1);
+    }
+
+    /* alloc image and output buffer */
+    outbuf_size = 100000;
+    outbuf = malloc(outbuf_size);
+    size = c->width * c->height;
+    picture_buf = malloc((size * 3) / 2); /* size for YUV 420 */
+
+    picture->data[0] = picture_buf;
+    picture->data[1] = picture->data[0] + size;
+    picture->data[2] = picture->data[1] + size / 4;
+    picture->linesize[0] = c->width;
+    picture->linesize[1] = c->width / 2;
+    picture->linesize[2] = c->width / 2;
+
+    /* encode 1 second of video */
+    for(i=0;i<25;i++) {
+        fflush(stdout);
+        /* prepare a dummy image */
+        /* Y */
+        for(y=0;y<c->height;y++) {
+            for(x=0;x<c->width;x++) {
+                picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
+            }
+        }
+
+        /* Cb and Cr */
+        for(y=0;y<c->height/2;y++) {
+            for(x=0;x<c->width/2;x++) {
+                picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
+                picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
+            }
+        }
+
+        /* encode the image */
+        out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
+        printf("encoding frame %3d (size=%5d)\n", i, out_size);
+        fwrite(outbuf, 1, out_size, f);
+    }
+
+    /* get the delayed frames */
+    for(; out_size; i++) {
+        fflush(stdout);
+
+        out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
+        printf("write frame %3d (size=%5d)\n", i, out_size);
+        fwrite(outbuf, 1, out_size, f);
+    }
+
+    /* add sequence end code to have a real mpeg file */
+    outbuf[0] = 0x00;
+    outbuf[1] = 0x00;
+    outbuf[2] = 0x01;
+    outbuf[3] = 0xb7;
+    fwrite(outbuf, 1, 4, f);
+    fclose(f);
+    free(picture_buf);
+    free(outbuf);
+
+    avcodec_close(c);
+    av_free(c);
+    av_free(picture);
+    printf("\n");
+}
+
+/*
+ * Video decoding example
+ */
+
+static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
+                     char *filename)
+{
+    FILE *f;
+    int i;
+
+    f=fopen(filename,"w");
+    fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
+    for(i=0;i<ysize;i++)
+        fwrite(buf + i * wrap,1,xsize,f);
+    fclose(f);
+}
+
+static void video_decode_example(const char *outfilename, const char *filename)
+{
+    AVCodec *codec;
+    AVCodecContext *c= NULL;
+    int frame, got_picture, len;
+    FILE *f;
+    AVFrame *picture;
+    uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
+    char buf[1024];
+    AVPacket avpkt;
+
+    av_init_packet(&avpkt);
+
+    /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
+    memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+
+    printf("Video decoding\n");
+
+    /* find the mpeg1 video decoder */
+    codec = avcodec_find_decoder(CODEC_ID_MPEG1VIDEO);
+    if (!codec) {
+        fprintf(stderr, "codec not found\n");
+        exit(1);
+    }
+
+    c = avcodec_alloc_context3(codec);
+    picture= avcodec_alloc_frame();
+
+    if(codec->capabilities&CODEC_CAP_TRUNCATED)
+        c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
+
+    /* For some codecs, such as msmpeg4 and mpeg4, width and height
+       MUST be initialized there because this information is not
+       available in the bitstream. */
+
+    /* open it */
+    if (avcodec_open(c, codec) < 0) {
+        fprintf(stderr, "could not open codec\n");
+        exit(1);
+    }
+
+    /* the codec gives us the frame size, in samples */
+
+    f = fopen(filename, "rb");
+    if (!f) {
+        fprintf(stderr, "could not open %s\n", filename);
+        exit(1);
+    }
+
+    frame = 0;
+    for(;;) {
+        avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
+        if (avpkt.size == 0)
+            break;
+
+        /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
+           and this is the only method to use them because you cannot
+           know the compressed data size before analysing it.
+
+           BUT some other codecs (msmpeg4, mpeg4) are inherently frame
+           based, so you must call them with all the data for one
+           frame exactly. You must also initialize 'width' and
+           'height' before initializing them. */
+
+        /* NOTE2: some codecs allow the raw parameters (frame size,
+           sample rate) to be changed at any frame. We handle this, so
+           you should also take care of it */
+
+        /* here, we use a stream based decoder (mpeg1video), so we
+           feed decoder and see if it could decode a frame */
+        avpkt.data = inbuf;
+        while (avpkt.size > 0) {
+            len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
+            if (len < 0) {
+                fprintf(stderr, "Error while decoding frame %d\n", frame);
+                exit(1);
+            }
+            if (got_picture) {
+                printf("saving frame %3d\n", frame);
+                fflush(stdout);
+
+                /* the picture is allocated by the decoder. no need to
+                   free it */
+                snprintf(buf, sizeof(buf), outfilename, frame);
+                pgm_save(picture->data[0], picture->linesize[0],
+                         c->width, c->height, buf);
+                frame++;
+            }
+            avpkt.size -= len;
+            avpkt.data += len;
+        }
+    }
+
+    /* some codecs, such as MPEG, transmit the I and P frame with a
+       latency of one frame. You must do the following to have a
+       chance to get the last frame of the video */
+    avpkt.data = NULL;
+    avpkt.size = 0;
+    len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
+    if (got_picture) {
+        printf("saving last frame %3d\n", frame);
+        fflush(stdout);
+
+        /* the picture is allocated by the decoder. no need to
+           free it */
+        snprintf(buf, sizeof(buf), outfilename, frame);
+        pgm_save(picture->data[0], picture->linesize[0],
+                 c->width, c->height, buf);
+        frame++;
+    }
+
+    fclose(f);
+
+    avcodec_close(c);
+    av_free(c);
+    av_free(picture);
+    printf("\n");
+}
+
+int main(int argc, char **argv)
+{
+    const char *filename;
+
+    /* must be called before using avcodec lib */
+    avcodec_init();
+
+    /* register all the codecs */
+    avcodec_register_all();
+
+    if (argc <= 1) {
+        audio_encode_example("/tmp/test.mp2");
+        audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
+
+        video_encode_example("/tmp/test.mpg");
+        filename = "/tmp/test.mpg";
+    } else {
+        filename = argv[1];
+    }
+
+    //    audio_decode_example("/tmp/test.sw", filename);
+    video_decode_example("/tmp/test%d.pgm", filename);
+
+    return 0;
+}
diff --git a/src/test-native/ffmpeg/avcodec_sample.c b/src/test-native/ffmpeg/avcodec_sample.c
new file mode 100644
index 0000000..f4001b4
--- /dev/null
+++ b/src/test-native/ffmpeg/avcodec_sample.c
@@ -0,0 +1,203 @@
+// avcodec_sample.0.5.0.c
+
+// A small sample program that shows how to use libavformat and libavcodec to
+// read video from a file.
+//
+// This version is for the 0.4.9+ release of ffmpeg. This release adds the
+// av_read_frame() API call, which simplifies the reading of video frames 
+// considerably. 
+//
+// Use
+//
+// gcc -o avcodec_sample.0.5.0 avcodec_sample.0.5.0.c -lavformat -lavcodec -lavutil -lswscale -lz -lbz2
+//
+// to build (assuming libavformat, libavcodec, libavutil, and swscale are correctly installed on
+// your system).
+//
+// Run using
+//
+// avcodec_sample.0.5.0 myvideofile.mpg
+//
+// to write the first five frames from "myvideofile.mpg" to disk in PPM
+// format.
+
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libswscale/swscale.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+static void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame);
+
+int main (int argc, const char * argv[])
+{
+    AVFormatContext *pFormatCtx;
+    int             i, videoStream;
+    AVCodecContext  *pCodecCtx;
+    AVCodec         *pCodec;
+    AVFrame         *pFrame; 
+    AVFrame         *pFrameRGB;
+    AVPacket        packet;
+    int             frameFinished;
+    int             numBytes;
+    uint8_t         *buffer;
+
+    // Register all formats and codecs
+    av_register_all();
+
+    avformat_network_init();
+
+    // Open video file
+    if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)
+        return -1; // Couldn't open file
+
+    // Retrieve stream information
+    if(avformat_find_stream_info(pFormatCtx, NULL)<0)
+        return -1; // Couldn't find stream information
+
+    // Dump information about file onto standard error
+    av_dump_format(pFormatCtx, 0, argv[1], false);
+
+    // Find the first video stream
+    videoStream=-1;
+    for(i=0; i<pFormatCtx->nb_streams; i++)
+        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
+        {
+            videoStream=i;
+            break;
+        }
+    if(videoStream==-1)
+        return -1; // Didn't find a video stream
+
+    // Get a pointer to the codec context for the video stream
+    pCodecCtx=pFormatCtx->streams[videoStream]->codec;
+
+    // Find the decoder for the video stream
+    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
+    if(pCodec==NULL)
+        return -1; // Codec not found
+
+    // Open codec
+    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
+        return -1; // Could not open codec
+
+    // Hack to correct wrong frame rates that seem to be generated by some codecs
+    if(pCodecCtx->time_base.num>1000 && pCodecCtx->time_base.den==1)
+		pCodecCtx->time_base.den=1000;
+		
+    // Allocate video frame
+    pFrame=avcodec_alloc_frame();
+
+    // Allocate an AVFrame structure
+    pFrameRGB=avcodec_alloc_frame();
+    if(pFrameRGB==NULL)
+        return -1;
+
+    // Determine required buffer size and allocate buffer
+    numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,
+        pCodecCtx->height);
+
+    buffer=malloc(numBytes);
+
+    // Assign appropriate parts of buffer to image planes in pFrameRGB
+    avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,
+        pCodecCtx->width, pCodecCtx->height);
+
+    // Read frames and save first five frames to disk
+    i=0;
+    while(av_read_frame(pFormatCtx, &packet)>=0)
+    {
+        // Is this a packet from the video stream?
+        if(packet.stream_index==videoStream)
+        {
+            // Decode video frame
+            avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
+
+            // Did we get a video frame?
+            if(frameFinished)
+            {
+				static struct SwsContext *img_convert_ctx;
+
+#if 0
+				// Older removed code
+                // Convert the image from its native format to RGB swscale
+                img_convert((AVPicture *)pFrameRGB, PIX_FMT_RGB24, 
+                    (AVPicture*)pFrame, pCodecCtx->pix_fmt, pCodecCtx->width, 
+                    pCodecCtx->height);
+				
+				// function template, for reference
+				int sws_scale(struct SwsContext *context, uint8_t* src[], int srcStride[], int srcSliceY,
+							  int srcSliceH, uint8_t* dst[], int dstStride[]);
+#endif
+				// Convert the image into YUV format that SDL uses
+				if(img_convert_ctx == NULL) {
+					int w = pCodecCtx->width;
+					int h = pCodecCtx->height;
+					
+					img_convert_ctx = sws_getContext(w, h, 
+									pCodecCtx->pix_fmt, 
+									w, h, PIX_FMT_RGB24, SWS_BICUBIC,
+									NULL, NULL, NULL);
+					if(img_convert_ctx == NULL) {
+						fprintf(stderr, "Cannot initialize the conversion context!\n");
+						exit(1);
+					}
+				}
+				int ret = sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, 
+						            pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
+#if 0 // this use to be true, as of 1/2009, but apparently it is no longer true in 3/2009
+				if(ret) {
+					fprintf(stderr, "SWS_Scale failed [%d]!\n", ret);
+					exit(-1);
+				}
+#endif
+                // Save the frame to disk
+                if(i++<=5)
+                    SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height, i);
+            }
+        }
+
+        // Free the packet that was allocated by av_read_frame
+        av_free_packet(&packet);
+    }
+
+    // Free the RGB image
+    free(buffer);
+    av_free(pFrameRGB);
+
+    // Free the YUV frame
+    av_free(pFrame);
+
+    // Close the codec
+    avcodec_close(pCodecCtx);
+
+    // Close the video file
+    avformat_close_input(&pFormatCtx);
+
+    return 0;
+}
+
+static void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame)
+{
+    FILE *pFile;
+    char szFilename[32];
+    int  y;
+
+    // Open file
+    sprintf(szFilename, "frame%d.ppm", iFrame);
+    pFile=fopen(szFilename, "wb");
+    if(pFile==NULL)
+        return;
+
+    // Write header
+    fprintf(pFile, "P6\n%d %d\n255\n", width, height);
+
+    // Write pixel data
+    for(y=0; y<height; y++)
+        fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);
+
+    // Close file
+    fclose(pFile);
+}
diff --git a/src/test-native/ffmpeg/avcodec_sample.sh b/src/test-native/ffmpeg/avcodec_sample.sh
new file mode 100644
index 0000000..c5ccd6c
--- /dev/null
+++ b/src/test-native/ffmpeg/avcodec_sample.sh
@@ -0,0 +1,6 @@
+#  -I/usr/include/libavcodec -I/usr/include/libavformat \
+
+gcc \
+  -o avcodec_sample avcodec_sample.c \
+  -lavformat -lavcodec -lavutil -lswscale
+
diff --git a/src/test/native/glExtensionsListGL2.c b/src/test-native/glExtensionsListGL2.c
similarity index 100%
rename from src/test/native/glExtensionsListGL2.c
rename to src/test-native/glExtensionsListGL2.c
diff --git a/src/test/native/glExtensionsListGL3.c b/src/test-native/glExtensionsListGL3.c
similarity index 100%
rename from src/test/native/glExtensionsListGL3.c
rename to src/test-native/glExtensionsListGL3.c
diff --git a/src/test-native/gst/helloworld-auto.c b/src/test-native/gst/helloworld-auto.c
new file mode 100644
index 0000000..6381c9c
--- /dev/null
+++ b/src/test-native/gst/helloworld-auto.c
@@ -0,0 +1,112 @@
+#include <gst/gst.h>
+#include <glib.h>
+
+
+static gboolean
+my_bus_callback (GstBus     *bus,
+          GstMessage *msg,
+          gpointer    data)
+{
+  GMainLoop *loop = (GMainLoop *) data;
+
+  switch (GST_MESSAGE_TYPE (msg)) {
+
+    case GST_MESSAGE_EOS:
+      g_print ("End of stream\n");
+      g_main_loop_quit (loop);
+      break;
+
+    case GST_MESSAGE_ERROR: {
+      gchar  *debug;
+      GError *error;
+
+      gst_message_parse_error (msg, &error, &debug);
+      g_free (debug);
+
+      g_printerr ("Error: %s\n", error->message);
+      g_error_free (error);
+
+      g_main_loop_quit (loop);
+      break;
+    }
+    default:
+      break;
+  }
+
+  return TRUE;
+}
+
+
+static gboolean
+idle_exit_loop (gpointer data)
+{
+  g_main_loop_quit ((GMainLoop *) data);
+
+  /* once */
+  return FALSE;
+}
+
+static void
+cb_typefound (GstElement *typefind,
+          guint       probability,
+          GstCaps    *caps,
+          gpointer    data)
+{
+  GMainLoop *loop = data;
+  gchar *type;
+
+  type = gst_caps_to_string (caps);
+  g_print ("Media type %s found, probability %d%%\n", type, probability);
+  g_free (type);
+
+  /* since we connect to a signal in the pipeline thread context, we need
+   * to set an idle handler to exit the main loop in the mainloop context.
+   * Normally, your app should not need to worry about such things. */
+  g_idle_add (idle_exit_loop, loop);
+}
+
+gint 
+main (gint   argc,
+      gchar *argv[])
+{
+  GMainLoop *loop;
+  GstElement *pipeline, *filesrc, *typefind, *fakesink;
+  GstBus *bus;
+
+  /* init GStreamer */
+  gst_init (&argc, &argv);
+  loop = g_main_loop_new (NULL, FALSE);
+
+  /* check args */
+  if (argc != 2) {
+    g_print ("Usage: %s <filename>\n", argv[0]);
+    return -1;
+  }
+
+  /* create a new pipeline to hold the elements */
+  pipeline = gst_pipeline_new ("pipe");
+
+  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
+  gst_bus_add_watch (bus, my_bus_callback, NULL);
+  gst_object_unref (bus);
+
+  /* create file source and typefind element */
+  filesrc = gst_element_factory_make ("filesrc", "source");
+  g_object_set (G_OBJECT (filesrc), "location", argv[1], NULL);
+  typefind = gst_element_factory_make ("typefind", "typefinder");
+  g_signal_connect (typefind, "have-type", G_CALLBACK (cb_typefound), loop);
+  fakesink = gst_element_factory_make ("fakesink", "sink");
+
+  /* setup */
+  gst_bin_add_many (GST_BIN (pipeline), filesrc, typefind, fakesink, NULL);
+  gst_element_link_many (filesrc, typefind, fakesink, NULL);
+  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);
+  g_main_loop_run (loop);
+
+  /* unset */
+  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL);
+  gst_object_unref (GST_OBJECT (pipeline));
+
+  return 0;
+}
+    
diff --git a/src/test-native/gst/helloworld-playbin.c b/src/test-native/gst/helloworld-playbin.c
new file mode 100644
index 0000000..c5a42fe
--- /dev/null
+++ b/src/test-native/gst/helloworld-playbin.c
@@ -0,0 +1,75 @@
+#include <gst/gst.h>
+#include <glib.h>
+
+
+static gboolean
+my_bus_callback (GstBus     *bus,
+          GstMessage *msg,
+          gpointer    data)
+{
+  GMainLoop *loop = (GMainLoop *) data;
+
+  switch (GST_MESSAGE_TYPE (msg)) {
+
+    case GST_MESSAGE_EOS:
+      g_print ("End of stream\n");
+      g_main_loop_quit (loop);
+      break;
+
+    case GST_MESSAGE_ERROR: {
+      gchar  *debug;
+      GError *error;
+
+      gst_message_parse_error (msg, &error, &debug);
+      g_free (debug);
+
+      g_printerr ("Error: %s\n", error->message);
+      g_error_free (error);
+
+      g_main_loop_quit (loop);
+      break;
+    }
+    default:
+      break;
+  }
+
+  return TRUE;
+}
+
+gint
+main (gint   argc,
+      gchar *argv[])
+{
+  GMainLoop *loop;
+  GstElement *play;
+  GstBus *bus;
+
+  /* init GStreamer */
+  gst_init (&argc, &argv);
+  loop = g_main_loop_new (NULL, FALSE);
+
+  /* make sure we have a URI */
+  if (argc != 2) {
+    g_print ("Usage: %s <URI>\n", argv[0]);
+    return -1;
+  }
+
+  /* set up */
+  play = gst_element_factory_make ("playbin", "play");
+  g_object_set (G_OBJECT (play), "uri", argv[1], NULL);
+
+  bus = gst_pipeline_get_bus (GST_PIPELINE (play));
+  gst_bus_add_watch (bus, my_bus_callback, loop);
+  gst_object_unref (bus);
+
+  gst_element_set_state (play, GST_STATE_PLAYING);
+
+  /* now run */
+  g_main_loop_run (loop);
+
+  /* also clean up */
+  gst_element_set_state (play, GST_STATE_NULL);
+  gst_object_unref (GST_OBJECT (play));
+
+  return 0;
+}
diff --git a/src/test-native/gst/helloworld-playbin2.c b/src/test-native/gst/helloworld-playbin2.c
new file mode 100644
index 0000000..b31e3e5
--- /dev/null
+++ b/src/test-native/gst/helloworld-playbin2.c
@@ -0,0 +1,75 @@
+#include <gst/gst.h>
+#include <glib.h>
+
+
+static gboolean
+my_bus_callback (GstBus     *bus,
+          GstMessage *msg,
+          gpointer    data)
+{
+  GMainLoop *loop = (GMainLoop *) data;
+
+  switch (GST_MESSAGE_TYPE (msg)) {
+
+    case GST_MESSAGE_EOS:
+      g_print ("End of stream\n");
+      g_main_loop_quit (loop);
+      break;
+
+    case GST_MESSAGE_ERROR: {
+      gchar  *debug;
+      GError *error;
+
+      gst_message_parse_error (msg, &error, &debug);
+      g_free (debug);
+
+      g_printerr ("Error: %s\n", error->message);
+      g_error_free (error);
+
+      g_main_loop_quit (loop);
+      break;
+    }
+    default:
+      break;
+  }
+
+  return TRUE;
+}
+
+gint
+main (gint   argc,
+      gchar *argv[])
+{
+  GMainLoop *loop;
+  GstElement *play;
+  GstBus *bus;
+
+  /* init GStreamer */
+  gst_init (&argc, &argv);
+  loop = g_main_loop_new (NULL, FALSE);
+
+  /* make sure we have a URI */
+  if (argc != 2) {
+    g_print ("Usage: %s <URI>\n", argv[0]);
+    return -1;
+  }
+
+  /* set up */
+  play = gst_element_factory_make ("playbin2", "play");
+  g_object_set (G_OBJECT (play), "uri", argv[1], NULL);
+
+  bus = gst_pipeline_get_bus (GST_PIPELINE (play));
+  gst_bus_add_watch (bus, my_bus_callback, loop);
+  gst_object_unref (bus);
+
+  gst_element_set_state (play, GST_STATE_PLAYING);
+
+  /* now run */
+  g_main_loop_run (loop);
+
+  /* also clean up */
+  gst_element_set_state (play, GST_STATE_NULL);
+  gst_object_unref (GST_OBJECT (play));
+
+  return 0;
+}
diff --git a/src/test-native/gst/helloworld.c b/src/test-native/gst/helloworld.c
new file mode 100644
index 0000000..6d99189
--- /dev/null
+++ b/src/test-native/gst/helloworld.c
@@ -0,0 +1,142 @@
+#include <gst/gst.h>
+#include <glib.h>
+
+
+static gboolean
+bus_call (GstBus     *bus,
+          GstMessage *msg,
+          gpointer    data)
+{
+  GMainLoop *loop = (GMainLoop *) data;
+
+  switch (GST_MESSAGE_TYPE (msg)) {
+
+    case GST_MESSAGE_EOS:
+      g_print ("End of stream\n");
+      g_main_loop_quit (loop);
+      break;
+
+    case GST_MESSAGE_ERROR: {
+      gchar  *debug;
+      GError *error;
+
+      gst_message_parse_error (msg, &error, &debug);
+      g_free (debug);
+
+      g_printerr ("Error: %s\n", error->message);
+      g_error_free (error);
+
+      g_main_loop_quit (loop);
+      break;
+    }
+    default:
+      break;
+  }
+
+  return TRUE;
+}
+
+
+static void
+on_pad_added (GstElement *element,
+              GstPad     *pad,
+              gpointer    data)
+{
+  GstPad *sinkpad;
+  GstElement *decoder = (GstElement *) data;
+
+  /* We can now link this pad with the vorbis-decoder sink pad */
+  g_print ("Dynamic pad created, linking demuxer/decoder\n");
+
+  sinkpad = gst_element_get_static_pad (decoder, "sink");
+
+  gst_pad_link (pad, sinkpad);
+
+  gst_object_unref (sinkpad);
+}
+
+
+
+int
+main (int   argc,
+      char *argv[])
+{
+  GMainLoop *loop;
+
+  GstElement *pipeline, *source, *demuxer, *decoder, *conv, *sink;
+  GstBus *bus;
+
+  /* Initialisation */
+  gst_init (&argc, &argv);
+
+  loop = g_main_loop_new (NULL, FALSE);
+
+
+  /* Check input arguments */
+  if (argc != 2) {
+    g_printerr ("Usage: %s <Ogg/Vorbis filename>\n", argv[0]);
+    return -1;
+  }
+
+
+  /* Create gstreamer elements */
+  pipeline = gst_pipeline_new ("audio-player");
+  source   = gst_element_factory_make ("filesrc",       "file-source");
+  demuxer  = gst_element_factory_make ("oggdemux",      "ogg-demuxer");
+  decoder  = gst_element_factory_make ("vorbisdec",     "vorbis-decoder");
+  conv     = gst_element_factory_make ("audioconvert",  "converter");
+  sink     = gst_element_factory_make ("autoaudiosink", "audio-output");
+
+  if (!pipeline || !source || !demuxer || !decoder || !conv || !sink) {
+    g_printerr ("One element could not be created. Exiting.\n");
+    return -1;
+  }
+
+  /* Set up the pipeline */
+
+  /* we set the input filename to the source element */
+  g_object_set (G_OBJECT (source), "location", argv[1], NULL);
+
+  /* we add a message handler */
+  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
+  gst_bus_add_watch (bus, bus_call, loop);
+  gst_object_unref (bus);
+
+  /* we add all elements into the pipeline */
+  /* file-source | ogg-demuxer | vorbis-decoder | converter | alsa-output */
+  gst_bin_add_many (GST_BIN (pipeline),
+                    source, demuxer, decoder, conv, sink, NULL);
+
+  /* we link the elements together */
+  /* file-source -> ogg-demuxer ~> vorbis-decoder -> converter -> alsa-output */
+  gst_element_link (source, demuxer);
+  gst_element_link_many (decoder, conv, sink, NULL);
+  g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), decoder);
+
+  /* note that the demuxer will be linked to the decoder dynamically.
+     The reason is that Ogg may contain various streams (for example
+     audio and video). The source pad(s) will be created at run time,
+     by the demuxer when it detects the amount and nature of streams.
+     Therefore we connect a callback function which will be executed
+     when the "pad-added" is emitted.*/
+
+
+  /* Set the pipeline to "playing" state*/
+  g_print ("Now playing: %s\n", argv[1]);
+  gst_element_set_state (pipeline, GST_STATE_PLAYING);
+
+
+  /* Iterate */
+  g_print ("Running...\n");
+  g_main_loop_run (loop);
+
+
+  /* Out of the main loop, clean up nicely */
+  g_print ("Returned, stopping playback\n");
+  gst_element_set_state (pipeline, GST_STATE_NULL);
+
+  g_print ("Deleting pipeline\n");
+  gst_object_unref (GST_OBJECT (pipeline));
+
+  return 0;
+}
diff --git a/src/test-native/gst/make.sh b/src/test-native/gst/make.sh
new file mode 100644
index 0000000..23e54a2
--- /dev/null
+++ b/src/test-native/gst/make.sh
@@ -0,0 +1,5 @@
+gcc -Wall helloworld.c -o helloworld $(pkg-config --cflags --libs gstreamer-0.10)
+gcc -Wall helloworld-auto.c -o helloworld-auto $(pkg-config --cflags --libs gstreamer-0.10)
+gcc -Wall helloworld-playbin.c -o helloworld-playbin $(pkg-config --cflags --libs gstreamer-0.10)
+gcc -Wall helloworld-playbin2.c -o helloworld-playbin2 $(pkg-config --cflags --libs gstreamer-0.10)
+
diff --git a/src/test/native/make.sh b/src/test-native/make.sh
similarity index 100%
rename from src/test/native/make.sh
rename to src/test-native/make.sh
diff --git a/make/stub_includes/egl/EGL/egl.h b/src/test-native/mesa-demos-patched/EGL/egl.h
similarity index 96%
copy from make/stub_includes/egl/EGL/egl.h
copy to src/test-native/mesa-demos-patched/EGL/egl.h
index 1eabe3a..99ea342 100644
--- a/make/stub_includes/egl/EGL/egl.h
+++ b/src/test-native/mesa-demos-patched/EGL/egl.h
@@ -56,8 +56,6 @@ typedef void *EGLClientBuffer;
 #define EGL_VERSION_1_3			1
 #define EGL_VERSION_1_4			1
 
-#ifndef EGL_VERSION_1_X
-
 /* EGL Enumerants. Bitmasks and other exceptional cases aside, most
  * enums are assigned unique values starting at 0x3000.
  */
@@ -244,10 +242,7 @@ typedef void *EGLClientBuffer;
  * a bug in Khronos Bugzilla against task "Registry".
  */
 
-#endif /* EGL_VERSION_1_X */
 
-#ifndef EGL_VERSION_1_X
-#define EGL_VERSION_1_X 1
 
 /* EGL Functions */
 
@@ -318,10 +313,14 @@ EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface)
 EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface,
 			  EGLNativePixmapType target);
 
-typedef void (* EGLAPIENTRY __EGLFuncPtr)(void);
-EGLAPI __EGLFuncPtr eglGetProcAddress(const char *procname);
+/* This is a generic function pointer type, whose name indicates it must
+ * be cast to the proper type *and calling convention* before use.
+ */
+typedef void (*__eglMustCastToProperFunctionPointerType)(void);
 
-#endif /* EGL_VERSION_1_X */
+/* Now, define eglGetProcAddress using the generic function ptr. type */
+EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY
+       eglGetProcAddress(const char *procname);
 
 #ifdef __cplusplus
 }
diff --git a/make/stub_includes/egl/EGL/eglext.h b/src/test-native/mesa-demos-patched/EGL/eglext.h
similarity index 64%
copy from make/stub_includes/egl/EGL/eglext.h
copy to src/test-native/mesa-demos-patched/EGL/eglext.h
index 972becf..9915b8c 100644
--- a/make/stub_includes/egl/EGL/eglext.h
+++ b/src/test-native/mesa-demos-patched/EGL/eglext.h
@@ -34,8 +34,8 @@ extern "C" {
 
 /* Header file version number */
 /* Current version at http://www.khronos.org/registry/egl/ */
-/* $Revision: 12814 $ on $Date: 2010-11-03 17:47:28 -0700 (Wed, 03 Nov 2010) $ */
-#define EGL_EGLEXT_VERSION 8
+/* $Revision: 12124 $ on $Date: 2010-07-27 20:12:35 -0700 (Tue, 27 Jul 2010) $ */
+#define EGL_EGLEXT_VERSION 7
 
 #ifndef EGL_KHR_config_attribs
 #define EGL_KHR_config_attribs 1
@@ -79,7 +79,7 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay display
 #define EGL_KHR_image 1
 #define EGL_NATIVE_PIXMAP_KHR			0x30B0	/* eglCreateImageKHR target */
 typedef void *EGLImageKHR;
-/* Manual: #define EGL_NO_IMAGE_KHR ((EGLImageKHR)0) */
+#define EGL_NO_IMAGE_KHR			((EGLImageKHR)0)
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
 EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image);
@@ -120,6 +120,43 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGL
 #define EGL_GL_RENDERBUFFER_KHR			0x30B9	/* eglCreateImageKHR target */
 #endif
 
+#ifndef EGL_MESA_drm_image
+#define EGL_MESA_drm_image 1
+#define EGL_DRM_BUFFER_FORMAT_MESA		0x31D0	/* eglCreateImageKHR attribute */
+#define EGL_DRM_BUFFER_USE_MESA			0x31D1
+
+/* EGL_DRM_BUFFER_FORMAT_MESA tokens */
+#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA	0x31D2
+
+/* EGL_DRM_BUFFER_USE_MESA bits */
+#define EGL_DRM_BUFFER_USE_SCANOUT_MESA		0x0001
+#define EGL_DRM_BUFFER_USE_SHARE_MESA		0x0002
+#define EGL_DRM_BUFFER_USE_CURSOR_MESA		0x0004
+
+#define EGL_DRM_BUFFER_MESA			0x31D3  /* eglCreateImageKHR target */
+#define EGL_DRM_BUFFER_STRIDE_MESA		0x31D4	/* eglCreateImageKHR attribute */
+
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA(EGLDisplay dpy, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA(EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
+#endif
+typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESA) (EGLDisplay dpy, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESA) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
+#endif
+
+#ifndef EGL_WL_bind_wayland_display
+#define EGL_WL_bind_wayland_display 1
+
+#define EGL_WAYLAND_BUFFER_WL			0x31D5 /* eglCreateImageKHR target */
+struct wl_display;
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglBindWaylandDisplayWL(EGLDisplay dpy, struct wl_display *display);
+EGLAPI EGLBoolean EGLAPIENTRY eglUnbindWaylandDisplayWL(EGLDisplay dpy, struct wl_display *display);
+#endif
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
+#endif
+
 #if KHRONOS_SUPPORT_INT64   /* EGLTimeKHR requires 64-bit uint support */
 #ifndef EGL_KHR_reusable_sync
 #define EGL_KHR_reusable_sync 1
@@ -136,7 +173,7 @@ typedef khronos_utime_nanoseconds_t EGLTimeKHR;
 #define EGL_SYNC_REUSABLE_KHR			0x30FA
 #define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR		0x0001	/* eglClientWaitSyncKHR <flags> bitfield */
 #define EGL_FOREVER_KHR				0xFFFFFFFFFFFFFFFFull
-/* Manual: #define EGL_NO_SYNC_KHR				((EGLSyncKHR)0) */
+#define EGL_NO_SYNC_KHR				((EGLSyncKHR)0)
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
 EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
@@ -152,6 +189,75 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EG
 #endif
 #endif
 
+/* EGL_MESA_screen extension  >>> PRELIMINARY <<< */
+#ifndef EGL_MESA_screen_surface
+#define EGL_MESA_screen_surface 1
+
+#define EGL_BAD_SCREEN_MESA                    0x4000
+#define EGL_BAD_MODE_MESA                      0x4001
+#define EGL_SCREEN_COUNT_MESA                  0x4002
+#define EGL_SCREEN_POSITION_MESA               0x4003
+#define EGL_SCREEN_POSITION_GRANULARITY_MESA   0x4004
+#define EGL_MODE_ID_MESA                       0x4005
+#define EGL_REFRESH_RATE_MESA                  0x4006
+#define EGL_OPTIMAL_MESA                       0x4007
+#define EGL_INTERLACED_MESA                    0x4008
+#define EGL_SCREEN_BIT_MESA                    0x08
+
+typedef khronos_uint32_t EGLScreenMESA;
+typedef khronos_uint32_t EGLModeMESA;
+
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglChooseModeMESA(EGLDisplay dpy, EGLScreenMESA screen, const EGLint *attrib_list, EGLModeMESA *modes, EGLint modes_size, EGLint *num_modes);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetModesMESA(EGLDisplay dpy, EGLScreenMESA screen, EGLModeMESA *modes, EGLint modes_size, EGLint *num_modes);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetModeAttribMESA(EGLDisplay dpy, EGLModeMESA mode, EGLint attribute, EGLint *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetScreensMESA(EGLDisplay dpy, EGLScreenMESA *screens, EGLint max_screens, EGLint *num_screens);
+EGLAPI EGLSurface EGLAPIENTRY eglCreateScreenSurfaceMESA(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglShowScreenSurfaceMESA(EGLDisplay dpy, EGLint screen, EGLSurface surface, EGLModeMESA mode);
+EGLAPI EGLBoolean EGLAPIENTRY eglScreenPositionMESA(EGLDisplay dpy, EGLScreenMESA screen, EGLint x, EGLint y);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryScreenMESA(EGLDisplay dpy, EGLScreenMESA screen, EGLint attribute, EGLint *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryScreenSurfaceMESA(EGLDisplay dpy, EGLScreenMESA screen, EGLSurface *surface);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryScreenModeMESA(EGLDisplay dpy, EGLScreenMESA screen, EGLModeMESA *mode);
+EGLAPI const char * EGLAPIENTRY eglQueryModeStringMESA(EGLDisplay dpy, EGLModeMESA mode);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCHOOSEMODEMESA) (EGLDisplay dpy, EGLScreenMESA screen, const EGLint *attrib_list, EGLModeMESA *modes, EGLint modes_size, EGLint *num_modes);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETMODESMESA) (EGLDisplay dpy, EGLScreenMESA screen, EGLModeMESA *modes, EGLint modes_size, EGLint *num_modes);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLGetModeATTRIBMESA) (EGLDisplay dpy, EGLModeMESA mode, EGLint attribute, EGLint *value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSCRREENSMESA) (EGLDisplay dpy, EGLScreenMESA *screens, EGLint max_screens, EGLint *num_screens);
+typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATESCREENSURFACEMESA) (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSHOWSCREENSURFACEMESA) (EGLDisplay dpy, EGLint screen, EGLSurface surface, EGLModeMESA mode);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSCREENPOSIITONMESA) (EGLDisplay dpy, EGLScreenMESA screen, EGLint x, EGLint y);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSCREENMESA) (EGLDisplay dpy, EGLScreenMESA screen, EGLint attribute, EGLint *value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSCREENSURFACEMESA) (EGLDisplay dpy, EGLScreenMESA screen, EGLSurface *surface);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSCREENMODEMESA) (EGLDisplay dpy, EGLScreenMESA screen, EGLModeMESA *mode);
+typedef const char * (EGLAPIENTRYP PFNEGLQUERYMODESTRINGMESA) (EGLDisplay dpy, EGLModeMESA mode);
+
+#endif /* EGL_MESA_screen_surface */
+
+
+#ifndef EGL_MESA_copy_context
+#define EGL_MESA_copy_context 1
+
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglCopyContextMESA(EGLDisplay dpy, EGLContext source, EGLContext dest, EGLint mask);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOPYCONTEXTMESA) (EGLDisplay dpy, EGLContext source, EGLContext dest, EGLint mask);
+
+#endif /* EGL_MESA_copy_context */
+
+#ifndef EGL_MESA_drm_display
+#define EGL_MESA_drm_display 1
+
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLDisplay EGLAPIENTRY eglGetDRMDisplayMESA(int fd);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+
+typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETDRMDISPLAYMESA) (int fd);
+
+#endif /* EGL_MESA_drm_display */
+
 #ifndef EGL_KHR_image_base
 #define EGL_KHR_image_base 1
 /* Most interfaces defined by EGL_KHR_image_pixmap above */
@@ -243,13 +349,13 @@ typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBNVPROC) (EGLSyncNV sync, EGL
  * Structure representing a client pixmap
  * (pixmap's data is in client-space memory).
  */
-typedef struct EGLClientPixmapHI
+struct EGLClientPixmapHI
 {
 	void*		pData;
 	EGLint		iWidth;
 	EGLint		iHeight;
 	EGLint		iStride;
-} EGLClientPixmapHI;
+};
 
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI(EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap);
@@ -267,59 +373,23 @@ typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEHIPROC) (EGLDisplay dp
 #define EGL_COLOR_ARGB_HI			0x8F73
 #endif /* EGL_HI_colorformats */
 
-#ifndef EGL_MESA_drm_image
-#define EGL_MESA_drm_image 1
-#define EGL_DRM_BUFFER_FORMAT_MESA		0x31D0	    /* CreateDRMImageMESA attribute */
-#define EGL_DRM_BUFFER_USE_MESA			0x31D1	    /* CreateDRMImageMESA attribute */
-#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA	0x31D2	    /* EGL_IMAGE_FORMAT_MESA attribute value */
-#define EGL_DRM_BUFFER_MESA			0x31D3	    /* eglCreateImageKHR target */
-#define EGL_DRM_BUFFER_STRIDE_MESA		0x31D4
-#define EGL_DRM_BUFFER_USE_SCANOUT_MESA		0x00000001  /* EGL_DRM_BUFFER_USE_MESA bits */
-#define EGL_DRM_BUFFER_USE_SHARE_MESA		0x00000002  /* EGL_DRM_BUFFER_USE_MESA bits */
+#ifndef EGL_NOK_swap_region
+#define EGL_NOK_swap_region 1
+
 #ifdef EGL_EGLEXT_PROTOTYPES
-EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA (EGLDisplay dpy, const EGLint *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
-#endif /* EGL_EGLEXT_PROTOTYPES */
-typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy, const EGLint *attrib_list);
-typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersRegionNOK(EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint* rects);
 #endif
 
-/**
- * Added a few NVidia extensions here.
- * FIXME: Double check if they are still 'active'
- */
-
-/* EGL_NV_texture_rectangle (reuse analagous WGL enum) */
-#ifndef EGL_NV_texture_rectangle
-#define EGL_NV_texture_rectangle 1
-#define EGL_GL_TEXTURE_RECTANGLE_NV_KHR           0x30BB
-#define EGL_TEXTURE_RECTANGLE_NV       0x20A2
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGIONNOK) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint* rects);
 #endif
 
-#include "egl-64bit-types.h"
 
-#ifndef EGL_NV_system_time
-#define EGL_NV_system_time 1
-#ifdef EGL_EGLEXT_PROTOTYPES
-EGLAPI EGLuint64 EGLAPIENTRY eglGetSystemTimeFrequencyNV(void);
-EGLAPI EGLuint64 EGLAPIENTRY eglGetSystemTimeNV(void);
-#endif
-typedef EGLuint64 (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC)(void);
-typedef EGLuint64 (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC)(void);
-#endif
+#ifndef EGL_NOK_texture_from_pixmap
+#define EGL_NOK_texture_from_pixmap 1
 
-/* EGL_NV_omx_il_sink
- */
-#ifndef EGL_NV_omx_il_sink
-#define EGL_NV_omx_il_sink
-#define EGL_OPENMAX_IL_BIT_NV  0x0010 /* EGL_RENDERABLE_TYPE bit */
-#define EGL_SURFACE_OMX_IL_EVENT_CALLBACK_NV 0x309A /* eglCreate*Surface attribute */
-#define EGL_SURFACE_OMX_IL_EMPTY_BUFFER_DONE_CALLBACK_NV 0x309B /* eglCreate*Surface attribute */
-#define EGL_SURFACE_OMX_IL_CALLBACK_DATA_NV 0x309C /* eglCreate*Surface attribute */
-#define EGL_SURFACE_COMPONENT_HANDLE_NV 0x309D /* eglQuerySurface attribute */
-#endif
+#define EGL_Y_INVERTED_NOK			0x307F
+#endif /* EGL_NOK_texture_from_pixmap */
 
-#define EGL_RMSURFACE_NV 0x30EF /* eglCreateImageKHR target */
 
 #ifdef __cplusplus
 }
diff --git a/make/stub_includes/egl/EGL/eglplatform.h b/src/test-native/mesa-demos-patched/EGL/eglplatform.h
similarity index 84%
copy from make/stub_includes/egl/EGL/eglplatform.h
copy to src/test-native/mesa-demos-patched/EGL/eglplatform.h
index a661736..fbfdce3 100644
--- a/make/stub_includes/egl/EGL/eglplatform.h
+++ b/src/test-native/mesa-demos-patched/EGL/eglplatform.h
@@ -25,7 +25,7 @@
 */
 
 /* Platform-specific types and definitions for egl.h
- * $Revision: 12306 $ on $Date: 2010-08-25 09:51:28 -0700 (Wed, 25 Aug 2010) $
+ * $Revision: 9724 $ on $Date: 2009-12-02 02:05:33 -0800 (Wed, 02 Dec 2009) $
  *
  * Adopters may modify khrplatform.h and this file to suit their platform.
  * You are encouraged to submit all modifications to the Khronos group so that
@@ -60,11 +60,6 @@
  * Windows Device Context. They must be defined in platform-specific
  * code below. The EGL-prefixed versions of Native*Type are the same
  * types, renamed in EGL 1.3 so all types in the API start with "EGL".
- *
- * Khronos STRONGLY RECOMMENDS that you use the default definitions
- * provided below, since these changes affect both binary and source
- * portability of applications using EGL running on different EGL
- * implementations.
  */
 
 #if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
@@ -83,7 +78,27 @@ typedef int   EGLNativeDisplayType;
 typedef void *EGLNativeWindowType;
 typedef void *EGLNativePixmapType;
 
-#elif defined(__X11__)
+#elif defined(WL_EGL_PLATFORM)
+
+typedef struct wl_display     *EGLNativeDisplayType;
+typedef struct wl_egl_pixmap  *EGLNativePixmapType;
+typedef struct wl_egl_window  *EGLNativeWindowType;
+
+#elif defined(__GBM__)
+
+typedef struct gbm_device  *EGLNativeDisplayType;
+typedef struct gbm_bo      *EGLNativePixmapType;
+typedef void               *EGLNativeWindowType;
+
+#elif defined(__unix__) || defined(__unix)
+
+#ifdef MESA_EGL_NO_X11_HEADERS
+
+typedef void            *EGLNativeDisplayType;
+typedef khronos_uint32_t EGLNativePixmapType;
+typedef khronos_uint32_t EGLNativeWindowType;
+
+#else
 
 /* X11 (tentative)  */
 #include <X11/Xlib.h>
@@ -93,14 +108,10 @@ typedef Display *EGLNativeDisplayType;
 typedef Pixmap   EGLNativePixmapType;
 typedef Window   EGLNativeWindowType;
 
-#else
-
-#warning "Info: Using generic void pointer for EGLNativeDisplayType, EGLNativeWindowType and EGLNativePixmapType"
-
-typedef void* EGLNativeDisplayType;
-typedef void* EGLNativeWindowType;
-typedef void* EGLNativePixmapType;
+#endif /* MESA_EGL_NO_X11_HEADERS */
 
+#else
+#error "Platform not recognized"
 #endif
 
 /* EGL 1.2 types, renamed for consistency in EGL 1.3 */
diff --git a/src/test-native/mesa-demos-patched/eglut/eglut.c b/src/test-native/mesa-demos-patched/eglut/eglut.c
new file mode 100644
index 0000000..eb72f64
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/eglut/eglut.c
@@ -0,0 +1,400 @@
+/*
+ * Copyright (C) 2010 LunarG Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Chia-I Wu <olv at lunarg.com>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <sys/time.h>
+
+#include "EGL/egl.h"
+#include "EGL/eglext.h"
+
+#include "eglutint.h"
+
+static struct eglut_state _eglut_state = {
+   .api_mask = EGLUT_OPENGL_ES1_BIT,
+   .window_width = 300,
+   .window_height = 300,
+   .verbose = 0,
+   .num_windows = 0,
+};
+
+struct eglut_state *_eglut = &_eglut_state;
+
+void
+_eglutFatal(char *format, ...)
+{
+  va_list args;
+
+  va_start(args, format);
+
+  fprintf(stderr, "EGLUT: ");
+  vfprintf(stderr, format, args);
+  va_end(args);
+  putc('\n', stderr);
+
+  exit(1);
+}
+
+/* return current time (in milliseconds) */
+int
+_eglutNow(void)
+{
+   struct timeval tv;
+#ifdef __VMS
+   (void) gettimeofday(&tv, NULL );
+#else
+   struct timezone tz;
+   (void) gettimeofday(&tv, &tz);
+#endif
+   return tv.tv_sec * 1000 + tv.tv_usec / 1000;
+}
+
+static void
+_eglutDestroyWindow(struct eglut_window *win)
+{
+   if (_eglut->surface_type != EGL_PBUFFER_BIT &&
+       _eglut->surface_type != EGL_SCREEN_BIT_MESA)
+      eglDestroySurface(_eglut->dpy, win->surface);
+
+   _eglutNativeFiniWindow(win);
+
+   eglDestroyContext(_eglut->dpy, win->context);
+}
+
+static EGLConfig
+_eglutChooseConfig(void)
+{
+   EGLConfig config;
+   EGLint config_attribs[32];
+   EGLint renderable_type, num_configs, i;
+   EGLint cfgid, vid;
+
+   i = 0;
+   config_attribs[i++] = EGL_RED_SIZE;
+   config_attribs[i++] = 1;
+   config_attribs[i++] = EGL_GREEN_SIZE;
+   config_attribs[i++] = 1;
+   config_attribs[i++] = EGL_BLUE_SIZE;
+   config_attribs[i++] = 1;
+   config_attribs[i++] = EGL_DEPTH_SIZE;
+   config_attribs[i++] = 1;
+
+   config_attribs[i++] = EGL_SURFACE_TYPE;
+   config_attribs[i++] = _eglut->surface_type;
+
+   config_attribs[i++] = EGL_RENDERABLE_TYPE;
+   renderable_type = 0x0;
+   if (_eglut->api_mask & EGLUT_OPENGL_BIT)
+      renderable_type |= EGL_OPENGL_BIT;
+   if (_eglut->api_mask & EGLUT_OPENGL_ES1_BIT)
+      renderable_type |= EGL_OPENGL_ES_BIT;
+   if (_eglut->api_mask & EGLUT_OPENGL_ES2_BIT)
+      renderable_type |= EGL_OPENGL_ES2_BIT;
+   if (_eglut->api_mask & EGLUT_OPENVG_BIT)
+      renderable_type |= EGL_OPENVG_BIT;
+   config_attribs[i++] = renderable_type;
+
+   config_attribs[i] = EGL_NONE;
+
+   if (!eglChooseConfig(_eglut->dpy,
+            config_attribs, &config, 1, &num_configs) || !num_configs)
+      _eglutFatal("failed to choose a config");
+
+   if (!eglGetConfigAttrib(_eglut->dpy,
+            config, EGL_CONFIG_ID, &cfgid))
+      _eglutFatal("failed to get visual id");
+   if (!eglGetConfigAttrib(_eglut->dpy,
+            config, EGL_NATIVE_VISUAL_ID, &vid))
+      _eglutFatal("failed to get visual id");
+
+   fprintf(stderr, "eglChooseConfig egl-cfg-id 0x%X, vid 0x%X\n", cfgid, vid);
+
+   return config;
+}
+
+static struct eglut_window *
+_eglutCreateWindow(const char *title, int x, int y, int w, int h)
+{
+   struct eglut_window *win;
+   EGLint context_attribs[4];
+   EGLint api, i;
+
+   win = calloc(1, sizeof(*win));
+   if (!win)
+      _eglutFatal("failed to allocate window");
+
+   win->config = _eglutChooseConfig();
+
+   i = 0;
+   context_attribs[i] = EGL_NONE;
+
+   /* multiple APIs? */
+
+   api = EGL_OPENGL_ES_API;
+   if (_eglut->api_mask & EGLUT_OPENGL_BIT) {
+      api = EGL_OPENGL_API;
+   }
+   else if (_eglut->api_mask & EGLUT_OPENVG_BIT) {
+      api = EGL_OPENVG_API;
+   }
+   else if (_eglut->api_mask & EGLUT_OPENGL_ES2_BIT) {
+      context_attribs[i++] = EGL_CONTEXT_CLIENT_VERSION;
+      context_attribs[i++] = 2;
+   }
+
+   context_attribs[i] = EGL_NONE;
+
+   eglBindAPI(api);
+   win->context = eglCreateContext(_eglut->dpy,
+         win->config, EGL_NO_CONTEXT, context_attribs);
+   if (!win->context)
+      _eglutFatal("failed to create context");
+
+   _eglutNativeInitWindow(win, title, x, y, w, h);
+   switch (_eglut->surface_type) {
+   case EGL_WINDOW_BIT:
+      win->surface = eglCreateWindowSurface(_eglut->dpy,
+            win->config, win->native.u.window, NULL);
+      break;
+   case EGL_PIXMAP_BIT:
+      win->surface = eglCreatePixmapSurface(_eglut->dpy,
+            win->config, win->native.u.pixmap, NULL);
+      break;
+   case EGL_PBUFFER_BIT:
+   case EGL_SCREEN_BIT_MESA:
+      win->surface = win->native.u.surface;
+      break;
+   default:
+      break;
+   }
+   if (win->surface == EGL_NO_SURFACE)
+      _eglutFatal("failed to create surface");
+
+   return win;
+}
+
+void
+eglutInitAPIMask(int mask)
+{
+   _eglut->api_mask = mask;
+}
+
+void
+eglutInitWindowSize(int width, int height)
+{
+   _eglut->window_width = width;
+   _eglut->window_height = height;
+}
+
+void
+eglutInit(int argc, char **argv)
+{
+   int i;
+
+   for (i = 1; i < argc; i++) {
+      if (strcmp(argv[i], "-display") == 0)
+         _eglut->display_name = argv[++i];
+      else if (strcmp(argv[i], "-info") == 0) {
+         _eglut->verbose = 1;
+      }
+   }
+
+   _eglutNativeInitDisplay();
+   _eglut->dpy = eglGetDisplay(_eglut->native_dpy);
+
+   if (!eglInitialize(_eglut->dpy, &_eglut->major, &_eglut->minor))
+      _eglutFatal("failed to initialize EGL display");
+
+   _eglut->init_time = _eglutNow();
+
+   printf("EGL_VERSION = %s\n", eglQueryString(_eglut->dpy, EGL_VERSION));
+   if (_eglut->verbose) {
+      printf("EGL_VENDOR = %s\n", eglQueryString(_eglut->dpy, EGL_VENDOR));
+      printf("EGL_EXTENSIONS = %s\n",
+            eglQueryString(_eglut->dpy, EGL_EXTENSIONS));
+      printf("EGL_CLIENT_APIS = %s\n",
+            eglQueryString(_eglut->dpy, EGL_CLIENT_APIS));
+   }
+}
+
+int
+eglutGet(int state)
+{
+   int val;
+
+   switch (state) {
+   case EGLUT_ELAPSED_TIME:
+      val = _eglutNow() - _eglut->init_time;
+      break;
+   default:
+      val = -1;
+      break;
+   }
+
+   return val;
+}
+
+void
+eglutIdleFunc(EGLUTidleCB func)
+{
+   _eglut->idle_cb = func;
+}
+
+void
+eglutPostRedisplay(void)
+{
+   _eglut->redisplay = 1;
+}
+
+void
+eglutMainLoop(void)
+{
+   struct eglut_window *win = _eglut->current;
+
+   if (!win)
+      _eglutFatal("no window is created\n");
+
+   if (win->reshape_cb)
+      win->reshape_cb(win->native.width, win->native.height);
+
+   _eglut->stop_loop = 0;
+   _eglutNativeEventLoop();
+}
+
+void
+eglutStopMainLoop(void)
+{
+   _eglut->stop_loop = 1;
+}
+
+static void
+_eglutFini(void)
+{
+   eglTerminate(_eglut->dpy);
+   _eglutNativeFiniDisplay();
+}
+
+void
+eglutTerminate(void)
+{
+    _eglutFini();
+}
+
+void
+eglutDestroyWindow(int win)
+{
+   struct eglut_window *window = _eglut->current;
+
+   if (window->index != win)
+      return;
+
+   /* XXX it causes some bug in st/egl KMS backend */
+   if ( _eglut->surface_type != EGL_SCREEN_BIT_MESA)
+      eglMakeCurrent(_eglut->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+
+   _eglutDestroyWindow(_eglut->current);
+}
+
+static void
+_eglutDefaultKeyboard(unsigned char key)
+{
+   if (key == 27) {
+      if (_eglut->current)
+         eglutDestroyWindow(_eglut->current->index);
+      _eglutFini();
+
+      exit(0);
+   }
+}
+
+int
+eglutCreateWindow(const char *title)
+{
+   struct eglut_window *win;
+
+   win = _eglutCreateWindow(title, 0, 0,
+         _eglut->window_width, _eglut->window_height);
+
+   win->index = _eglut->num_windows++;
+   win->reshape_cb = NULL;
+   win->display_cb = NULL;
+   win->keyboard_cb = _eglutDefaultKeyboard;
+   win->special_cb = NULL;
+
+   if (!eglMakeCurrent(_eglut->dpy, win->surface, win->surface, win->context))
+      _eglutFatal("failed to make window current");
+   _eglut->current = win;
+
+   return win->index;
+}
+
+void eglutSwapInterval(EGLint interval) {
+   eglSwapInterval(_eglut->dpy, interval);
+}
+
+int
+eglutGetWindowWidth(void)
+{
+   struct eglut_window *win = _eglut->current;
+   return win->native.width;
+}
+
+int
+eglutGetWindowHeight(void)
+{
+   struct eglut_window *win = _eglut->current;
+   return win->native.height;
+}
+
+void
+eglutDisplayFunc(EGLUTdisplayCB func)
+{
+   struct eglut_window *win = _eglut->current;
+   win->display_cb = func;
+
+}
+
+void
+eglutReshapeFunc(EGLUTreshapeCB func)
+{
+   struct eglut_window *win = _eglut->current;
+   win->reshape_cb = func;
+}
+
+void
+eglutKeyboardFunc(EGLUTkeyboardCB func)
+{
+   struct eglut_window *win = _eglut->current;
+   win->keyboard_cb = func;
+}
+
+void
+eglutSpecialFunc(EGLUTspecialCB func)
+{
+   struct eglut_window *win = _eglut->current;
+   win->special_cb = func;
+}
diff --git a/src/test-native/mesa-demos-patched/eglut/eglut.h b/src/test-native/mesa-demos-patched/eglut/eglut.h
new file mode 100644
index 0000000..b1758ff
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/eglut/eglut.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2010 LunarG Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Chia-I Wu <olv at lunarg.com>
+ */
+
+#ifndef EGLUT_H
+#define EGLUT_H
+
+/* used by eglutInitAPIMask */
+enum {
+   EGLUT_OPENGL_BIT     = 0x1,
+   EGLUT_OPENGL_ES1_BIT = 0x2,
+   EGLUT_OPENGL_ES2_BIT = 0x4,
+   EGLUT_OPENVG_BIT     = 0x8
+};
+
+/* used by EGLUTspecialCB */
+enum {
+   /* function keys */
+   EGLUT_KEY_F1,
+   EGLUT_KEY_F2,
+   EGLUT_KEY_F3,
+   EGLUT_KEY_F4,
+   EGLUT_KEY_F5,
+   EGLUT_KEY_F6,
+   EGLUT_KEY_F7,
+   EGLUT_KEY_F8,
+   EGLUT_KEY_F9,
+   EGLUT_KEY_F10,
+   EGLUT_KEY_F11,
+   EGLUT_KEY_F12,
+
+   /* directional keys */
+   EGLUT_KEY_LEFT,
+   EGLUT_KEY_UP,
+   EGLUT_KEY_RIGHT,
+   EGLUT_KEY_DOWN,
+};
+
+/* used by eglutGet */
+enum {
+   EGLUT_ELAPSED_TIME
+};
+
+typedef void (*EGLUTidleCB)(void);
+typedef void (*EGLUTreshapeCB)(int, int);
+typedef void (*EGLUTdisplayCB)(void);
+typedef void (*EGLUTkeyboardCB)(unsigned char);
+typedef void (*EGLUTspecialCB)(int);
+
+void eglutInitAPIMask(int mask);
+void eglutInitWindowSize(int width, int height);
+void eglutInit(int argc, char **argv);
+
+int eglutGet(int state);
+
+void eglutIdleFunc(EGLUTidleCB func);
+void eglutPostRedisplay(void);
+void eglutSwapInterval(EGLint interval);
+
+void eglutMainLoop(void);
+void eglutStopMainLoop(void);
+
+int eglutCreateWindow(const char *title);
+void eglutDestroyWindow(int win);
+void eglutTerminate(void);
+
+int eglutGetWindowWidth(void);
+int eglutGetWindowHeight(void);
+
+void eglutDisplayFunc(EGLUTdisplayCB func);
+void eglutReshapeFunc(EGLUTreshapeCB func);
+void eglutKeyboardFunc(EGLUTkeyboardCB func);
+void eglutSpecialFunc(EGLUTspecialCB func);
+
+#endif /* EGLUT_H */
diff --git a/src/test-native/mesa-demos-patched/eglut/eglut_screen.c b/src/test-native/mesa-demos-patched/eglut/eglut_screen.c
new file mode 100644
index 0000000..727e57f
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/eglut/eglut_screen.c
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2010 LunarG Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Chia-I Wu <olv at lunarg.com>
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+
+#define EGL_EGLEXT_PROTOTYPES
+#include "EGL/egl.h"
+#include "EGL/eglext.h"
+
+#include "eglutint.h"
+
+#define MAX_MODES 100
+
+static EGLScreenMESA kms_screen;
+static EGLModeMESA kms_mode;
+static EGLint kms_width, kms_height;
+
+void
+_eglutNativeInitDisplay(void)
+{
+   _eglut->native_dpy = EGL_DEFAULT_DISPLAY;
+   _eglut->surface_type = EGL_SCREEN_BIT_MESA;
+}
+
+void
+_eglutNativeFiniDisplay(void)
+{
+   kms_screen = 0;
+   kms_mode = 0;
+   kms_width = 0;
+   kms_height = 0;
+}
+
+static void
+init_kms(void)
+{
+   EGLModeMESA modes[MAX_MODES];
+   EGLint num_screens, num_modes;
+   EGLint width, height, best_mode;
+   EGLint i;
+
+   if (!eglGetScreensMESA(_eglut->dpy, &kms_screen, 1, &num_screens) ||
+         !num_screens)
+      _eglutFatal("eglGetScreensMESA failed\n");
+
+   if (!eglGetModesMESA(_eglut->dpy, kms_screen,
+            modes, MAX_MODES, &num_modes) || !num_modes)
+      _eglutFatal("eglGetModesMESA failed!\n");
+
+   printf("Found %d modes:\n", num_modes);
+
+   best_mode = 0;
+   width = 0;
+   height = 0;
+   for (i = 0; i < num_modes; i++) {
+      EGLint w, h;
+      eglGetModeAttribMESA(_eglut->dpy, modes[i], EGL_WIDTH, &w);
+      eglGetModeAttribMESA(_eglut->dpy, modes[i], EGL_HEIGHT, &h);
+      printf("%3d: %d x %d\n", i, w, h);
+      if (w > width && h > height) {
+         width = w;
+         height = h;
+         best_mode = i;
+      }
+   }
+
+   printf("Will use screen size: %d x %d\n", width, height);
+
+   kms_mode = modes[best_mode];
+   kms_width = width;
+   kms_height = height;
+}
+
+void
+_eglutNativeInitWindow(struct eglut_window *win, const char *title,
+                       int x, int y, int w, int h)
+{
+   EGLint surf_attribs[16];
+   EGLint i;
+   const char *exts;
+
+   exts = eglQueryString(_eglut->dpy, EGL_EXTENSIONS);
+   if (!exts || !strstr(exts, "EGL_MESA_screen_surface"))
+      _eglutFatal("EGL_MESA_screen_surface is not supported\n");
+
+   init_kms();
+
+   i = 0;
+   surf_attribs[i++] = EGL_WIDTH;
+   surf_attribs[i++] = kms_width;
+   surf_attribs[i++] = EGL_HEIGHT;
+   surf_attribs[i++] = kms_height;
+   surf_attribs[i++] = EGL_NONE;
+
+   /* create surface */
+   win->native.u.surface = eglCreateScreenSurfaceMESA(_eglut->dpy,
+         win->config, surf_attribs);
+   if (win->native.u.surface == EGL_NO_SURFACE)
+      _eglutFatal("eglCreateScreenSurfaceMESA failed\n");
+
+   if (!eglShowScreenSurfaceMESA(_eglut->dpy, kms_screen,
+            win->native.u.surface, kms_mode))
+      _eglutFatal("eglShowScreenSurfaceMESA failed\n");
+
+   win->native.width = kms_width;
+   win->native.height = kms_height;
+}
+
+void
+_eglutNativeFiniWindow(struct eglut_window *win)
+{
+   eglShowScreenSurfaceMESA(_eglut->dpy,
+         kms_screen, EGL_NO_SURFACE, 0);
+   eglDestroySurface(_eglut->dpy, win->native.u.surface);
+}
+
+void
+_eglutNativeEventLoop(void)
+{
+   int start = _eglutNow();
+   int frames = 0;
+
+   _eglut->redisplay = 1;
+
+   while (!_eglut->stop_loop) {
+      struct eglut_window *win = _eglut->current;
+      int now = _eglutNow();
+
+      if (now - start > 5000) {
+         double elapsed = (double) (now - start) / 1000.0;
+
+         printf("%d frames in %3.1f seconds = %6.3f FPS\n",
+               frames, elapsed, frames / elapsed);
+         fflush(stdout);
+
+         start = now;
+         frames = 0;
+
+         /* send escape */
+         if (win->keyboard_cb)
+            win->keyboard_cb(27);
+      }
+
+      if (_eglut->idle_cb)
+         _eglut->idle_cb();
+
+      if (_eglut->redisplay) {
+         _eglut->redisplay = 0;
+
+         if (win->display_cb)
+            win->display_cb();
+         eglSwapBuffers(_eglut->dpy, win->surface);
+         frames++;
+      }
+   }
+}
diff --git a/src/test-native/mesa-demos-patched/eglut/eglut_x11.c b/src/test-native/mesa-demos-patched/eglut/eglut_x11.c
new file mode 100644
index 0000000..e37e52b
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/eglut/eglut_x11.c
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2010 LunarG Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Chia-I Wu <olv at lunarg.com>
+ */
+
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <X11/keysym.h>
+
+#include "eglutint.h"
+
+void
+_eglutNativeInitDisplay(void)
+{
+   _eglut->native_dpy = XOpenDisplay(_eglut->display_name);
+   if (!_eglut->native_dpy)
+      _eglutFatal("failed to initialize native display");
+
+   _eglut->surface_type = EGL_WINDOW_BIT;
+}
+
+void
+_eglutNativeFiniDisplay(void)
+{
+   XCloseDisplay(_eglut->native_dpy);
+}
+
+void
+_eglutNativeInitWindow(struct eglut_window *win, const char *title,
+                       int x, int y, int w, int h)
+{
+   XVisualInfo *visInfo, visTemplate;
+   int num_visuals;
+   Window root, xwin;
+   XSetWindowAttributes attr;
+   unsigned long mask;
+   EGLint vid;
+
+   if (!eglGetConfigAttrib(_eglut->dpy,
+            win->config, EGL_NATIVE_VISUAL_ID, &vid))
+      _eglutFatal("failed to get visual id");
+
+   /* The X window visual must match the EGL config */
+   visTemplate.visualid = vid;
+   visInfo = XGetVisualInfo(_eglut->native_dpy,
+         VisualIDMask, &visTemplate, &num_visuals);
+   if (!visInfo)
+      _eglutFatal("failed to get an visual of id 0x%x", vid);
+
+   root = RootWindow(_eglut->native_dpy, DefaultScreen(_eglut->native_dpy));
+
+   /* window attributes */
+   attr.background_pixel = 0;
+   attr.border_pixel = 0;
+   attr.colormap = XCreateColormap(_eglut->native_dpy,
+         root, visInfo->visual, AllocNone);
+   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
+   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
+
+   xwin = XCreateWindow(_eglut->native_dpy, root, x, y, w, h,
+         0, visInfo->depth, InputOutput, visInfo->visual, mask, &attr);
+   if (!xwin)
+      _eglutFatal("failed to create a window");
+
+   XFree(visInfo);
+
+   /* set hints and properties */
+   {
+      XSizeHints sizehints;
+      sizehints.x = x;
+      sizehints.y = y;
+      sizehints.width  = w;
+      sizehints.height = h;
+      sizehints.flags = USSize | USPosition;
+      XSetNormalHints(_eglut->native_dpy, xwin, &sizehints);
+      XSetStandardProperties(_eglut->native_dpy, xwin,
+            title, title, None, (char **) NULL, 0, &sizehints);
+   }
+
+   XMapWindow(_eglut->native_dpy, xwin);
+
+   win->native.u.window = xwin;
+   win->native.width = w;
+   win->native.height = h;
+}
+
+void
+_eglutNativeFiniWindow(struct eglut_window *win)
+{
+   XDestroyWindow(_eglut->native_dpy, win->native.u.window);
+}
+
+static int
+lookup_keysym(KeySym sym)
+{
+   int special;
+
+   switch (sym) {
+   case XK_F1:
+      special = EGLUT_KEY_F1;
+      break;
+   case XK_F2:
+      special = EGLUT_KEY_F2;
+      break;
+   case XK_F3:
+      special = EGLUT_KEY_F3;
+      break;
+   case XK_F4:
+      special = EGLUT_KEY_F4;
+      break;
+   case XK_F5:
+      special = EGLUT_KEY_F5;
+      break;
+   case XK_F6:
+      special = EGLUT_KEY_F6;
+      break;
+   case XK_F7:
+      special = EGLUT_KEY_F7;
+      break;
+   case XK_F8:
+      special = EGLUT_KEY_F8;
+      break;
+   case XK_F9:
+      special = EGLUT_KEY_F9;
+      break;
+   case XK_F10:
+      special = EGLUT_KEY_F10;
+      break;
+   case XK_F11:
+      special = EGLUT_KEY_F11;
+      break;
+   case XK_F12:
+      special = EGLUT_KEY_F12;
+      break;
+   case XK_KP_Left:
+   case XK_Left:
+      special = EGLUT_KEY_LEFT;
+      break;
+   case XK_KP_Up:
+   case XK_Up:
+      special = EGLUT_KEY_UP;
+      break;
+   case XK_KP_Right:
+   case XK_Right:
+      special = EGLUT_KEY_RIGHT;
+      break;
+   case XK_KP_Down:
+   case XK_Down:
+      special = EGLUT_KEY_DOWN;
+      break;
+   default:
+      special = -1;
+      break;
+   }
+
+   return special;
+}
+
+static void
+next_event(struct eglut_window *win)
+{
+   int redraw = 0;
+   XEvent event;
+
+   if (!XPending(_eglut->native_dpy)) {
+      /* there is an idle callback */
+      if (_eglut->idle_cb) {
+         _eglut->idle_cb();
+         return;
+      }
+
+      /* the app requests re-display */
+      if (_eglut->redisplay)
+         return;
+   }
+
+   /* block for next event */
+   XNextEvent(_eglut->native_dpy, &event);
+
+   switch (event.type) {
+   case Expose:
+      redraw = 1;
+      break;
+   case ConfigureNotify:
+      win->native.width = event.xconfigure.width;
+      win->native.height = event.xconfigure.height;
+      if (win->reshape_cb)
+         win->reshape_cb(win->native.width, win->native.height);
+      break;
+   case KeyPress:
+      {
+         char buffer[1];
+         KeySym sym;
+         int r;
+
+         r = XLookupString(&event.xkey,
+               buffer, sizeof(buffer), &sym, NULL);
+         if (r && win->keyboard_cb) {
+            win->keyboard_cb(buffer[0]);
+         }
+         else if (!r && win->special_cb) {
+            r = lookup_keysym(sym);
+            if (r >= 0)
+               win->special_cb(r);
+         }
+      }
+      redraw = 1;
+      break;
+   default:
+      ; /*no-op*/
+   }
+
+   _eglut->redisplay = redraw;
+}
+
+void
+_eglutNativeEventLoop(void)
+{
+   while (!_eglut->stop_loop) {
+      struct eglut_window *win = _eglut->current;
+
+      next_event(win);
+
+      if (_eglut->redisplay) {
+         _eglut->redisplay = 0;
+
+         if (win->display_cb)
+            win->display_cb();
+         eglSwapBuffers(_eglut->dpy, win->surface);
+      }
+   }
+}
diff --git a/src/test-native/mesa-demos-patched/eglut/eglutint.h b/src/test-native/mesa-demos-patched/eglut/eglutint.h
new file mode 100644
index 0000000..449df28
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/eglut/eglutint.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2010 LunarG Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Chia-I Wu <olv at lunarg.com>
+ */
+
+#ifndef _EGLUTINT_H_
+#define _EGLUTINT_H_
+
+#include "EGL/egl.h"
+#include "eglut.h"
+
+struct eglut_window {
+   EGLConfig config;
+   EGLContext context;
+
+   /* initialized by native display */
+   struct {
+      union {
+         EGLNativeWindowType window;
+         EGLNativePixmapType pixmap;
+         EGLSurface surface; /* pbuffer or screen surface */
+      } u;
+      int width, height;
+   } native;
+
+   EGLSurface surface;
+
+   int index;
+
+   EGLUTreshapeCB reshape_cb;
+   EGLUTdisplayCB display_cb;
+   EGLUTkeyboardCB keyboard_cb;
+   EGLUTspecialCB special_cb;
+};
+
+struct eglut_state {
+   int api_mask;
+   int window_width, window_height;
+   const char *display_name;
+   int verbose;
+   int init_time;
+
+   EGLUTidleCB idle_cb;
+
+   int num_windows;
+
+   /* initialized by native display */
+   EGLNativeDisplayType native_dpy;
+   EGLint surface_type;
+
+   EGLDisplay dpy;
+   EGLint major, minor;
+
+   struct eglut_window *current;
+
+   int redisplay;
+   int stop_loop;
+};
+
+extern struct eglut_state *_eglut;
+
+void
+_eglutFatal(char *format, ...);
+
+int
+_eglutNow(void);
+
+void
+_eglutNativeInitDisplay(void);
+
+void
+_eglutNativeFiniDisplay(void);
+
+void
+_eglutNativeInitWindow(struct eglut_window *win, const char *title,
+                       int x, int y, int w, int h);
+
+void
+_eglutNativeFiniWindow(struct eglut_window *win);
+
+void
+_eglutNativeEventLoop(void);
+
+#endif /* _EGLUTINT_H_ */
diff --git a/src/test-native/mesa-demos-patched/es2gears.c b/src/test-native/mesa-demos-patched/es2gears.c
new file mode 100644
index 0000000..10d3be0
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/es2gears.c
@@ -0,0 +1,751 @@
+/*
+ * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * Ported to GLES2.
+ * Kristian Høgsberg <krh at bitplanet.net>
+ * May 3, 2010
+ * 
+ * Improve GLES2 port:
+ *   * Refactor gear drawing.
+ *   * Use correct normals for surfaces.
+ *   * Improve shader.
+ *   * Use perspective projection transformation.
+ *   * Add FPS count.
+ *   * Add comments.
+ * Alexandros Frantzis <alexandros.frantzis at linaro.org>
+ * Jul 13, 2010
+ */
+
+#define GL_GLEXT_PROTOTYPES
+#define EGL_EGLEXT_PROTOTYPES
+
+#define _GNU_SOURCE
+
+#include <math.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <GLES2/gl2.h>
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include "eglut.h"
+
+static int demo_start_duration = 5000; // ms
+
+#define STRIPS_PER_TOOTH 7
+#define VERTICES_PER_TOOTH 34
+#define GEAR_VERTEX_STRIDE 6
+
+/**
+ * Struct describing the vertices in triangle strip
+ */
+struct vertex_strip {
+   /** The first vertex in the strip */
+   GLint first;
+   /** The number of consecutive vertices in the strip after the first */
+   GLint count;
+};
+
+/* Each vertex consist of GEAR_VERTEX_STRIDE GLfloat attributes */
+typedef GLfloat GearVertex[GEAR_VERTEX_STRIDE];
+
+/**
+ * Struct representing a gear.
+ */
+struct gear {
+   /** The array of vertices comprising the gear */
+   GearVertex *vertices;
+   /** The number of vertices comprising the gear */
+   int nvertices;
+   /** The array of triangle strips comprising the gear */
+   struct vertex_strip *strips;
+   /** The number of triangle strips comprising the gear */
+   int nstrips;
+   /** The Vertex Buffer Object holding the vertices in the graphics card */
+   GLuint vbo;
+};
+
+/** The view rotation [x, y, z] */
+static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
+/** The gears */
+static struct gear *gear1, *gear2, *gear3;
+/** The current gear rotation angle */
+static GLfloat angle = 0.0;
+/** The location of the shader uniforms */
+static GLuint ModelViewProjectionMatrix_location,
+              NormalMatrix_location,
+              LightSourcePosition_location,
+              MaterialColor_location;
+/** The projection matrix */
+static GLfloat ProjectionMatrix[16];
+/** The direction of the directional light for the scene */
+static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0};
+
+/** 
+ * Fills a gear vertex.
+ * 
+ * @param v the vertex to fill
+ * @param x the x coordinate
+ * @param y the y coordinate
+ * @param z the z coortinate
+ * @param n pointer to the normal table 
+ * 
+ * @return the operation error code
+ */
+static GearVertex *
+vert(GearVertex *v, GLfloat x, GLfloat y, GLfloat z, GLfloat n[3])
+{
+   v[0][0] = x;
+   v[0][1] = y;
+   v[0][2] = z;
+   v[0][3] = n[0];
+   v[0][4] = n[1];
+   v[0][5] = n[2];
+
+   return v + 1;
+}
+
+/**
+ *  Create a gear wheel.
+ * 
+ *  @param inner_radius radius of hole at center
+ *  @param outer_radius radius at center of teeth
+ *  @param width width of gear
+ *  @param teeth number of teeth
+ *  @param tooth_depth depth of tooth
+ *  
+ *  @return pointer to the constructed struct gear
+ */
+static struct gear *
+create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
+      GLint teeth, GLfloat tooth_depth)
+{
+   GLfloat r0, r1, r2;
+   GLfloat da;
+   GearVertex *v;
+   struct gear *gear;
+   double s[5], c[5];
+   GLfloat normal[3];
+   int cur_strip = 0;
+   int i;
+
+   /* Allocate memory for the gear */
+   gear = malloc(sizeof *gear);
+   if (gear == NULL)
+      return NULL;
+
+   /* Calculate the radii used in the gear */
+   r0 = inner_radius;
+   r1 = outer_radius - tooth_depth / 2.0;
+   r2 = outer_radius + tooth_depth / 2.0;
+
+   da = 2.0 * M_PI / teeth / 4.0;
+
+   /* Allocate memory for the triangle strip information */
+   gear->nstrips = STRIPS_PER_TOOTH * teeth;
+   gear->strips = calloc(gear->nstrips, sizeof (*gear->strips));
+
+   /* Allocate memory for the vertices */
+   gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices));
+   v = gear->vertices;
+
+   for (i = 0; i < teeth; i++) {
+      /* Calculate needed sin/cos for varius angles */
+      sincos(i * 2.0 * M_PI / teeth, &s[0], &c[0]);
+      sincos(i * 2.0 * M_PI / teeth + da, &s[1], &c[1]);
+      sincos(i * 2.0 * M_PI / teeth + da * 2, &s[2], &c[2]);
+      sincos(i * 2.0 * M_PI / teeth + da * 3, &s[3], &c[3]);
+      sincos(i * 2.0 * M_PI / teeth + da * 4, &s[4], &c[4]);
+
+      /* A set of macros for making the creation of the gears easier */
+#define  GEAR_POINT(r, da) { (r) * c[(da)], (r) * s[(da)] }
+#define  SET_NORMAL(x, y, z) do { \
+   normal[0] = (x); normal[1] = (y); normal[2] = (z); \
+} while(0)
+
+#define  GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal)
+
+#define START_STRIP do { \
+   gear->strips[cur_strip].first = v - gear->vertices; \
+} while(0);
+
+#define END_STRIP do { \
+   int _tmp = (v - gear->vertices); \
+   gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \
+   cur_strip++; \
+} while (0)
+
+#define QUAD_WITH_NORMAL(p1, p2) do { \
+   SET_NORMAL((p[(p1)].y - p[(p2)].y), -(p[(p1)].x - p[(p2)].x), 0); \
+   v = GEAR_VERT(v, (p1), -1); \
+   v = GEAR_VERT(v, (p1), 1); \
+   v = GEAR_VERT(v, (p2), -1); \
+   v = GEAR_VERT(v, (p2), 1); \
+} while(0)
+
+      struct point {
+         GLfloat x;
+         GLfloat y;
+      };
+
+      /* Create the 7 points (only x,y coords) used to draw a tooth */
+      struct point p[7] = {
+         GEAR_POINT(r2, 1), // 0
+         GEAR_POINT(r2, 2), // 1
+         GEAR_POINT(r1, 0), // 2
+         GEAR_POINT(r1, 3), // 3
+         GEAR_POINT(r0, 0), // 4
+         GEAR_POINT(r1, 4), // 5
+         GEAR_POINT(r0, 4), // 6
+      };
+
+      /* Front face */
+      START_STRIP;
+      SET_NORMAL(0, 0, 1.0);
+      v = GEAR_VERT(v, 0, +1);
+      v = GEAR_VERT(v, 1, +1);
+      v = GEAR_VERT(v, 2, +1);
+      v = GEAR_VERT(v, 3, +1);
+      v = GEAR_VERT(v, 4, +1);
+      v = GEAR_VERT(v, 5, +1);
+      v = GEAR_VERT(v, 6, +1);
+      END_STRIP;
+
+      /* Inner face */
+      START_STRIP;
+      QUAD_WITH_NORMAL(4, 6);
+      END_STRIP;
+
+      /* Back face */
+      START_STRIP;
+      SET_NORMAL(0, 0, -1.0);
+      v = GEAR_VERT(v, 6, -1);
+      v = GEAR_VERT(v, 5, -1);
+      v = GEAR_VERT(v, 4, -1);
+      v = GEAR_VERT(v, 3, -1);
+      v = GEAR_VERT(v, 2, -1);
+      v = GEAR_VERT(v, 1, -1);
+      v = GEAR_VERT(v, 0, -1);
+      END_STRIP;
+
+      /* Outer face */
+      START_STRIP;
+      QUAD_WITH_NORMAL(0, 2);
+      END_STRIP;
+
+      START_STRIP;
+      QUAD_WITH_NORMAL(1, 0);
+      END_STRIP;
+
+      START_STRIP;
+      QUAD_WITH_NORMAL(3, 1);
+      END_STRIP;
+
+      START_STRIP;
+      QUAD_WITH_NORMAL(5, 3);
+      END_STRIP;
+   }
+
+   gear->nvertices = (v - gear->vertices);
+
+   /* Store the vertices in a vertex buffer object (VBO) */
+   glGenBuffers(1, &gear->vbo);
+   glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
+   glBufferData(GL_ARRAY_BUFFER, gear->nvertices * sizeof(GearVertex),
+         gear->vertices, GL_STATIC_DRAW);
+
+   return gear;
+}
+
+/** 
+ * Multiplies two 4x4 matrices.
+ * 
+ * The result is stored in matrix m.
+ * 
+ * @param m the first matrix to multiply
+ * @param n the second matrix to multiply
+ */
+static void
+multiply(GLfloat *m, const GLfloat *n)
+{
+   GLfloat tmp[16];
+   const GLfloat *row, *column;
+   div_t d;
+   int i, j;
+
+   for (i = 0; i < 16; i++) {
+      tmp[i] = 0;
+      d = div(i, 4);
+      row = n + d.quot * 4;
+      column = m + d.rem;
+      for (j = 0; j < 4; j++)
+         tmp[i] += row[j] * column[j * 4];
+   }
+   memcpy(m, &tmp, sizeof tmp);
+}
+
+/** 
+ * Rotates a 4x4 matrix.
+ * 
+ * @param[in,out] m the matrix to rotate
+ * @param angle the angle to rotate
+ * @param x the x component of the direction to rotate to
+ * @param y the y component of the direction to rotate to
+ * @param z the z component of the direction to rotate to
+ */
+static void
+rotate(GLfloat *m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+   double s, c;
+
+   sincos(angle, &s, &c);
+   GLfloat r[16] = {
+      x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
+      x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0, 
+      x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
+      0, 0, 0, 1
+   };
+
+   multiply(m, r);
+}
+
+
+/** 
+ * Translates a 4x4 matrix.
+ * 
+ * @param[in,out] m the matrix to translate
+ * @param x the x component of the direction to translate to
+ * @param y the y component of the direction to translate to
+ * @param z the z component of the direction to translate to
+ */
+static void
+translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
+{
+   GLfloat t[16] = { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 };
+
+   multiply(m, t);
+}
+
+/** 
+ * Creates an identity 4x4 matrix.
+ * 
+ * @param m the matrix make an identity matrix
+ */
+static void
+identity(GLfloat *m)
+{
+   GLfloat t[16] = {
+      1.0, 0.0, 0.0, 0.0,
+      0.0, 1.0, 0.0, 0.0,
+      0.0, 0.0, 1.0, 0.0,
+      0.0, 0.0, 0.0, 1.0,
+   };
+
+   memcpy(m, t, sizeof(t));
+}
+
+/** 
+ * Transposes a 4x4 matrix.
+ *
+ * @param m the matrix to transpose
+ */
+static void 
+transpose(GLfloat *m)
+{
+   GLfloat t[16] = {
+      m[0], m[4], m[8],  m[12],
+      m[1], m[5], m[9],  m[13],
+      m[2], m[6], m[10], m[14],
+      m[3], m[7], m[11], m[15]};
+
+   memcpy(m, t, sizeof(t));
+}
+
+/**
+ * Inverts a 4x4 matrix.
+ *
+ * This function can currently handle only pure translation-rotation matrices.
+ * Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
+ * for an explanation.
+ */
+static void
+invert(GLfloat *m)
+{
+   GLfloat t[16];
+   identity(t);
+
+   // Extract and invert the translation part 't'. The inverse of a
+   // translation matrix can be calculated by negating the translation
+   // coordinates.
+   t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
+
+   // Invert the rotation part 'r'. The inverse of a rotation matrix is
+   // equal to its transpose.
+   m[12] = m[13] = m[14] = 0;
+   transpose(m);
+
+   // inv(m) = inv(r) * inv(t)
+   multiply(m, t);
+}
+
+/** 
+ * Calculate a perspective projection transformation.
+ * 
+ * @param m the matrix to save the transformation in
+ * @param fovy the field of view in the y direction
+ * @param aspect the view aspect ratio
+ * @param zNear the near clipping plane
+ * @param zFar the far clipping plane
+ */
+void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
+{
+   GLfloat tmp[16];
+   identity(tmp);
+
+   double sine, cosine, cotangent, deltaZ;
+   GLfloat radians = fovy / 2 * M_PI / 180;
+
+   deltaZ = zFar - zNear;
+   sincos(radians, &sine, &cosine);
+
+   if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
+      return;
+
+   cotangent = cosine / sine;
+
+   tmp[0] = cotangent / aspect;
+   tmp[5] = cotangent;
+   tmp[10] = -(zFar + zNear) / deltaZ;
+   tmp[11] = -1;
+   tmp[14] = -2 * zNear * zFar / deltaZ;
+   tmp[15] = 0;
+
+   memcpy(m, tmp, sizeof(tmp));
+}
+
+/**
+ * Draws a gear.
+ *
+ * @param gear the gear to draw
+ * @param transform the current transformation matrix
+ * @param x the x position to draw the gear at
+ * @param y the y position to draw the gear at
+ * @param angle the rotation angle of the gear
+ * @param color the color of the gear
+ */
+static void
+draw_gear(struct gear *gear, GLfloat *transform,
+      GLfloat x, GLfloat y, GLfloat angle, const GLfloat color[4])
+{
+   GLfloat model_view[16];
+   GLfloat normal_matrix[16];
+   GLfloat model_view_projection[16];
+
+   /* Translate and rotate the gear */
+   memcpy(model_view, transform, sizeof (model_view));
+   translate(model_view, x, y, 0);
+   rotate(model_view, 2 * M_PI * angle / 360.0, 0, 0, 1);
+
+   /* Create and set the ModelViewProjectionMatrix */
+   memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
+   multiply(model_view_projection, model_view);
+
+   glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
+                      model_view_projection);
+
+   /* 
+    * Create and set the NormalMatrix. It's the inverse transpose of the
+    * ModelView matrix.
+    */
+   memcpy(normal_matrix, model_view, sizeof (normal_matrix));
+   invert(normal_matrix);
+   transpose(normal_matrix);
+   glUniformMatrix4fv(NormalMatrix_location, 1, GL_FALSE, normal_matrix);
+
+   /* Set the gear color */
+   glUniform4fv(MaterialColor_location, 1, color);
+
+   /* Set the vertex buffer object to use */
+   glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
+
+   /* Set up the position of the attributes in the vertex buffer object */
+   glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
+         6 * sizeof(GLfloat), NULL);
+   glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
+         6 * sizeof(GLfloat), (GLfloat *) 0 + 3);
+
+   /* Enable the attributes */
+   glEnableVertexAttribArray(0);
+   glEnableVertexAttribArray(1);
+
+   /* Draw the triangle strips that comprise the gear */
+   int n;
+   for (n = 0; n < gear->nstrips; n++)
+      glDrawArrays(GL_TRIANGLE_STRIP, gear->strips[n].first, gear->strips[n].count);
+
+   /* Disable the attributes */
+   glDisableVertexAttribArray(1);
+   glDisableVertexAttribArray(0);
+}
+
+/** 
+ * Draws the gears.
+ */
+static void
+gears_draw(void)
+{
+   const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
+   const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
+   const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
+   GLfloat transform[16];
+   identity(transform);
+
+   glClearColor(0.0, 0.0, 0.0, 0.0);
+   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+   /* Translate and rotate the view */
+   translate(transform, 0, 0, -20);
+   rotate(transform, 2 * M_PI * view_rot[0] / 360.0, 1, 0, 0);
+   rotate(transform, 2 * M_PI * view_rot[1] / 360.0, 0, 1, 0);
+   rotate(transform, 2 * M_PI * view_rot[2] / 360.0, 0, 0, 1);
+
+   /* Draw the gears */
+   draw_gear(gear1, transform, -3.0, -2.0, angle, red);
+   draw_gear(gear2, transform, 3.1, -2.0, -2 * angle - 9.0, green);
+   draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
+}
+
+/** 
+ * Handles a new window size or exposure.
+ * 
+ * @param width the window width
+ * @param height the window height
+ */
+static void
+gears_reshape(int width, int height)
+{
+   /* Update the projection matrix */
+   perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
+
+   /* Set the viewport */
+   glViewport(0, 0, (GLint) width, (GLint) height);
+}
+
+/** 
+ * Handles special eglut events.
+ * 
+ * @param special the event to handle.
+ */
+static void
+gears_special(int special)
+{
+   switch (special) {
+      case EGLUT_KEY_LEFT:
+         view_rot[1] += 5.0;
+         break;
+      case EGLUT_KEY_RIGHT:
+         view_rot[1] -= 5.0;
+         break;
+      case EGLUT_KEY_UP:
+         view_rot[0] += 5.0;
+         break;
+      case EGLUT_KEY_DOWN:
+         view_rot[0] -= 5.0;
+         break;
+   }
+}
+
+static void
+gears_idle(void)
+{
+   static int frames = 0;
+   static double tRot0 = -1.0, tRate0 = -1.0;
+   int tms = eglutGet(EGLUT_ELAPSED_TIME);
+   double dt, t = tms / 1000.0;
+
+
+   if(tms>demo_start_duration) {
+        eglutStopMainLoop();
+        return;
+   }
+
+   if (tRot0 < 0.0)
+      tRot0 = t;
+   dt = t - tRot0;
+   tRot0 = t;
+
+   /* advance rotation for next frame */
+   angle += 70.0 * dt;  /* 70 degrees per second */
+   if (angle > 3600.0)
+      angle -= 3600.0;
+
+   eglutPostRedisplay();
+   frames++;
+
+   if (tRate0 < 0.0)
+      tRate0 = t;
+   if (t - tRate0 >= 5.0) {
+      GLfloat seconds = t - tRate0;
+      GLfloat fps = frames / seconds;
+      printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
+            fps);
+      tRate0 = t;
+      frames = 0;
+   }
+}
+
+static const char vertex_shader[] =
+"attribute vec3 position;\n"
+"attribute vec3 normal;\n"
+"\n"
+"uniform mat4 ModelViewProjectionMatrix;\n"
+"uniform mat4 NormalMatrix;\n"
+"uniform vec4 LightSourcePosition;\n"
+"uniform vec4 MaterialColor;\n"
+"\n"
+"varying vec4 Color;\n"
+"\n"
+"void main(void)\n"
+"{\n"
+"    // Transform the normal to eye coordinates\n"
+"    vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
+"\n"
+"    // The LightSourcePosition is actually its direction for directional light\n"
+"    vec3 L = normalize(LightSourcePosition.xyz);\n"
+"\n"
+"    // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
+"    // to get the actual color that we will use to draw this vertex with\n"
+"    float diffuse = max(dot(N, L), 0.0);\n"
+"    Color = diffuse * MaterialColor;\n"
+"\n"
+"    // Transform the position to clip coordinates\n"
+"    gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
+"}";
+
+static const char fragment_shader[] =
+"precision mediump float;\n"
+"varying vec4 Color;\n"
+"\n"
+"void main(void)\n"
+"{\n"
+"    gl_FragColor = Color;\n"
+"}";
+
+static void
+gears_init(void)
+{
+   GLuint v, f, program;
+   const char *p;
+   char msg[512];
+
+   glEnable(GL_CULL_FACE);
+   glEnable(GL_DEPTH_TEST);
+
+   /* Compile the vertex shader */
+   p = vertex_shader;
+   v = glCreateShader(GL_VERTEX_SHADER);
+   glShaderSource(v, 1, &p, NULL);
+   glCompileShader(v);
+   glGetShaderInfoLog(v, sizeof msg, NULL, msg);
+   printf("vertex shader info: %s\n", msg);
+
+   /* Compile the fragment shader */
+   p = fragment_shader;
+   f = glCreateShader(GL_FRAGMENT_SHADER);
+   glShaderSource(f, 1, &p, NULL);
+   glCompileShader(f);
+   glGetShaderInfoLog(f, sizeof msg, NULL, msg);
+   printf("fragment shader info: %s\n", msg);
+
+   /* Create and link the shader program */
+   program = glCreateProgram();
+   glAttachShader(program, v);
+   glAttachShader(program, f);
+   glBindAttribLocation(program, 0, "position");
+   glBindAttribLocation(program, 1, "normal");
+
+   glLinkProgram(program);
+   glGetProgramInfoLog(program, sizeof msg, NULL, msg);
+   printf("info: %s\n", msg);
+
+   /* Enable the shaders */
+   glUseProgram(program);
+
+   /* Get the locations of the uniforms so we can access them */
+   ModelViewProjectionMatrix_location = glGetUniformLocation(program, "ModelViewProjectionMatrix");
+   NormalMatrix_location = glGetUniformLocation(program, "NormalMatrix");
+   LightSourcePosition_location = glGetUniformLocation(program, "LightSourcePosition");
+   MaterialColor_location = glGetUniformLocation(program, "MaterialColor");
+
+   /* Set the LightSourcePosition uniform which is constant throught the program */
+   glUniform4fv(LightSourcePosition_location, 1, LightSourcePosition);
+
+   /* make the gears */
+   gear1 = create_gear(1.0, 4.0, 1.0, 20, 0.7);
+   gear2 = create_gear(0.5, 2.0, 2.0, 10, 0.7);
+   gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
+}
+
+int
+main(int argc, char *argv[])
+{
+   int demo_loops = 1;
+   int i;
+   for (i = 1; i < argc; i++) {
+      if (strcmp(argv[i], "-time") == 0) {
+         demo_start_duration = atoi(argv[++i]);
+      } else if (strcmp(argv[i], "-loops") == 0) {
+         demo_loops = atoi(argv[++i]);
+      }
+   }
+   fprintf(stderr, "duration: %d\n", demo_start_duration);
+   fprintf(stderr, "loops: %d\n", demo_loops);
+
+   for(i=0; i<demo_loops; i++) {
+       fprintf(stderr, "Loop: %d/%d\n", i, demo_loops);
+
+       /* Initialize the window */
+       eglutInitWindowSize(300, 300);
+       eglutInitAPIMask(EGLUT_OPENGL_ES2_BIT);
+       eglutInit(argc, argv);
+
+       int winid = eglutCreateWindow("es2gears");
+
+       /* Set up eglut callback functions */
+       eglutIdleFunc(gears_idle);
+       eglutReshapeFunc(gears_reshape);
+       eglutDisplayFunc(gears_draw);
+       eglutSpecialFunc(gears_special);
+
+       /* Initialize the gears */
+       gears_init();
+
+       eglutMainLoop();
+
+       eglutDestroyWindow(winid);
+       eglutTerminate();
+   }
+
+   return 0;
+}
diff --git a/src/test-native/mesa-demos-patched/es2redsquare.c b/src/test-native/mesa-demos-patched/es2redsquare.c
new file mode 100644
index 0000000..886bdd3
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/es2redsquare.c
@@ -0,0 +1,611 @@
+/*
+ * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * Ported to GLES2.
+ * Kristian Høgsberg <krh at bitplanet.net>
+ * May 3, 2010
+ * 
+ * Improve GLES2 port:
+ *   * Refactor gear drawing.
+ *   * Use correct normals for surfaces.
+ *   * Improve shader.
+ *   * Use perspective projection transformation.
+ *   * Add FPS count.
+ *   * Add comments.
+ * Alexandros Frantzis <alexandros.frantzis at linaro.org>
+ * Jul 13, 2010
+ */
+
+#define GL_GLEXT_PROTOTYPES
+#define EGL_EGLEXT_PROTOTYPES
+
+#define _GNU_SOURCE
+
+#include <math.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <assert.h>
+#include <GLES2/gl2.h>
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include "eglut.h"
+
+static int demo_start_duration = 5000; // ms
+
+#define OBJECT_VERTEX_STRIDE 3
+#define OBJECT_COLOR_STRIDE 4
+
+typedef GLfloat ObjectVertex[OBJECT_VERTEX_STRIDE];
+typedef GLfloat ObjectColor[OBJECT_COLOR_STRIDE];
+
+/**
+ * Struct representing an object.
+ */
+struct object {
+   ObjectVertex *vertices;
+   int nvertices;
+   ObjectColor *colors;
+   int ncolors;
+
+   GLuint vbo;
+   GLuint cbo;
+};
+
+static struct object *obj;
+/** The location of the shader uniforms */
+static GLuint ModelViewProjectionMatrix_location;
+/** The projection matrix */
+static GLfloat ProjectionMatrix[16];
+
+GLuint vertextCode=0, fragmentCode=0;
+GLuint program = 0;
+
+/** 
+ * Fills an object vertex.
+ * 
+ * @param v the vertex to fill
+ * @param x the x coordinate
+ * @param y the y coordinate
+ * @param z the z coortinate
+ * 
+ * @return the operation error code
+ */
+static ObjectVertex *
+vert(ObjectVertex *v, GLfloat x, GLfloat y, GLfloat z)
+{
+   v[0][0] = x;
+   v[0][1] = y;
+   v[0][2] = z;
+
+   return v + 1;
+}
+
+static ObjectColor *
+color(ObjectColor *v, GLfloat r, GLfloat g, GLfloat b, GLfloat a)
+{
+   v[0][0] = r;
+   v[0][1] = g;
+   v[0][2] = b;
+   v[0][3] = a;
+
+   return v + 1;
+}
+
+static struct object *
+create_object()
+{
+   ObjectVertex *v;
+   ObjectColor *c;
+   struct object *object;
+
+   /* Allocate memory for the object */
+   object = malloc(sizeof *object);
+   if (object == NULL)
+      return NULL;
+
+   /* Allocate memory for the vertices */
+   object->vertices = calloc(4, sizeof(*object->vertices));
+   v = object->vertices;
+   v = vert(v, -2,  2, 0);
+   v = vert(v,  2,  2, 0);
+   v = vert(v, -2, -2, 0);
+   v = vert(v,  2, -2, 0);
+   object->nvertices = (v - object->vertices);
+   assert(4 == object->nvertices);
+
+   object->colors = calloc(4, sizeof(*object->colors));
+   c = object->colors;
+   c = color(c, 1.0, 0.0, 0.0, 1.0);
+   c = color(c, 0.0, 0.0, 1.0, 1.0);
+   c = color(c, 1.0, 0.0, 0.0, 1.0);
+   c = color(c, 1.0, 0.0, 0.0, 1.0);
+   object->ncolors = (c - object->colors);
+   assert(4 == object->ncolors);
+
+   /* Store the vertices in a vertex buffer object (VBO) */
+   glGenBuffers(1, &object->vbo);
+   glBindBuffer(GL_ARRAY_BUFFER, object->vbo);
+   glBufferData(GL_ARRAY_BUFFER, object->nvertices * sizeof(ObjectVertex),
+         object->vertices, GL_STATIC_DRAW);
+   glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+   glGenBuffers(1, &object->cbo);
+   glBindBuffer(GL_ARRAY_BUFFER, object->cbo);
+   glBufferData(GL_ARRAY_BUFFER, object->ncolors * sizeof(ObjectColor),
+         object->colors, GL_STATIC_DRAW);
+   glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+   return object;
+}
+
+static void destroy_object(struct object *object)
+{
+   glDeleteBuffers(1, &object->cbo);
+   glDeleteBuffers(1, &object->vbo);
+   free(object->colors);
+   free(object->vertices);
+   free(object);
+}
+
+/** 
+ * Multiplies two 4x4 matrices.
+ * 
+ * The result is stored in matrix m.
+ * 
+ * @param m the first matrix to multiply
+ * @param n the second matrix to multiply
+ */
+static void
+multiply(GLfloat *m, const GLfloat *n)
+{
+   GLfloat tmp[16];
+   const GLfloat *row, *column;
+   div_t d;
+   int i, j;
+
+   for (i = 0; i < 16; i++) {
+      tmp[i] = 0;
+      d = div(i, 4);
+      row = n + d.quot * 4;
+      column = m + d.rem;
+      for (j = 0; j < 4; j++)
+         tmp[i] += row[j] * column[j * 4];
+   }
+   memcpy(m, &tmp, sizeof tmp);
+}
+
+/** 
+ * Rotates a 4x4 matrix.
+ * 
+ * @param[in,out] m the matrix to rotate
+ * @param angle the angle to rotate
+ * @param x the x component of the direction to rotate to
+ * @param y the y component of the direction to rotate to
+ * @param z the z component of the direction to rotate to
+ */
+static void
+rotate(GLfloat *m, GLfloat _angle, GLfloat x, GLfloat y, GLfloat z)
+{
+   double s, c;
+
+   sincos(_angle, &s, &c);
+   GLfloat r[16] = {
+      x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
+      x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0, 
+      x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
+      0, 0, 0, 1
+   };
+
+   multiply(m, r);
+}
+
+
+/** 
+ * Translates a 4x4 matrix.
+ * 
+ * @param[in,out] m the matrix to translate
+ * @param x the x component of the direction to translate to
+ * @param y the y component of the direction to translate to
+ * @param z the z component of the direction to translate to
+ */
+static void
+translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
+{
+   GLfloat t[16] = { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 };
+
+   multiply(m, t);
+}
+
+/** 
+ * Creates an identity 4x4 matrix.
+ * 
+ * @param m the matrix make an identity matrix
+ */
+static void
+identity(GLfloat *m)
+{
+   GLfloat t[16] = {
+      1.0, 0.0, 0.0, 0.0,
+      0.0, 1.0, 0.0, 0.0,
+      0.0, 0.0, 1.0, 0.0,
+      0.0, 0.0, 0.0, 1.0,
+   };
+
+   memcpy(m, t, sizeof(t));
+}
+
+/** 
+ * Transposes a 4x4 matrix.
+ *
+ * @param m the matrix to transpose
+ */
+static void 
+transpose(GLfloat *m)
+{
+   GLfloat t[16] = {
+      m[0], m[4], m[8],  m[12],
+      m[1], m[5], m[9],  m[13],
+      m[2], m[6], m[10], m[14],
+      m[3], m[7], m[11], m[15]};
+
+   memcpy(m, t, sizeof(t));
+}
+
+/**
+ * Inverts a 4x4 matrix.
+ *
+ * This function can currently handle only pure translation-rotation matrices.
+ * Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
+ * for an explanation.
+ */
+static void
+invert(GLfloat *m)
+{
+   GLfloat t[16];
+   identity(t);
+
+   // Extract and invert the translation part 't'. The inverse of a
+   // translation matrix can be calculated by negating the translation
+   // coordinates.
+   t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
+
+   // Invert the rotation part 'r'. The inverse of a rotation matrix is
+   // equal to its transpose.
+   m[12] = m[13] = m[14] = 0;
+   transpose(m);
+
+   // inv(m) = inv(r) * inv(t)
+   multiply(m, t);
+}
+
+/** 
+ * Calculate a perspective projection transformation.
+ * 
+ * @param m the matrix to save the transformation in
+ * @param fovy the field of view in the y direction
+ * @param aspect the view aspect ratio
+ * @param zNear the near clipping plane
+ * @param zFar the far clipping plane
+ */
+void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
+{
+   GLfloat tmp[16];
+   identity(tmp);
+
+   double sine, cosine, cotangent, deltaZ;
+   GLfloat radians = fovy / 2 * M_PI / 180;
+
+   deltaZ = zFar - zNear;
+   sincos(radians, &sine, &cosine);
+
+   if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
+      return;
+
+   cotangent = cosine / sine;
+
+   tmp[0] = cotangent / aspect;
+   tmp[5] = cotangent;
+   tmp[10] = -(zFar + zNear) / deltaZ;
+   tmp[11] = -1;
+   tmp[14] = -2 * zNear * zFar / deltaZ;
+   tmp[15] = 0;
+
+   memcpy(m, tmp, sizeof(tmp));
+}
+
+/**
+ * Draws
+ *
+ * @param transform the current transformation matrix
+ * @param x the x position to draw the gear at
+ * @param y the y position to draw the gear at
+ * @param _angle the rotation angle
+ */
+static void
+draw_object(GLfloat *transform)
+{
+   GLfloat model_view[16];
+   GLfloat model_view_projection[16];
+   int tms = eglutGet(EGLUT_ELAPSED_TIME);
+   GLfloat angle = ( tms * 360.0 ) / 4000.0;
+   GLfloat grad = 2 * M_PI * angle / 360.0;
+
+   // fprintf(stderr, "td %d, angle %f\n", tms, angle);
+
+   /* Translate and rotate the gear */
+   memcpy(model_view, transform, sizeof (model_view));
+   translate(model_view, 0, 0, -10);
+   rotate(model_view, grad, 0.0, 0.0, 1.0);
+   rotate(model_view, grad, 0.0, 1.0, 0.0);
+
+   /* Create and set the ModelViewProjectionMatrix */
+   memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
+   multiply(model_view_projection, model_view);
+
+   glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
+                      model_view_projection);
+
+   /* Set the vertex buffer object to use */
+   glBindBuffer(GL_ARRAY_BUFFER, obj->vbo);
+   glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
+         3 * sizeof(GLfloat), NULL);
+   glEnableVertexAttribArray(0);
+
+   glBindBuffer(GL_ARRAY_BUFFER, obj->cbo);
+   glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE,
+         4 * sizeof(GLfloat), NULL);
+   glEnableVertexAttribArray(1);
+
+   glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+
+   /* Disable the attributes */
+   glDisableVertexAttribArray(1);
+   glDisableVertexAttribArray(0);
+   glBindBuffer(GL_ARRAY_BUFFER, 0);
+}
+
+/** 
+ * Draws the object.
+ */
+static void
+object_draw(void)
+{
+   const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
+   const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
+   const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
+   GLfloat transform[16];
+   identity(transform);
+
+   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+   glUseProgram(program);
+
+   /* Draw the object */
+   draw_object(transform);
+
+   glUseProgram(0);
+}
+
+/** 
+ * Handles a new window size or exposure.
+ * 
+ * @param width the window width
+ * @param height the window height
+ */
+static void
+object_reshape(int width, int height)
+{
+   /* Update the projection matrix */
+   perspective(ProjectionMatrix, 45.0, (float)width / (float)height, 1.0, 100.0);
+
+   /* Set the viewport */
+   glViewport(0, 0, (GLint) width, (GLint) height);
+
+   glClearColor(0.0, 0.0, 0.0, 1.0);
+}
+
+/** 
+ * Handles special eglut events.
+ * 
+ * @param special the event to handle.
+ */
+static void
+object_special(int special)
+{
+   switch (special) {
+      case EGLUT_KEY_LEFT:
+         break;
+      case EGLUT_KEY_RIGHT:
+         break;
+      case EGLUT_KEY_UP:
+         break;
+      case EGLUT_KEY_DOWN:
+         break;
+   }
+}
+
+static void
+object_idle(void)
+{
+   static int frames = 0;
+   static double tRate0 = -1.0;
+   int tms = eglutGet(EGLUT_ELAPSED_TIME);
+   double t = tms / 1000.0;
+
+   if(tms>demo_start_duration) {
+        eglutStopMainLoop();
+        return;
+   }
+
+   eglutPostRedisplay();
+   frames++;
+
+   if (tRate0 < 0.0)
+      tRate0 = t;
+   if (t - tRate0 >= 1.0) {
+      GLfloat seconds = t - tRate0;
+      GLfloat fps = frames / seconds;
+      printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
+            fps);
+      tRate0 = t;
+      frames = 0;
+   }
+}
+
+static const char vertex_shader[] =
+                " #ifdef GL_ES\n" 
+                "  precision mediump float;\n" 
+                "  precision mediump int;\n" 
+                "#endif\n" 
+                "\n" 
+                "uniform mat4    mgl_PMVMatrix;\n" 
+                "attribute vec3    mgl_Vertex;\n" 
+                "attribute vec4    mgl_Color;\n" 
+                "varying vec4    frontColor;\n" 
+                "\n" 
+                "void main(void)\n" 
+                "{\n" 
+                "  frontColor=mgl_Color;\n" 
+                "  gl_Position = mgl_PMVMatrix * vec4(mgl_Vertex, 1.0);\n" 
+                "}\n" ;
+
+static const char fragment_shader[] =
+                " #ifdef GL_ES\n" 
+                "  precision mediump float;\n" 
+                "  precision mediump int;\n" 
+                "#endif\n" 
+                "\n" 
+                "varying   vec4    frontColor;\n" 
+                "\n" 
+                "void main (void)\n" 
+                "{\n" 
+                "    gl_FragColor = frontColor;\n" 
+                "}\n" ;
+
+
+static void
+object_init(void)
+{
+   const char *p;
+   char msg[512];
+
+   glEnable(GL_DEPTH_TEST);
+
+   /* Compile the vertex shader */
+   p = vertex_shader;
+   vertextCode = glCreateShader(GL_VERTEX_SHADER);
+   glShaderSource(vertextCode, 1, &p, NULL);
+   glCompileShader(vertextCode);
+   glGetShaderInfoLog(vertextCode, sizeof msg, NULL, msg);
+   printf("vertex shader info: %s\n", msg);
+
+   /* Compile the fragment shader */
+   p = fragment_shader;
+   fragmentCode = glCreateShader(GL_FRAGMENT_SHADER);
+   glShaderSource(fragmentCode, 1, &p, NULL);
+   glCompileShader(fragmentCode);
+   glGetShaderInfoLog(fragmentCode, sizeof msg, NULL, msg);
+   printf("fragment shader info: %s\n", msg);
+
+   /* Create and link the shader program */
+   program = glCreateProgram();
+   glAttachShader(program, vertextCode);
+   glAttachShader(program, fragmentCode);
+   glBindAttribLocation(program, 0, "mgl_Vertex");
+   glBindAttribLocation(program, 1, "mgl_Color");
+
+   glLinkProgram(program);
+   glGetProgramInfoLog(program, sizeof msg, NULL, msg);
+   printf("info: %s\n", msg);
+
+   /* Enable the shaders */
+   glUseProgram(program);
+
+   /* Get the locations of the uniforms so we can access them */
+   ModelViewProjectionMatrix_location = glGetUniformLocation(program, "mgl_PMVMatrix");
+
+   /* make the object */
+   obj = create_object();
+
+   glUseProgram(0);
+   // eglutSwapInterval(1);
+}
+
+static void
+object_release(void)
+{
+   destroy_object(obj);
+   obj = NULL;
+
+   glDetachShader(program, vertextCode);
+   glDeleteShader(vertextCode);
+   glDetachShader(program, fragmentCode);
+   glDeleteShader(fragmentCode);
+   glDeleteProgram(program);
+}
+
+int
+main(int argc, char *argv[])
+{
+   int demo_loops = 1;
+   int i;
+   for (i = 1; i < argc; i++) {
+      if (strcmp(argv[i], "-time") == 0) {
+         demo_start_duration = atoi(argv[++i]);
+      } else if (strcmp(argv[i], "-loops") == 0) {
+         demo_loops = atoi(argv[++i]);
+      }
+   }
+   fprintf(stderr, "duration: %d\n", demo_start_duration);
+   fprintf(stderr, "loops: %d\n", demo_loops);
+
+   for(i=0; i<demo_loops; i++) {
+       fprintf(stderr, "Loop: %d/%d\n", i, demo_loops);
+
+       /* Initialize the window */
+       eglutInitWindowSize(512, 512);
+       eglutInitAPIMask(EGLUT_OPENGL_ES2_BIT);
+       eglutInit(argc, argv);
+
+       int winid = eglutCreateWindow("es2object");
+
+       /* Set up eglut callback functions */
+       eglutIdleFunc(object_idle);
+       eglutReshapeFunc(object_reshape);
+       eglutDisplayFunc(object_draw);
+       eglutSpecialFunc(object_special);
+
+       /* Initialize the object */
+       object_init();
+
+       eglutMainLoop();
+
+       object_release();
+
+       eglutDestroyWindow(winid);
+       eglutTerminate();
+   }
+
+   return 0;
+}
diff --git a/src/test-native/mesa-demos-patched/loop.sh b/src/test-native/mesa-demos-patched/loop.sh
new file mode 100644
index 0000000..747957c
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/loop.sh
@@ -0,0 +1,5 @@
+#! /bin/sh
+
+#./es2gears -loops 500 -time 100
+./es2redsquare -loops 500 -time 100
+ 
diff --git a/src/test-native/mesa-demos-patched/make.sh b/src/test-native/mesa-demos-patched/make.sh
new file mode 100644
index 0000000..a7926f5
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/make.sh
@@ -0,0 +1,17 @@
+
+THISDIR=`pwd`
+
+#eglut/eglut_x11.c \
+#eglut/eglut_screen.c \
+
+#DEMO_C=es2gears.c
+#DEMO_C=es2redsquare.c
+DEMO_C=$1
+
+gcc -I$THISDIR -I$THISDIR/eglut -o `basename $DEMO_C .c` \
+eglut/eglut.c \
+eglut/eglut_x11.c \
+$DEMO_C \
+-lX11 \
+-lEGL \
+-lGLESv2 \
diff --git a/src/test-native/mesa-demos-patched/shell_loop.sh b/src/test-native/mesa-demos-patched/shell_loop.sh
new file mode 100644
index 0000000..c95d04b
--- /dev/null
+++ b/src/test-native/mesa-demos-patched/shell_loop.sh
@@ -0,0 +1,11 @@
+#! /bin/sh
+
+let i=0
+
+while true ; do
+ let i=$i+1
+ echo TEST RUN $i
+ #./es2gears -loops 1 -time 100
+ ./es2redsquare -loops 1 -time 100
+done
+ 
diff --git a/src/test/com/jogamp/opengl/test/android/LauncherUtil.java b/src/test/com/jogamp/opengl/test/android/LauncherUtil.java
new file mode 100644
index 0000000..1f9c26b
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/LauncherUtil.java
@@ -0,0 +1,329 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ * Helper class to parse Uri's and programmatically add package names and properties to create an Uri or Intend.
+ * <p>
+ * The order of the Uri segments (any arguments) is preserved.
+ * </p>  
+ */
+public class LauncherUtil {
+    
+   /** Default launch mode. */
+   public static final String LAUNCH_ACTIVITY_NORMAL = "org.jogamp.launcher.action.LAUNCH_ACTIVITY_NORMAL";
+   
+   /** Transparent launch mode. Note: This seems to be required to achieve translucency, since setTheme(..) doesn't work. */
+   public static final String LAUNCH_ACTIVITY_TRANSPARENT = "org.jogamp.launcher.action.LAUNCH_ACTIVITY_TRANSPARENT";
+   
+   /** FIXME: TODO */
+   public static final String LAUNCH_MAIN = "org.jogamp.launcher.action.LAUNCH_MAIN";
+   
+   /** FIXME: TODO */
+   public static final String LAUNCH_JUNIT = "org.jogamp.launcher.action.LAUNCH_JUNIT";
+   
+   /** The protocol <code>launch</code> */
+   public static final String SCHEME = "launch";
+   
+   /** The host <code>jogamp.org</code> */
+   public static final String HOST = "jogamp.org";
+   
+   static final String PKG = "pkg";
+   
+   public static abstract class BaseActivityLauncher extends Activity {
+       final OrderedProperties props = new OrderedProperties();
+       
+       /** 
+        * Returns the default {@link LauncherUtil#LAUNCH_ACTIVITY_NORMAL} action.
+        * <p>
+        * Should be overridden for other action, eg.  {@link LauncherUtil#LAUNCH_ACTIVITY_TRANSPARENT}.
+        * </p>
+        */
+       public String getAction() { return LAUNCH_ACTIVITY_NORMAL; }
+       
+       /**
+        * Returns the properties, which are being propagated to the target activity.
+        * <p>
+        * Maybe be used to set custom properties.
+        * </p>
+        */
+       public final OrderedProperties getProperties() { return props; }
+       
+       /** Custom initialization hook which can be overriden to setup data, e.g. fill the properties retrieved by {@link #getProperties()}. */
+       public void init() { }
+       
+       /** Returns true if this launcher activity shall end after starting the downstream activity. Defaults to <code>true</code>, override to change behavior. */
+       public boolean finishAfterDelegate() { return true; }
+       
+       /** Must return the downstream Activity class name */
+       public abstract String getActivityName();
+       
+       /** Must return a list of required packages, at least one. */
+       public abstract List<String> getPackages();
+
+       @Override
+       public void onCreate(Bundle savedInstanceState) {
+           super.onCreate(savedInstanceState);
+           
+           init();
+           
+           final DataSet data = new DataSet();
+           data.setActivityName(getActivityName());
+           data.addAllPackages(getPackages());
+           data.addAllProperties(props);
+           
+           final Intent intent = LauncherUtil.getIntent(getAction(), data);
+           Log.d(getClass().getSimpleName(), "Launching Activity: "+intent);
+           startActivity (intent);
+           
+           if(finishAfterDelegate()) {
+               finish(); // done
+           }
+       }        
+   }
+   
+   public static class OrderedProperties {
+       HashMap<String, String> map = new HashMap<String, String>();
+       ArrayList<String> keyList = new ArrayList<String>(); 
+              
+       public final void setProperty(String key, String value) { 
+           if(key.equals(PKG)) {
+               throw new IllegalArgumentException("Illegal property key, '"+PKG+"' is reserved");
+           }
+           final String oval = map.put(key, value);
+           if(null != oval) {
+               map.put(key, oval); // restore
+               throw new IllegalArgumentException("Property overwriting not allowed: "+key+": "+oval+" -> "+value);
+           }
+           keyList.add(key); // new key
+       }
+       
+       public final void addAll(OrderedProperties props) {
+           Iterator<String> argKeys = props.keyList.iterator();
+           while(argKeys.hasNext()) {
+                   final String key = argKeys.next();
+                   setProperty(key, props.map.get(key));
+           }           
+       }
+       
+       public final void setSystemProperties() {
+           Iterator<String> argKeys = keyList.iterator();
+           while(argKeys.hasNext()) {
+                   final String key = argKeys.next();
+                   System.setProperty(key, map.get(key));
+           }
+       }
+       public final void clearSystemProperties() {
+           Iterator<String> argKeys = keyList.iterator();
+           while(argKeys.hasNext()) {
+               System.clearProperty(argKeys.next());
+           }
+       }
+       
+       public final String getProperty(String key) { return map.get(key); }
+       public final Map<String, String> getProperties() { return map; }
+           
+       /** Returns the list of property keys in the order, as they were added. */
+       public final List<String> getPropertyKeys() { return keyList; }       
+   }
+   
+   public static class DataSet {
+       static final char SLASH = '/';
+       static final char QMARK = '?';
+       static final char AMPER = '&';
+       static final char ASSIG = '=';
+       static final String COLSLASH2 = "://";
+       static final String EMPTY = "";
+       
+       String activityName = null;
+       ArrayList<String> packages = new ArrayList<String>();
+       OrderedProperties properties = new OrderedProperties();
+       
+       public final void setActivityName(String name) { activityName = name; }
+       public final String getActivityName() { return activityName; }
+       
+       public final void addPackage(String p) { 
+           packages.add(p); 
+       }   
+       public final void addAllPackages(List<String> plist) { 
+           packages.addAll(plist);
+       }   
+       public final List<String> getPackages()  { return packages; }
+       
+       public final void setProperty(String key, String value) {
+           properties.setProperty(key, value);
+       }
+       public final void addAllProperties(OrderedProperties props) {
+           properties.addAll(props);
+       }
+       public final void setSystemProperties() {
+           properties.setSystemProperties();
+       }   
+       public final void clearSystemProperties() {
+           properties.clearSystemProperties();
+       }   
+       public final String getProperty(String key) { return properties.getProperty(key); }
+       public final OrderedProperties getProperties() { return properties; }
+       public final List<String> getPropertyKeys() { return properties.getPropertyKeys(); }       
+       
+       public final Uri getUri() {
+           StringBuilder sb = new StringBuilder();
+           sb.append(SCHEME).append(COLSLASH2).append(HOST).append(SLASH).append(getActivityName());
+           boolean needsSep = false;
+           if(packages.size()>0) {
+               sb.append(QMARK);
+               for(int i=0; i<packages.size(); i++) {
+                   if(needsSep) {
+                       sb.append(AMPER);
+                   }
+                   sb.append(PKG).append(ASSIG).append(packages.get(i));
+                   needsSep = true;
+               }
+           }
+           Iterator<String> argKeys = properties.keyList.iterator();
+           while(argKeys.hasNext()) {
+                   if(needsSep) {
+                       sb.append(AMPER);
+                   }
+                   final String key = argKeys.next();
+                   sb.append(key).append(ASSIG).append(properties.map.get(key));
+                   needsSep = true;
+           }
+           return Uri.parse(sb.toString());
+       }
+       
+       public static final DataSet create(Uri uri) {
+           if(!uri.getScheme().equals(SCHEME)) {
+               return null;
+           }
+           if(!uri.getHost().equals(HOST)) {
+               return null;
+           }
+           DataSet data = new DataSet();
+           {
+               String an =  uri.getPath();
+               if(SLASH == an.charAt(0)) {
+                   an = an.substring(1);
+               }
+               if(SLASH == an.charAt(an.length()-1)) {
+                   an = an.substring(0, an.length()-1);
+               }
+               data.setActivityName(an);
+           }
+           
+           final String q = uri.getQuery();
+           final int q_l = q.length();
+           int q_e = -1;
+           while(q_e < q_l) {
+               int q_b = q_e + 1; // next term
+               q_e = q.indexOf(AMPER, q_b);
+               if(0 == q_e) {
+                   // single seperator
+                   continue; 
+               }
+               if(0 > q_e) {
+                   // end
+                   q_e = q_l;
+               }
+               // n-part
+               final String part = q.substring(q_b, q_e);
+               final int assignment = part.indexOf(ASSIG);
+               if(0 < assignment) {
+                   // assignment
+                   final String k = part.substring(0, assignment);
+                   final String v = part.substring(assignment+1);
+                   if(k.equals(PKG)) {
+                       if(v.length()==0) {
+                           throw new IllegalArgumentException("Empty package name: part <"+part+">, query <"+q+"> of "+uri);
+                       }
+                       data.addPackage(v);
+                   } else {
+                       data.setProperty(k, v);
+                   }
+               } else {
+                   // property key only
+                   if(part.equals(PKG)) {
+                       throw new IllegalArgumentException("Empty package name: part <"+part+">, query <"+q+"> of "+uri);
+                   }
+                   data.setProperty(part, EMPTY);
+               }
+           }
+           data.validate();
+           return data;
+       }
+       
+       public final void validate() {
+           if(null == activityName) {
+               throw new RuntimeException("Activity is not NULL");
+           }
+           if(packages.size() == 0) {
+               throw new RuntimeException("Empty package list");
+           }
+       }
+   }
+   
+   public final static Intent getIntent(String action, DataSet data) {
+       data.validate();
+       return new Intent(action, data.getUri());
+   }
+   
+   public static void main(String[] args) {
+       if(args.length==0) {
+           args = new String[] {
+               SCHEME+"://"+HOST+"/com.jogamp.TestActivity?"+PKG+"=jogamp.pack1&"+PKG+"=javax.pack2&"+PKG+"=com.jogamp.pack3&jogamp.common.debug=true&com.jogamp.test=false",   
+               SCHEME+"://"+HOST+"/com.jogamp.TestActivity?"+PKG+"=jogamp.pack1&jogamp.common.debug=true&com.jogamp.test=false",   
+               SCHEME+"://"+HOST+"/com.jogamp.TestActivity?"+PKG+"=jogamp.pack1"   
+           };
+       }
+       for(int i=0; i<args.length; i++) {
+           String uri_s = args[i];
+           Uri uri0 = Uri.parse(uri_s);
+           DataSet data = DataSet.create(uri0);
+           if(null == data) {
+               System.err.println("Error: NULL JogAmpLauncherUtil: <"+uri_s+"> -> "+uri0+" -> NULL");
+           }
+           Uri uri1 = data.getUri();
+           if(!uri0.equals(uri1)) {
+               System.err.println("Error: Not equal: <"+uri_s+"> -> "+uri0+" -> "+uri1);
+           }
+       }
+   }
+   
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieCubeActivity0.java b/src/test/com/jogamp/opengl/test/android/MovieCubeActivity0.java
new file mode 100644
index 0000000..59e7893
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieCubeActivity0.java
@@ -0,0 +1,125 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.io.IOException;
+import java.net.URLConnection;
+import java.util.Arrays;
+
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLProfile;
+
+import jogamp.newt.driver.android.AndroidWindow;
+import jogamp.newt.driver.android.NewtBaseActivity;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.newt.NewtFactory;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.newt.opengl.GLWindow;
+
+import com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieCube;
+import com.jogamp.opengl.util.Animator;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.inputmethod.InputMethodManager;
+
+public class MovieCubeActivity0 extends NewtBaseActivity {
+   static String TAG = "MovieCubeActivity0";
+   
+   MouseAdapter showKeyboardMouseListener = new MouseAdapter() {
+        @Override
+        public void mousePressed(MouseEvent e) {
+           if(e.getPressure()>2f) {
+               final AndroidWindow win = (AndroidWindow)e.getSource();           
+               InputMethodManager mgr = (InputMethodManager) win.getAndroidView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+               mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // shows keyboard ..
+               win.getAndroidView().requestFocus();
+           }
+        }
+   };
+   
+   @Override
+   public void onCreate(Bundle savedInstanceState) {
+       super.onCreate(savedInstanceState);
+       
+       String[] urls0 = new String[] {                    
+               System.getProperty("jnlp.media0_url2"),
+               System.getProperty("jnlp.media0_url1"),
+               System.getProperty("jnlp.media0_url0") };       
+       final URLConnection urlConnection0 = getResource(urls0, 0);
+       if(null == urlConnection0) { throw new RuntimeException("no media reachable: "+Arrays.asList(urls0)); }
+       
+       // also initializes JOGL
+       final GLCapabilities capsMain = new GLCapabilities(GLProfile.getGL2ES2());
+       capsMain.setBackgroundOpaque(false);
+
+       // screen for layout params ..
+       final com.jogamp.newt.Display dpy = NewtFactory.createDisplay(null);
+       final com.jogamp.newt.Screen scrn = NewtFactory.createScreen(dpy, 0);
+       scrn.addReference();
+              
+       try {
+           final Animator animator = new Animator();
+           setAnimator(animator);
+           
+           // Main           
+           final MovieCube demoMain = new MovieCube(urlConnection0, -2.3f, 0f, 0f);
+           final GLWindow glWindowMain = GLWindow.create(scrn, capsMain);
+           glWindowMain.setFullscreen(true);
+           setContentView(getWindow(), glWindowMain);
+           glWindowMain.addMouseListener(showKeyboardMouseListener);
+           glWindowMain.addGLEventListener(demoMain);
+           animator.add(glWindowMain);
+           glWindowMain.setVisible(true);
+           
+           // animator.setUpdateFPSFrames(60, System.err);
+           animator.setUpdateFPSFrames(-1, null);
+           animator.resetFPSCounter();
+       } catch (IOException e) {
+           e.printStackTrace();
+       }
+       
+       scrn.removeReference();
+
+       Log.d(TAG, "onCreate - X");
+   }
+   
+   static URLConnection getResource(String path[], int off) {
+       URLConnection uc = null;
+       for(int i=off; null==uc && i<path.length; i++) {
+           if(null != path[i] && path[i].length()>0) {
+               uc = IOUtil.getResource(path[i], null);
+               Log.d(TAG, "Stream: <"+path[i]+">: "+(null!=uc));
+           }
+       }
+       return uc;       
+   }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java b/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java
new file mode 100644
index 0000000..4f24fc9
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieCubeActivityLauncher0.java
@@ -0,0 +1,79 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieCubeActivityLauncher0 extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieCubeActivity0";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");    
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");   
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java
new file mode 100644
index 0000000..11babf1
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity0.java
@@ -0,0 +1,119 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.io.IOException;
+import java.net.URLConnection;
+import java.util.Arrays;
+
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLProfile;
+
+import jogamp.newt.driver.android.AndroidWindow;
+import jogamp.newt.driver.android.NewtBaseActivity;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.newt.NewtFactory;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.newt.opengl.GLWindow;
+
+import com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple;
+import com.jogamp.opengl.util.Animator;
+
+import android.os.Bundle;
+import android.util.Log;
+
+public class MovieSimpleActivity0 extends NewtBaseActivity {
+   static String TAG = "MovieSimpleActivity0";
+   
+   MouseAdapter toFrontMouseListener = new MouseAdapter() {
+       public void mouseClicked(MouseEvent e) {
+           Object src = e.getSource();
+           if(src instanceof AndroidWindow) {
+               ((AndroidWindow)src).requestFocus(false);
+           }
+       } };
+   
+   @Override
+   public void onCreate(Bundle savedInstanceState) {
+       super.onCreate(savedInstanceState);
+       
+       String[] urls0 = new String[] {                    
+               System.getProperty("jnlp.media0_url2"),
+               System.getProperty("jnlp.media0_url1"),
+               System.getProperty("jnlp.media0_url0") };       
+       final URLConnection urlConnection0 = getResource(urls0, 0);
+       if(null == urlConnection0) { throw new RuntimeException("no media reachable: "+Arrays.asList(urls0)); }
+       
+       // also initializes JOGL
+       final GLCapabilities capsMain = new GLCapabilities(GLProfile.getGL2ES2());
+       capsMain.setBackgroundOpaque(false);
+
+       // screen for layout params ..
+       final com.jogamp.newt.Display dpy = NewtFactory.createDisplay(null);
+       final com.jogamp.newt.Screen scrn = NewtFactory.createScreen(dpy, 0);
+       scrn.addReference();
+              
+       try {
+           final Animator animator = new Animator();
+           setAnimator(animator);
+           
+           // Main           
+           final MovieSimple demoMain = new MovieSimple(urlConnection0);
+           demoMain.setScaleOrig(true);
+           final GLWindow glWindowMain = GLWindow.create(scrn, capsMain);
+           glWindowMain.setFullscreen(true);
+           setContentView(getWindow(), glWindowMain);
+           glWindowMain.addGLEventListener(demoMain);
+           animator.add(glWindowMain);
+           glWindowMain.setVisible(true);
+           
+           animator.setUpdateFPSFrames(60, System.err);
+           // animator.setUpdateFPSFrames(-1, null);
+           animator.resetFPSCounter();
+       } catch (IOException e) {
+           e.printStackTrace();
+       }
+       
+       scrn.removeReference();
+
+       Log.d(TAG, "onCreate - X");
+   }
+   
+   static URLConnection getResource(String path[], int off) {
+       URLConnection uc = null;
+       for(int i=off; null==uc && i<path.length; i++) {
+           if(null != path[i] && path[i].length()>0) {
+               uc = IOUtil.getResource(path[i], null);
+               Log.d(TAG, "Stream: <"+path[i]+">: "+(null!=uc));
+           }
+       }
+       return uc;       
+   }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java
new file mode 100644
index 0000000..a5e5f4c
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivity1.java
@@ -0,0 +1,204 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.io.IOException;
+import java.net.URLConnection;
+import java.util.Arrays;
+
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.GLRunnable;
+
+import jogamp.newt.driver.android.AndroidWindow;
+import jogamp.newt.driver.android.NewtBaseActivity;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.newt.NewtFactory;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.newt.opengl.GLWindow;
+
+import com.jogamp.opengl.test.junit.jogl.demos.es2.av.MovieSimple;
+import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.av.GLMediaPlayer;
+
+import android.os.Bundle;
+import android.util.Log;
+import android.view.Gravity;
+
+public class MovieSimpleActivity1 extends NewtBaseActivity {
+   static String TAG = "MovieSimpleActivity1";
+   
+   MouseAdapter toFrontMouseListener = new MouseAdapter() {
+       public void mouseClicked(MouseEvent e) {
+           Object src = e.getSource();
+           if(src instanceof AndroidWindow) {
+               ((AndroidWindow)src).requestFocus(false);
+           }
+       } };
+   
+   @Override
+   public void onCreate(Bundle savedInstanceState) {
+       super.onCreate(savedInstanceState);
+       
+       final boolean mPlayerLocal = Boolean.valueOf(System.getProperty("jnlp.mplayer.local"));
+       final boolean mPlayerNoZoom = Boolean.valueOf(System.getProperty("jnlp.mplayer.nozoom"));
+       final boolean mPlayerHUD = Boolean.valueOf(System.getProperty("jnlp.mplayer.hud"));
+       final boolean mPlayerSharedHUD = mPlayerHUD && Boolean.valueOf(System.getProperty("jnlp.mplayer.hud.shared"));
+       Log.d(TAG, "onCreate - 0 - mPlayerLocal "+mPlayerLocal+", mPlayerNoScale "+mPlayerNoZoom+", mPlayerHUD "+mPlayerHUD+", mPlayerSharedHUD "+mPlayerSharedHUD);
+       
+       String[] urls0 = new String[] {                    
+               System.getProperty("jnlp.media0_url2"),
+               System.getProperty("jnlp.media0_url1"),
+               System.getProperty("jnlp.media0_url0") };       
+       final URLConnection urlConnection0 = getResource(urls0, mPlayerLocal ? 2 : 0);
+       if(null == urlConnection0) { throw new RuntimeException("no media reachable: "+Arrays.asList(urls0)); }
+       
+       final URLConnection urlConnection1;
+       {
+           URLConnection _urlConnection1 = null;
+           if(mPlayerHUD && !mPlayerSharedHUD) {
+               String[] urls1 = new String[] { System.getProperty("jnlp.media1_url0") };
+               _urlConnection1 = getResource(urls1, 0);
+           }
+           if(null == _urlConnection1) { _urlConnection1 = urlConnection0; }
+           urlConnection1 = _urlConnection1;
+       }
+       
+       setTransparencyTheme();
+       setFullscreenFeature(getWindow(), true);
+           
+       final android.view.ViewGroup viewGroup = new android.widget.FrameLayout(getActivity().getApplicationContext());
+       getWindow().setContentView(viewGroup);
+       
+       // also initializes JOGL
+       final GLCapabilities capsMain = new GLCapabilities(GLProfile.getGL2ES2());
+       capsMain.setBackgroundOpaque(!mPlayerHUD);
+
+       // screen for layout params ..
+       final com.jogamp.newt.Display dpy = NewtFactory.createDisplay(null);
+       final com.jogamp.newt.Screen scrn = NewtFactory.createScreen(dpy, 0);
+       scrn.addReference();
+              
+       try {
+           final Animator animator = new Animator();
+           setAnimator(animator);
+           
+           // Main           
+           final MovieSimple demoMain = new MovieSimple(urlConnection0);
+           if(mPlayerHUD) {
+               demoMain.setEffects(MovieSimple.EFFECT_GRADIENT_BOTTOM2TOP);
+               demoMain.setTransparency(0.9f);
+           }
+           demoMain.setScaleOrig(mPlayerNoZoom);
+           final GLWindow glWindowMain = GLWindow.create(scrn, capsMain);
+           {
+               final int padding = mPlayerHUD ? 32 : 0;
+               final android.view.View androidView = ((AndroidWindow)glWindowMain.getDelegatedWindow()).getAndroidView();
+               glWindowMain.setSize(scrn.getWidth()-padding, scrn.getHeight()-padding);
+               glWindowMain.setUndecorated(true);
+               // setContentView(getWindow(), glWindowMain);
+               viewGroup.addView(androidView, new android.widget.FrameLayout.LayoutParams(glWindowMain.getWidth(), glWindowMain.getHeight(), Gravity.BOTTOM|Gravity.RIGHT));
+               registerNEWTWindow(glWindowMain);
+           }
+           
+           glWindowMain.addGLEventListener(demoMain);
+           animator.add(glWindowMain);
+           glWindowMain.setVisible(true);
+           
+           if(mPlayerHUD) {
+                final GLMediaPlayer sharedPlayer = mPlayerSharedHUD ? demoMain.getGLMediaPlayer() : null; 
+                final GLCapabilities capsHUD = new GLCapabilities(GLProfile.getGL2ES2());
+                capsHUD.setBackgroundOpaque(false);
+                final GLWindow glWindowHUD = GLWindow.create(scrn, capsHUD);
+                glWindowMain.invoke(false, new GLRunnable() {
+                    @Override
+                    public boolean run(GLAutoDrawable drawable) {
+                        int x2 = scrn.getX();
+                        int y2 = scrn.getY();
+                        int w2 = scrn.getWidth()/3;
+                        int h2 = scrn.getHeight()/3;
+                        if(null != sharedPlayer) {
+                           if(0 < sharedPlayer.getWidth() && sharedPlayer.getWidth()<scrn.getWidth()/2 &&
+                              0 < sharedPlayer.getHeight() && sharedPlayer.getHeight()<scrn.getHeight()/2) {
+                               w2 = sharedPlayer.getWidth();
+                               h2 = sharedPlayer.getHeight();
+                           }
+                           glWindowHUD.setSharedContext(glWindowMain.getContext());
+                           glWindowHUD.addGLEventListener(new MovieSimple(sharedPlayer));                            
+                        } else {
+                           try {
+                               glWindowHUD.addGLEventListener(new MovieSimple(urlConnection1));
+                           } catch (IOException e) {
+                               e.printStackTrace();
+                           }
+                        }
+                        glWindowHUD.setPosition(x2, y2);
+                        glWindowHUD.setSize(w2, h2);
+                        System.err.println("HUD: "+mPlayerHUD);
+                        System.err.println("HUD: "+w2+"x"+h2);                            
+                        glWindowHUD.addMouseListener(toFrontMouseListener);               
+
+                        viewGroup.post(new Runnable() {
+                            public void run() {
+                                final android.view.View androidView = ((AndroidWindow)glWindowHUD.getDelegatedWindow()).getAndroidView();
+                                // addContentView(getWindow(), glWindowHUD, new android.view.ViewGroup.LayoutParams(glWindowHUD.getWidth(), glWindowHUD.getHeight()));
+                                viewGroup.addView(androidView, new android.widget.FrameLayout.LayoutParams(glWindowHUD.getWidth(), glWindowHUD.getHeight(), Gravity.TOP|Gravity.LEFT));
+                                registerNEWTWindow(glWindowHUD);  
+                                animator.add(glWindowHUD);
+                                glWindowHUD.setVisible(true);
+                            } } );
+                        return true;
+                    } } );
+           }
+           
+           animator.setUpdateFPSFrames(60, System.err);
+           // animator.setUpdateFPSFrames(-1, null);
+           animator.resetFPSCounter();
+       } catch (IOException e) {
+           e.printStackTrace();
+       }
+       
+       scrn.removeReference();
+
+       Log.d(TAG, "onCreate - X");
+   }
+   
+   static URLConnection getResource(String path[], int off) {
+       URLConnection uc = null;
+       for(int i=off; null==uc && i<path.length; i++) {
+           if(null != path[i] && path[i].length()>0) {
+               uc = IOUtil.getResource(path[i], null);
+               Log.d(TAG, "Stream: <"+path[i]+">: "+(null!=uc));
+           }
+       }
+       return uc;       
+   }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00a.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00a.java
new file mode 100644
index 0000000..fbb0223
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00a.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieSimpleActivityLauncher00a extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieSimpleActivity0";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       props.setProperty("jnlp.mplayer.nozoom",     "true");
+       props.setProperty("jnlp.mplayer.hud",        "false");
+       props.setProperty("jnlp.mplayer.hud.shared", "false");
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00b.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00b.java
new file mode 100644
index 0000000..8c08e98
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher00b.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieSimpleActivityLauncher00b extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieSimpleActivity1";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       props.setProperty("jnlp.mplayer.nozoom",     "false");
+       props.setProperty("jnlp.mplayer.hud",        "false");
+       props.setProperty("jnlp.mplayer.hud.shared", "false");
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01a.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01a.java
new file mode 100644
index 0000000..b2a3fac
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01a.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieSimpleActivityLauncher01a extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieSimpleActivity1";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       props.setProperty("jnlp.mplayer.nozoom",     "true");
+       props.setProperty("jnlp.mplayer.hud",        "true");
+       props.setProperty("jnlp.mplayer.hud.shared", "true");
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01b.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01b.java
new file mode 100644
index 0000000..905e262
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher01b.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieSimpleActivityLauncher01b extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieSimpleActivity1";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       props.setProperty("jnlp.mplayer.nozoom",     "false");
+       props.setProperty("jnlp.mplayer.hud",        "true");
+       props.setProperty("jnlp.mplayer.hud.shared", "true");
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher02.java b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher02.java
new file mode 100644
index 0000000..3694579
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/MovieSimpleActivityLauncher02.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class MovieSimpleActivityLauncher02 extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.MovieSimpleActivity1";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       props.setProperty("jnlp.mplayer.nozoom",     "false");
+       props.setProperty("jnlp.mplayer.hud",        "true");
+       props.setProperty("jnlp.mplayer.hud.shared", "false");
+       // props.setProperty("jnlp.media0_url2", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v");
+       props.setProperty("jnlp.media0_url2", "");
+       props.setProperty("jnlp.media0_url1", "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media0_url0", "file:///mnt/sdcard/Movies/BigBuckBunny_320x180.mp4");
+       props.setProperty("jnlp.media1_url0", "http://archive.org/download/ElephantsDream/ed_1024_512kb.mp4");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // props.setProperty("jogamp.debug.IOUtil", "true");       
+       // props.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // props.setProperty("jogl.debug", "all");
+       // props.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // props.setProperty("jogl.debug.GLSLState", "true");
+       // props.setProperty("jogl.debug.DebugGL", "true");
+       // props.setProperty("jogl.debug.TraceGL", "true");
+       // props.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java
index 74419e5..d1c8f27 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivity.java
@@ -52,10 +52,6 @@ public class NEWTElektronActivity extends NewtBaseActivity {
        
        // create GLWindow (-> incl. underlying NEWT Display, Screen & Window)
        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2));
-       caps.setRedBits(5);
-       caps.setGreenBits(6);
-       caps.setBlueBits(5);
-       caps.setAlphaBits(0);
        Log.d(TAG, "req caps: "+caps);
        GLWindow glWindow = GLWindow.create(caps);
        glWindow.setFullscreen(true);
@@ -70,9 +66,12 @@ public class NEWTElektronActivity extends NewtBaseActivity {
        });
        glWindow.setVisible(true);
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTElektronActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivityLauncher.java
new file mode 100644
index 0000000..33e05de
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTElektronActivityLauncher.java
@@ -0,0 +1,45 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTElektronActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.NEWTElektronActivity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java
index ba861d0..c24c3af 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1Activity.java
@@ -59,9 +59,10 @@ public class NEWTGearsES1Activity extends NewtBaseActivity {
        caps.setAlphaBits(0); */
        Log.d(TAG, "req caps: "+caps);
        GLWindow glWindow = GLWindow.create(caps);
+       glWindow.setFullscreen(true);
        setContentView(getWindow(), glWindow);
        
-       glWindow.addGLEventListener(new GearsES1(1));
+       glWindow.addGLEventListener(new GearsES1(-1));
        glWindow.getScreen().addScreenModeListener(new ScreenModeListener() {
         public void screenModeChangeNotify(ScreenMode sm) { }
         public void screenModeChanged(ScreenMode sm, boolean success) {
@@ -70,9 +71,12 @@ public class NEWTGearsES1Activity extends NewtBaseActivity {
        });
        glWindow.setVisible(true);
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES1ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1ActivityLauncher.java
new file mode 100644
index 0000000..d0f6263
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES1ActivityLauncher.java
@@ -0,0 +1,44 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTGearsES1ActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES1Activity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java
index 89ecf4c..592ecf5 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2Activity.java
@@ -30,17 +30,22 @@ package com.jogamp.opengl.test.android;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLProfile;
 
+import jogamp.newt.driver.android.AndroidWindow;
 import jogamp.newt.driver.android.NewtBaseActivity;
 
 import com.jogamp.newt.ScreenMode;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
 import com.jogamp.newt.event.ScreenModeListener;
 import com.jogamp.newt.opengl.GLWindow;
 
 import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.opengl.util.Animator;
 
+import android.content.Context;
 import android.os.Bundle;
 import android.util.Log;
+import android.view.inputmethod.InputMethodManager;
 
 public class NEWTGearsES2Activity extends NewtBaseActivity {
    static String TAG = "NEWTGearsES2Activity";
@@ -52,17 +57,23 @@ public class NEWTGearsES2Activity extends NewtBaseActivity {
        
        // create GLWindow (-> incl. underlying NEWT Display, Screen & Window)
        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2));
-       /*
-       caps.setRedBits(5);
-       caps.setGreenBits(6);
-       caps.setBlueBits(5);
-       caps.setAlphaBits(0); */
        Log.d(TAG, "req caps: "+caps);
        GLWindow glWindow = GLWindow.create(caps);
        glWindow.setFullscreen(true);
        setContentView(getWindow(), glWindow);
+       glWindow.addMouseListener(new MouseAdapter() {
+        @Override
+        public void mousePressed(MouseEvent e) {
+           if(e.getPressure()>2f) { // show Keyboard
+               final AndroidWindow win = (AndroidWindow)e.getSource();           
+               InputMethodManager mgr = (InputMethodManager) win.getAndroidView().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+               mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // shows keyboard ..
+               win.getAndroidView().requestFocus();
+           }
+        }
+       });
        
-       GearsES2 demo = new GearsES2(0);
+       GearsES2 demo = new GearsES2(-1);
        // demo.enableAndroidTrace(true);
        glWindow.addGLEventListener(demo);
        glWindow.getScreen().addScreenModeListener(new ScreenModeListener() {
@@ -72,13 +83,16 @@ public class NEWTGearsES2Activity extends NewtBaseActivity {
         }
        });
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        // animator.setRunAsFastAsPossible(true);
        setAnimator(animator);
        // glWindow.setSkipContextReleaseThread(animator.getThread());
        
        glWindow.setVisible(true);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java
new file mode 100644
index 0000000..1dfdde5
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2ActivityLauncher.java
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTGearsES2ActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+
+    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2Activity";
+    // static String[] pkgs = new String[] { "com.jogamp.common", "javax.media.opengl", "com.jogamp.opengl.test" };
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       // props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       // props.setProperty("newt.debug.Window", "true");
+       // props.setProperty("newt.debug.Window.MouseEvent", "true");
+       // props.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java
index d6b7507..9e50a1b 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivity.java
@@ -32,6 +32,8 @@ import javax.media.opengl.GLProfile;
 
 import jogamp.newt.driver.android.NewtBaseActivity;
 
+import com.jogamp.newt.NewtFactory;
+import com.jogamp.newt.Screen;
 import com.jogamp.newt.ScreenMode;
 import com.jogamp.newt.event.ScreenModeListener;
 import com.jogamp.newt.opengl.GLWindow;
@@ -53,14 +55,16 @@ public class NEWTGearsES2TransActivity extends NewtBaseActivity {
        // create GLWindow (-> incl. underlying NEWT Display, Screen & Window)
        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2));
        caps.setBackgroundOpaque(false);
+       
        Log.d(TAG, "req caps: "+caps);
-       GLWindow glWindow = GLWindow.create(caps);
-       glWindow.setSize(300, 300);
-       // glWindow.setFullscreen(true);
+       Screen screen = NewtFactory.createScreen(NewtFactory.createDisplay(null), 0);
+       screen.addReference();
+       GLWindow glWindow = GLWindow.create(screen, caps);
+       glWindow.setSize(2*screen.getWidth()/3, 2*screen.getHeight()/3);
        glWindow.setUndecorated(true);
        setContentView(getWindow(), glWindow);
        
-       glWindow.addGLEventListener(new GearsES2(1));
+       glWindow.addGLEventListener(new GearsES2(-1));
        glWindow.getScreen().addScreenModeListener(new ScreenModeListener() {
         public void screenModeChangeNotify(ScreenMode sm) { }
         public void screenModeChanged(ScreenMode sm, boolean success) {
@@ -68,12 +72,16 @@ public class NEWTGearsES2TransActivity extends NewtBaseActivity {
         }
        });
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        // glWindow.setSkipContextReleaseThread(animator.getThread());
        
        glWindow.setVisible(true);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
+       screen.removeReference();
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivityLauncher.java
new file mode 100644
index 0000000..c29c0c5
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGearsES2TransActivityLauncher.java
@@ -0,0 +1,50 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTGearsES2TransActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+    static String demo = "com.jogamp.opengl.test.android.NEWTGearsES2TransActivity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jnlp.android.translucent", "true");
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+       props.setProperty("jogamp.debug.IOUtil", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+    @Override
+    public String getAction() {
+        return LauncherUtil.LAUNCH_ACTIVITY_TRANSPARENT;
+    }      
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java
index 1efedcd..b8bf285 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivity.java
@@ -69,9 +69,12 @@ public class NEWTGraphUI1pActivity extends NewtBaseActivity {
        });
        glWindow.setVisible(true);
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java
new file mode 100644
index 0000000..c75c229
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI1pActivityLauncher.java
@@ -0,0 +1,44 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTGraphUI1pActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+    static String demo = "com.jogamp.opengl.test.android.NEWTGraphUI1pActivity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java
index 39fb5e2..103af1a 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivity.java
@@ -70,9 +70,12 @@ public class NEWTGraphUI2pActivity extends NewtBaseActivity {
        });
        glWindow.setVisible(true);
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivityLauncher.java
new file mode 100644
index 0000000..8f6b514
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTGraphUI2pActivityLauncher.java
@@ -0,0 +1,44 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTGraphUI2pActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+    static String demo = "com.jogamp.opengl.test.android.NEWTGraphUI2pActivity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java
index 99d7fd7..a394482 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1Activity.java
@@ -52,15 +52,11 @@ public class NEWTRedSquareES1Activity extends NewtBaseActivity {
        
        // create GLWindow (-> incl. underlying NEWT Display, Screen & Window)
        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES1));
-       caps.setRedBits(5);
-       caps.setGreenBits(6);
-       caps.setBlueBits(5);
-       caps.setAlphaBits(0);
        Log.d(TAG, "req caps: "+caps);
        GLWindow glWindow = GLWindow.create(caps);
        setContentView(getWindow(), glWindow);
        
-       glWindow.addGLEventListener(new RedSquareES1(1));
+       glWindow.addGLEventListener(new RedSquareES1(-1));
        glWindow.getScreen().addScreenModeListener(new ScreenModeListener() {
         public void screenModeChangeNotify(ScreenMode sm) { }
         public void screenModeChanged(ScreenMode sm, boolean success) {
@@ -69,9 +65,12 @@ public class NEWTRedSquareES1Activity extends NewtBaseActivity {
        });
        glWindow.setVisible(true);
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        setAnimator(animator);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
+       
        Log.d(TAG, "onCreate - X");
    }   
 }
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1ActivityLauncher.java
new file mode 100644
index 0000000..478fe65
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES1ActivityLauncher.java
@@ -0,0 +1,44 @@
+package com.jogamp.opengl.test.android;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.jogamp.opengl.test.android.LauncherUtil.OrderedProperties;
+
+public class NEWTRedSquareES1ActivityLauncher extends LauncherUtil.BaseActivityLauncher {
+    static String demo = "com.jogamp.opengl.test.android.NEWTRedSquareES1Activity";
+    static String[] pkgs = new String[] { "com.jogamp.opengl.test" };
+    
+    @Override
+    public void init() {
+       final OrderedProperties props = getProperties();       
+       // props.setProperty("jogamp.debug.JNILibLoader", "true");
+       // props.setProperty("jogamp.debug.NativeLibrary", "true");
+       // properties.setProperty("jogamp.debug.NativeLibrary.Lookup", "true");
+       // properties.setProperty("jogamp.debug.IOUtil", "true");       
+       // properties.setProperty("nativewindow.debug", "all");
+       props.setProperty("nativewindow.debug.GraphicsConfiguration", "true");
+       // properties.setProperty("jogl.debug", "all");
+       // properties.setProperty("jogl.debug.GLProfile", "true");
+       props.setProperty("jogl.debug.GLDrawable", "true");
+       props.setProperty("jogl.debug.GLContext", "true");
+       props.setProperty("jogl.debug.GLSLCode", "true");
+       props.setProperty("jogl.debug.CapabilitiesChooser", "true");       
+       // properties.setProperty("jogl.debug.GLSLState", "true");
+       // properties.setProperty("jogl.debug.DebugGL", "true");
+       // properties.setProperty("jogl.debug.TraceGL", "true");
+       // properties.setProperty("newt.debug", "all");
+       props.setProperty("newt.debug.Window", "true");
+       // properties.setProperty("newt.debug.Window.MouseEvent", "true");
+       // properties.setProperty("newt.debug.Window.KeyEvent", "true");
+    }
+    
+    @Override
+    public String getActivityName() {
+        return demo;
+    }
+    @Override
+    public List<String> getPackages() {
+        return Arrays.asList(pkgs);
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java
index 804e627..889e094 100644
--- a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java
+++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2Activity.java
@@ -52,16 +52,14 @@ public class NEWTRedSquareES2Activity extends NewtBaseActivity {
        
        // create GLWindow (-> incl. underlying NEWT Display, Screen & Window)
        GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GLES2));
-       caps.setRedBits(5);
-       caps.setGreenBits(6);
-       caps.setBlueBits(5);
-       caps.setAlphaBits(0);
        Log.d(TAG, "req caps: "+caps);
        GLWindow glWindow = GLWindow.create(caps);
-       glWindow.setFullscreen(true);
+       // glWindow.setSize(200, 200);
+       // glWindow.setUndecorated(true);
+       glWindow.setFullscreen(true);       
        setContentView(getWindow(), glWindow);
        
-       final RedSquareES2 demo = new RedSquareES2(0);
+       final RedSquareES2 demo = new RedSquareES2(-1);
        // demo.enableAndroidTrace(true);
        glWindow.addGLEventListener(demo);
        glWindow.getScreen().addScreenModeListener(new ScreenModeListener() {
@@ -71,12 +69,14 @@ public class NEWTRedSquareES2Activity extends NewtBaseActivity {
         }
        });
        Animator animator = new Animator(glWindow);
-       animator.setUpdateFPSFrames(60, System.err);
        // animator.setRunAsFastAsPossible(true);
        setAnimator(animator);
        // glWindow.setSkipContextReleaseThread(animator.getThread());
        glWindow.setVisible(true);
        
+       animator.setUpdateFPSFrames(60, System.err);
+       animator.resetFPSCounter();
+       glWindow.resetFPSCounter();
        
        Log.d(TAG, "onCreate - X");
    }   
diff --git a/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2ActivityLauncher.java b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2ActivityLauncher.java
new file mode 100644
index 0000000..96299e8
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/android/NEWTRedSquareES2ActivityLauncher.java
@@ -0,0 +1,21 @@
+package com.jogamp.opengl.test.android;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+public class NEWTRedSquareES2ActivityLauncher extends Activity {
+       @Override
+       public void onCreate(Bundle savedInstanceState) {
+           super.onCreate(savedInstanceState);
+           
+           final Uri uri = Uri.parse("launch://jogamp.org/com.jogamp.opengl.test.android.NEWTRedSquareES2Activity?pkg=com.jogamp.opengl.test");
+           final Intent intent = new Intent("org.jogamp.launcher.action.LAUNCH_ACTIVITY_NORMAL", uri);           
+           Log.d(getClass().getSimpleName(), "Launching Activity: "+intent);
+           startActivity (intent);
+           
+           finish(); // done
+       }        
+}
diff --git a/src/test/com/jogamp/opengl/test/bugs/Bug427GLJPanelTest1.java b/src/test/com/jogamp/opengl/test/bugs/Bug427GLJPanelTest1.java
index 04ce155..18a4324 100644
--- a/src/test/com/jogamp/opengl/test/bugs/Bug427GLJPanelTest1.java
+++ b/src/test/com/jogamp/opengl/test/bugs/Bug427GLJPanelTest1.java
@@ -17,7 +17,7 @@ public class Bug427GLJPanelTest1 extends JFrame implements GLEventListener {
         setLocation(40, 40);
         setVisible(true);
 
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.get(GLProfile.GL2);
         GLCapabilities caps = new GLCapabilities(glp);
         caps.setDoubleBuffered(true);
         caps.setHardwareAccelerated(true);
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/TestRegionRendererNEWT01.java b/src/test/com/jogamp/opengl/test/junit/graph/TestRegionRendererNEWT01.java
index b6c3cc7..a69f995 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/TestRegionRendererNEWT01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/TestRegionRendererNEWT01.java
@@ -2,7 +2,6 @@ package com.jogamp.opengl.test.junit.graph;
 
 import java.io.IOException;
 
-import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLCapabilitiesImmutable;
@@ -11,9 +10,9 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
 import org.junit.Assert;
-import org.junit.BeforeClass;
 import org.junit.Test;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.graph.curve.Region;
 import com.jogamp.graph.curve.opengl.RenderState;
 import com.jogamp.graph.geom.opengl.SVertex;
@@ -53,6 +52,11 @@ public class TestRegionRendererNEWT01 extends UITestCase {
 
     @Test
     public void testRegionRendererR2T01() throws InterruptedException {
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Disabled for now - since it doesn't seem fit for mobile (performance wise). 
+            System.err.println("disabled on non desktop (x86) arch for now ..");
+            return;
+        }
         GLProfile glp = GLProfile.getGL2ES2();
         
         GLCapabilities caps = new GLCapabilities(glp);
@@ -113,6 +117,12 @@ public class TestRegionRendererNEWT01 extends UITestCase {
     
     @Test
     public void testRegionRendererMSAA02() throws InterruptedException {
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Disabled for now - since it doesn't seem fit for mobile (performance wise).
+            // FIXME: Also the GLSL code for VARIABLE_CURVE is not fit for mobile yet!
+            System.err.println("disabled on non desktop (x86) arch for now ..");
+            return;
+        }
         GLProfile glp = GLProfile.get(GLProfile.GL2ES2);
         GLCapabilities caps = new GLCapabilities(glp);
         caps.setAlphaBits(4);    
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT01.java b/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT01.java
index 8f03af7..3830b0c 100755
--- a/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/TestTextRendererNEWT01.java
@@ -2,7 +2,6 @@ package com.jogamp.opengl.test.junit.graph;
 
 import java.io.IOException;
 
-import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.opengl.GL;
 import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GLAutoDrawable;
@@ -12,9 +11,9 @@ import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
 import org.junit.Assert;
-import org.junit.BeforeClass;
 import org.junit.Test;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.graph.curve.Region;
 import com.jogamp.graph.curve.opengl.RenderState;
 import com.jogamp.graph.curve.opengl.TextRenderer;
@@ -29,12 +28,32 @@ import com.jogamp.opengl.util.glsl.ShaderState;
 public class TestTextRendererNEWT01 extends UITestCase {
     static final boolean DEBUG = false;
     static final boolean TRACE = false;
+    static long duration = 100; // ms
 
+    static int atoi(String a) {
+        try {
+            return Integer.parseInt(a);
+        } catch (Exception ex) { throw new RuntimeException(ex); }
+    }
+    
     public static void main(String args[]) throws IOException {
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-time")) {
+                i++;
+                duration = atoi(args[i]);
+            }
+        }
         String tstname = TestTextRendererNEWT01.class.getName();
         org.junit.runner.JUnitCore.main(tstname);
     }    
         
+    static void sleep() {
+        try {
+            System.err.println("** new frame ** (sleep: "+duration+"ms)");
+            Thread.sleep(duration);
+        } catch (InterruptedException ie) {}
+    }
+    
     static void destroyWindow(GLWindow window) {
         if(null!=window) {
             window.destroy();
@@ -56,36 +75,53 @@ public class TestTextRendererNEWT01 extends UITestCase {
 
     @Test
     public void testTextRendererR2T01() throws InterruptedException {
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Disabled for now - since it doesn't seem fit for mobile (performance wise).
+            System.err.println("disabled on non desktop (x86) arch for now ..");
+            return;
+        }
         GLProfile glp = GLProfile.getGL2ES2();
         
         GLCapabilities caps = new GLCapabilities(glp);
         caps.setAlphaBits(4);    
+        System.err.println("Requested: "+caps);
 
         GLWindow window = createWindow("text-vbaa1-msaa0", caps, 800,400);
+        window.display();
+        System.err.println("Chosen: "+window.getChosenGLCapabilities());
+        
         RenderState rs = RenderState.createRenderState(new ShaderState(), SVertex.factory());
         TextGLListener textGLListener = new TextGLListener(rs, Region.VBAA_RENDERING_BIT, DEBUG, TRACE);
         textGLListener.attachInputListenerTo(window);
         window.addGLEventListener(textGLListener);
         
-        textGLListener.setFontSet(FontFactory.UBUNTU, 0, 0);
-        textGLListener.setTech(-400, -30, 0f, -1000, window.getWidth()*2);
-        window.display();
-        
-        textGLListener.setTech(-400, -30, 0, -380, window.getWidth()*3);
-        window.display();
-        
-        textGLListener.setTech(-400, -20, 0, -80, window.getWidth()*4);
-        window.display();
+        if(textGLListener.setFontSet(FontFactory.UBUNTU, 0, 0)) {
+            textGLListener.setTech(-400, -30, 0f, -1000, window.getWidth()*2);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -30, 0, -380, window.getWidth()*3);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -20, 0, -80, window.getWidth()*4);
+            window.display();
+            sleep();
+        }
 
-        textGLListener.setFontSet(FontFactory.JAVA, 0, 0);
-        textGLListener.setTech(-400, -30, 0f, -1000, window.getWidth()*2);
-        window.display();
-        
-        textGLListener.setTech(-400, -30, 0, -380, window.getWidth()*3);
-        window.display();
-        
-        textGLListener.setTech(-400, -20, 0, -80, window.getWidth()*4);
-        window.display();
+        if(textGLListener.setFontSet(FontFactory.JAVA, 0, 0)) {
+            textGLListener.setTech(-400, -30, 0f, -1000, window.getWidth()*2);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -30, 0, -380, window.getWidth()*3);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -20, 0, -80, window.getWidth()*4);
+            window.display();
+            sleep();
+        }
         
         destroyWindow(window); 
     }
@@ -97,32 +133,44 @@ public class TestTextRendererNEWT01 extends UITestCase {
         caps.setAlphaBits(4);    
         caps.setSampleBuffers(true);
         caps.setNumSamples(4);
+        System.err.println("Requested: "+caps);
 
         GLWindow window = createWindow("text-vbaa0-msaa1", caps, 800, 400);
+        window.display();
+        System.err.println("Chosen: "+window.getChosenGLCapabilities());
+        
         RenderState rs = RenderState.createRenderState(new ShaderState(), SVertex.factory());
         TextGLListener textGLListener = new TextGLListener(rs, 0, DEBUG, TRACE);
         textGLListener.attachInputListenerTo(window);
         window.addGLEventListener(textGLListener);
         
-        textGLListener.setFontSet(FontFactory.UBUNTU, 0, 0);
-        textGLListener.setTech(-400, -30, 0f, -1000, 0);
-        window.display();
-        
-        textGLListener.setTech(-400, -30, 0, -380, 0);
-        window.display();
-        
-        textGLListener.setTech(-400, -20, 0, -80, 0);
-        window.display();
-        
-        textGLListener.setFontSet(FontFactory.JAVA, 0, 0);
-        textGLListener.setTech(-400, -30, 0f, -1000, 0);
-        window.display();
-        
-        textGLListener.setTech(-400, -30, 0, -380, 0);
-        window.display();
-        
-        textGLListener.setTech(-400, -20, 0, -80, 0);
-        window.display();
+        if(textGLListener.setFontSet(FontFactory.UBUNTU, 0, 0)) {
+            textGLListener.setTech(-400, -30, 0f, -1000, 0);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -30, 0, -380, 0);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -20, 0, -80, 0);
+            window.display();
+            sleep();
+        }
+
+        if(textGLListener.setFontSet(FontFactory.JAVA, 0, 0)) {
+            textGLListener.setTech(-400, -30, 0f, -1000, 0);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -30, 0, -380, 0);
+            window.display();
+            sleep();
+            
+            textGLListener.setTech(-400, -20, 0, -80, 0);
+            window.display();
+            sleep();
+        }
         
         destroyWindow(window); 
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener01.java
index b8bb9ac..46557e8 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener01.java
@@ -102,7 +102,6 @@ public class GPURegionGLListener01 extends GPURegionRendererListenerBase01 {
         gl.glEnable(GL2ES2.GL_BLEND);
         regionRenderer.setAlpha(gl, 1.0f);
         regionRenderer.setColorStatic(gl, 0.0f, 0.0f, 0.0f);
-        MSAATool.dump(drawable);
         
         createTestOutline();
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener02.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener02.java
index 904e54e..525c5e6 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener02.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURegionGLListener02.java
@@ -100,7 +100,6 @@ public class GPURegionGLListener02 extends GPURegionRendererListenerBase01 {
         gl.glEnable(GL2ES2.GL_BLEND);
         regionRenderer.setAlpha(gl, 1.0f);
         regionRenderer.setColorStatic(gl, 0.0f, 0.0f, 0.0f);
-        MSAATool.dump(drawable);
         
         createTestOutline();
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java
index dac965d..a3182a3 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPURendererListenerBase01.java
@@ -80,7 +80,7 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
     private float yTran =  10;    
     private float ang = 0f;
     private float zoom = -70f;
-    private int texSize = 400; 
+    private int[] texSize = new int[] { 400 }; 
 
     protected volatile float weight = 1.0f;
     boolean ignoreInput = false;
@@ -99,7 +99,7 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
     public final float getXTran() { return xTran; }
     public final float getYTran() { return yTran; }
     public final float getAngle() { return ang; }
-    public final int getTexSize() { return texSize; }
+    public final int[] getTexSize() { return texSize; }
     public final float[] getPosition() { return position; }
 
     public void setMatrix(float xtrans, float ytrans, float angle, int zoom, int fbosize) {
@@ -107,7 +107,7 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
         this.yTran = ytrans; 
         this.ang = angle;  
         this.zoom = zoom;
-        this.texSize = fbosize;     
+        this.texSize[0] = fbosize;     
     }
     
     public void init(GLAutoDrawable drawable) {
@@ -121,6 +121,7 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
         }
         System.err.println("*** "+gl.getContext().getGLVersion());
         System.err.println("*** GLDebugMessage "+gl.getContext().isGLDebugMessageEnabled());
+        MSAATool.dump(drawable);
         gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
         getRenderer().init(gl);
     }
@@ -190,11 +191,12 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
     public void printScreen(GLAutoDrawable drawable, String dir, String tech, String objName, boolean exportAlpha) throws GLException, IOException {
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
-        pw.printf("-%03dx%03d-Z%04d-T%04d-%s", drawable.getWidth(), drawable.getHeight(), (int)Math.abs(zoom), texSize, objName);
+        pw.printf("-%03dx%03d-Z%04d-T%04d-%s", drawable.getWidth(), drawable.getHeight(), (int)Math.abs(zoom), texSize[0], objName);
         
-        final String filename = dir + tech + sw +".tga";
-        screenshot.readPixels(drawable.getGL(), drawable, false);
-        screenshot.write(new File(filename));
+        final String filename = dir + tech + sw +".png";
+        if(screenshot.readPixels(drawable.getGL(), drawable, false)) {
+            screenshot.write(new File(filename));
+        }
     }
     
     int screenshot_num = 0;
@@ -231,12 +233,12 @@ public abstract class GPURendererListenerBase01 implements GLEventListener {
                 move(-1, 0);
             }
             else if(arg0.getKeyCode() == KeyEvent.VK_6){
-                texSize -= 10;
-                System.err.println("Tex Size: " + texSize);
+                texSize[0] -= 10;
+                System.err.println("Tex Size: " + texSize[0]);
             }
             else if(arg0.getKeyCode() == KeyEvent.VK_7){
-                texSize += 10;
-                System.err.println("Tex Size: " + texSize);
+                texSize[0] += 10;
+                System.err.println("Tex Size: " + texSize[0]);
             }            
             else if(arg0.getKeyCode() == KeyEvent.VK_0){
                 rotate(1);
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextGLListener0A.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextGLListener0A.java
index da34b1d..5c7d15a 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextGLListener0A.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextGLListener0A.java
@@ -64,7 +64,6 @@ public class GPUTextGLListener0A extends GPUTextRendererListenerBase01 {
         gl.glEnable(GL2ES2.GL_BLEND);
         textRenderer.setAlpha(gl, 1.0f);
         textRenderer.setColorStatic(gl, 0.0f, 0.0f, 0.0f);
-        MSAATool.dump(drawable);
     }
     
     public void dispose(GLAutoDrawable drawable) {
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextRendererListenerBase01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextRendererListenerBase01.java
index ad662e0..551ab55 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextRendererListenerBase01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUTextRendererListenerBase01.java
@@ -29,7 +29,6 @@ package com.jogamp.opengl.test.junit.graph.demos;
 
 import java.io.IOException;
 
-import javax.media.opengl.FPSCounter;
 import javax.media.opengl.GL;
 import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GLAnimatorControl;
@@ -41,7 +40,6 @@ import com.jogamp.graph.curve.opengl.TextRenderer;
 import com.jogamp.graph.font.Font;
 import com.jogamp.graph.font.FontFactory;
 import com.jogamp.graph.geom.AABBox;
-import com.jogamp.graph.geom.Vertex;
 import com.jogamp.newt.event.KeyEvent;
 import com.jogamp.newt.event.KeyListener;
 import com.jogamp.newt.opengl.GLWindow;
@@ -99,17 +97,22 @@ public abstract class GPUTextRendererListenerBase01 extends GPURendererListenerB
         "in lorem. Maecenas in ipsum ac justo scelerisque sollicitudin. Quisque sit amet neque lorem,\n" +
         "-------Press H to change text---------\n"; 
     
-    StringBuffer userString = new StringBuffer();
+    StringBuilder userString = new StringBuilder();
     boolean userInput = false;
     
     public GPUTextRendererListenerBase01(RenderState rs, int modes, boolean debug, boolean trace) {
-        super(TextRenderer.create(rs, modes), modes, debug, trace);        
-        this.font = FontFactory.get(fontSet).getDefault();
-        dumpFontNames();
-        
-        this.fontName = font.toString();
-        this.fontNameBox = font.getStringBounds(fontName, fontSizeFixed*2);
-        switchHeadBox();        
+        super(TextRenderer.create(rs, modes), modes, debug, trace);
+        try {
+            this.font = FontFactory.get(fontSet).getDefault();
+            dumpFontNames();
+            
+            this.fontName = font.toString();
+            this.fontNameBox = font.getStringBounds(fontName, fontSizeFixed*2);
+            switchHeadBox();        
+        } catch (IOException ioe) {
+            System.err.println("Catched: "+ioe.getMessage());
+            ioe.printStackTrace();
+        }
     }
 
     void dumpFontNames() {
@@ -198,18 +201,39 @@ public abstract class GPUTextRendererListenerBase01 extends GPURendererListenerB
         dumpMatrix(true);
     }
 
-    public void nextFontSet() {
-        fontSet = ( fontSet == FontFactory.UBUNTU ) ? FontFactory.JAVA : FontFactory.UBUNTU ;
-        font = FontFactory.get(fontSet).getDefault();   
-        this.fontName = font.getFullFamilyName(null).toString();
-        this.fontNameBox = font.getStringBounds(fontName, fontSizeFixed*3);
-        dumpFontNames();
+    public boolean nextFontSet() {        
+        try {
+            int set = ( fontSet == FontFactory.UBUNTU ) ? FontFactory.JAVA : FontFactory.UBUNTU ;
+            Font _font = FontFactory.get(set).getDefault();
+            if(null != _font) {
+                fontSet = set;
+                font = _font;
+                fontName = font.getFullFamilyName(null).toString();
+                fontNameBox = font.getStringBounds(fontName, fontSizeFixed*3);       
+                dumpFontNames();
+                return true;
+            }
+        } catch (IOException ex) {
+            System.err.println("Catched: "+ex.getMessage());
+        }
+        return false;
     }
     
-    public void setFontSet(int set, int family, int stylebits) {
-        fontSet = set;
-        font = FontFactory.get(fontSet).get(family, stylebits);       
-        dumpFontNames();
+    public boolean setFontSet(int set, int family, int stylebits) {
+        try {
+            Font _font = FontFactory.get(set).get(family, stylebits);
+            if(null != _font) {
+                fontSet = set;
+                font = _font;
+                fontName = font.getFullFamilyName(null).toString();
+                fontNameBox = font.getStringBounds(fontName, fontSizeFixed*3);       
+                dumpFontNames();
+                return true;
+            }
+        } catch (IOException ex) {
+            System.err.println("Catched: "+ex.getMessage());
+        }
+        return false;
     }
     
     public boolean isUserInputMode() { return userInput; }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUUISceneGLListener0A.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUUISceneGLListener0A.java
index 5abc181..eaac2b1 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUUISceneGLListener0A.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/GPUUISceneGLListener0A.java
@@ -1,5 +1,7 @@
 package com.jogamp.opengl.test.junit.graph.demos;
 
+import java.io.IOException;
+
 import javax.media.opengl.GL;
 import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GLAnimatorControl;
@@ -29,9 +31,9 @@ public class GPUUISceneGLListener0A implements GLEventListener {
     private boolean trace = false; 
     
     private final int renderModes;
-    private final int texSize; 
+    private final int[] texSize = new int[1]; 
     private final int renderModes2;
-    private final int texSize2; 
+    private final int[] texSize2 = new int[1]; 
     private RegionRenderer regionRenderer;
     private RenderState rs;
     
@@ -75,13 +77,18 @@ public class GPUUISceneGLListener0A implements GLEventListener {
     public GPUUISceneGLListener0A(RenderState rs, int renderModes, boolean debug, boolean trace) {
         this.rs = rs;
         this.renderModes = renderModes;
-        this.texSize = Region.isVBAA(renderModes) ? 400 : 0;
+        this.texSize[0] = Region.isVBAA(renderModes) ? 400 : 0;
         this.renderModes2 = 0;
-        this.texSize2 = 0;
+        this.texSize2[0] = 0;
         
         this.debug = debug;
         this.trace = trace;
-        font = FontFactory.get(FontFactory.UBUNTU).getDefault();
+        try {
+            font = FontFactory.get(FontFactory.UBUNTU).getDefault();
+        } catch (IOException ioe) {
+            System.err.println("Catched: "+ioe.getMessage());
+            ioe.printStackTrace();
+        }
         labelRegions = new UIRegion[3];
         sceneUIController = new SceneUIController();
     }
@@ -211,7 +218,13 @@ public class GPUUISceneGLListener0A implements GLEventListener {
             gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ).getGL2ES2();
         }
         
-        this.font = FontFactory.get(fontSet).getDefault();
+        try {
+            font = FontFactory.get(fontSet).getDefault();
+        } catch (IOException ioe) {
+            System.err.println("Catched: "+ioe.getMessage());
+            ioe.printStackTrace();
+        }
+        
         regionRenderer = RegionRenderer.create(rs, renderModes); 
         
         gl.glEnable(GL2ES2.GL_DEPTH_TEST);
@@ -288,7 +301,7 @@ public class GPUUISceneGLListener0A implements GLEventListener {
         regionRenderer.scale(gl, 1.5f, 1.5f, 1.0f);
         regionRenderer.rotate(gl, angText , 0, 1, 0);
         regionRenderer.setColorStatic(gl, 0.0f, 1.0f, 0.0f);
-        regionRenderer.draw(gl, jogampRegion.getRegion(gl, rs, 0), new float[]{0,0,0}, 0);
+        regionRenderer.draw(gl, jogampRegion.getRegion(gl, rs, 0), new float[]{0,0,0}, null);
         
         if(null == labelRegions[currentText]) {
             if( null == labels[currentText]) {
@@ -332,7 +345,7 @@ public class GPUUISceneGLListener0A implements GLEventListener {
         if(showFPS && null != fpsRegion) {
             regionRenderer.translate(gl, 0, -60, 0);
             regionRenderer.scale(null, zoomText, zoomText, 1);
-            regionRenderer.draw(gl, fpsRegion.getRegion(gl, rs, 0), new float[]{0,0,0}, 0);
+            regionRenderer.draw(gl, fpsRegion.getRegion(gl, rs, 0), new float[]{0,0,0}, null);
         }
     }
     
@@ -413,5 +426,10 @@ public class GPUUISceneGLListener0A implements GLEventListener {
                 ly = ny;
             }
         }
+        
+        @Override
+        public void mouseWheelMoved(MouseEvent e) {
+            zoom += 2f*e.getWheelRotation();
+        }
     }
 }      
\ No newline at end of file
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/MSAATool.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/MSAATool.java
index 1fbedb3..4cddb13 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/MSAATool.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/MSAATool.java
@@ -27,12 +27,27 @@
  */
 package com.jogamp.opengl.test.junit.graph.demos;
 
+import javax.media.opengl.GL;
 import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GL2GL3;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilitiesImmutable;
 
 public class MSAATool {
+    public static boolean glIsEnabled(GL gl, int name) {
+        boolean isEnabled = false;
+        try {
+            isEnabled = gl.glIsEnabled(name);
+            int glerr = gl.glGetError();
+            if(GL.GL_NO_ERROR != glerr) {
+                System.err.println("glIsEnabled(0x"+Integer.toHexString(name)+") -> error 0x"+Integer.toHexString(glerr));
+            }
+        } catch (Exception e) {
+            System.err.println("Catched Exception: "+e.getMessage());
+            // e.printStackTrace();
+        }        
+        return isEnabled;
+    }
     public static void dump(GLAutoDrawable drawable) {
         float[] vf = new float[] { 0f };
         byte[] vb = new byte[] { 0 };
@@ -44,8 +59,7 @@ public class MSAATool {
         System.out.println("  Caps realised "+caps);        
         System.out.println("  Caps sample buffers "+caps.getSampleBuffers()+", samples "+caps.getNumSamples());
         
-        // default TRUE
-        System.out.println("  GL MULTISAMPLE "+gl.glIsEnabled(GL2ES2.GL_MULTISAMPLE));
+        System.out.println("  GL MULTISAMPLE "+glIsEnabled(gl, GL2ES2.GL_MULTISAMPLE));
         // sample buffers min 0, same as GLX_SAMPLE_BUFFERS_ARB or WGL_SAMPLE_BUFFERS_ARB 
         gl.glGetIntegerv(GL2GL3.GL_SAMPLE_BUFFERS, vi, 0);
         // samples min 0
@@ -54,15 +68,15 @@ public class MSAATool {
         
         System.out.println("GL CSAA SETUP:");
         // default FALSE
-        System.out.println("  GL SAMPLE COVERAGE "+gl.glIsEnabled(GL2GL3.GL_SAMPLE_COVERAGE));
+        System.out.println("  GL SAMPLE COVERAGE "+glIsEnabled(gl, GL2GL3.GL_SAMPLE_COVERAGE));
         // default FALSE
-        System.out.println("  GL SAMPLE_ALPHA_TO_COVERAGE "+gl.glIsEnabled(GL2GL3.GL_SAMPLE_ALPHA_TO_COVERAGE));
+        System.out.println("  GL SAMPLE_ALPHA_TO_COVERAGE "+glIsEnabled(gl, GL2GL3.GL_SAMPLE_ALPHA_TO_COVERAGE));
         // default FALSE
-        System.out.println("  GL SAMPLE_ALPHA_TO_ONE "+gl.glIsEnabled(GL2GL3.GL_SAMPLE_ALPHA_TO_ONE));
+        System.out.println("  GL SAMPLE_ALPHA_TO_ONE "+glIsEnabled(gl, GL2GL3.GL_SAMPLE_ALPHA_TO_ONE));
         // default FALSE, value 1, invert false
         gl.glGetFloatv(GL2GL3.GL_SAMPLE_COVERAGE_VALUE, vf, 0);
         gl.glGetBooleanv(GL2GL3.GL_SAMPLE_COVERAGE_INVERT, vb, 0);
-        System.out.println("  GL SAMPLE_COVERAGE "+gl.glIsEnabled(GL2GL3.GL_SAMPLE_COVERAGE) + 
+        System.out.println("  GL SAMPLE_COVERAGE "+glIsEnabled(gl, GL2GL3.GL_SAMPLE_COVERAGE) + 
                               ": SAMPLE_COVERAGE_VALUE "+vf[0]+
                               ", SAMPLE_COVERAGE_INVERT "+vb[0]);            
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/Label.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/Label.java
index ca70481..4fef2d8 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/Label.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/Label.java
@@ -100,7 +100,6 @@ public abstract class Label extends UIShape implements UITextShape {
 
     @Override
     public void render(GL2ES2 gl, RenderState rs, RegionRenderer renderer,
-            int renderModes, int texSize, boolean selection) {
-        
+            int renderModes, int[/*1*/] texSize, boolean selection) {        
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/RIButton.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/RIButton.java
index 3acab3b..bf40390 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/RIButton.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/RIButton.java
@@ -199,7 +199,7 @@ public abstract class RIButton extends UIShape {
     private boolean toggle =false;
     private boolean toggleable = false;
 
-    public void render(GL2ES2 gl, RenderState rs, RegionRenderer renderer, int renderModes, int texSize, boolean selection) {
+    public void render(GL2ES2 gl, RenderState rs, RegionRenderer renderer, int renderModes, int[/*1*/] texSize, boolean selection) {
         if(null == buttonRegion) {
             buttonRegion = new UIRegion(this);
             labelRegion = new UIRegion(getLabel());
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/SceneUIController.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/SceneUIController.java
index 6a400e9..c6d4348 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/SceneUIController.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/SceneUIController.java
@@ -23,7 +23,7 @@ public class SceneUIController implements GLEventListener{
 
     private int count = 0;
     private int renderModes; 
-    private int texSize; 
+    private int[] texSize; 
     private RegionRenderer renderer = null;
     private RenderState rs = null;
 
@@ -42,14 +42,14 @@ public class SceneUIController implements GLEventListener{
     public SceneUIController() {
     }
     
-    public void setRenderer(RegionRenderer renderer, RenderState rs, int renderModes, int texSize) {
+    public void setRenderer(RegionRenderer renderer, RenderState rs, int renderModes, int[] texSize) {
         this.renderer = renderer;
         this.rs = rs;
         this.renderModes = renderModes;
         this.texSize = texSize;
     }
     
-    public SceneUIController(RegionRenderer renderer, RenderState rs, int renderModes, int texSize) {
+    public SceneUIController(RegionRenderer renderer, RenderState rs, int renderModes, int[] texSize) {
         this.renderer = renderer;
         this.rs = rs;
         this.renderModes = renderModes;
@@ -136,7 +136,7 @@ public class SceneUIController implements GLEventListener{
         gl.glClearColor(sceneClearColor[0], sceneClearColor[1], sceneClearColor[2], sceneClearColor[3]);
         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
 
-        render(gl, width, height, 0, 0, true);
+        render(gl, width, height, 0, null, true);
         ByteBuffer pixel = Buffers.newDirectByteBuffer(4);
         pixel.order(ByteOrder.nativeOrder());
         IntBuffer viewport = IntBuffer.allocate(4);
@@ -151,7 +151,7 @@ public class SceneUIController implements GLEventListener{
         return index;
     }
 
-    private void render(GL2ES2 gl, int width, int height, int renderModes, int texSize, boolean select) {
+    private void render(GL2ES2 gl, int width, int height, int renderModes, int[/*1*/] texSize, boolean select) {
         renderer.reshapePerspective(null, 45.0f, width, height, 0.1f, 7000.0f);
         
         for(int index=0; index < count;index++){
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIGLListener01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIGLListener01.java
index 5f92f13..da94f6a 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIGLListener01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIGLListener01.java
@@ -28,6 +28,8 @@
 
 package com.jogamp.opengl.test.junit.graph.demos.ui;
 
+import java.io.IOException;
+
 import javax.media.opengl.GL;
 import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GLAutoDrawable;
@@ -45,24 +47,29 @@ public class UIGLListener01 extends UIListenerBase01 {
     public UIGLListener01 (RenderState rs, boolean debug, boolean trace) {
         super(RegionRenderer.create(rs, 0), debug, trace);
         setMatrix(-20, 00, 0f, -50);
-        final Font font = FontFactory.get(FontFactory.UBUNTU).getDefault();
-        button = new RIButton(SVertex.factory(), font, "Click me!", 4f, 3f){
-            public void onClick() {
-            }
-            public void onPressed() {
-            }
-            public void onRelease() {
-            }
-            
-        };
-        button.setPosition(2,1,0);
-        /** Button defaults !
-            button.setLabelColor(1.0f,1.0f,1.0f);
-            button.setButtonColor(0.6f,0.6f,0.6f);
-            button.setCorner(1.0f);
-            button.setSpacing(2.0f);
-         */
-        System.err.println(button);
+        try {
+            final Font font = FontFactory.get(FontFactory.UBUNTU).getDefault();
+            button = new RIButton(SVertex.factory(), font, "Click me!", 4f, 3f){
+                public void onClick() {
+                }
+                public void onPressed() {
+                }
+                public void onRelease() {
+                }
+                
+            };
+            button.setPosition(2,1,0);
+            /** Button defaults !
+                button.setLabelColor(1.0f,1.0f,1.0f);
+                button.setButtonColor(0.6f,0.6f,0.6f);
+                button.setCorner(1.0f);
+                button.setSpacing(2.0f);
+             */
+            System.err.println(button);
+        } catch (IOException ex) {
+            System.err.println("Catched: "+ex.getMessage());
+            ex.printStackTrace();
+        }            
     }
     
     public void init(GLAutoDrawable drawable) {
@@ -102,10 +109,10 @@ public class UIGLListener01 extends UIListenerBase01 {
         }        
         
         regionRenderer.setColorStatic(gl, bColor[0], bColor[1], bColor[2]);
-        regionRenderer.draw(gl, regionButton.getRegion(gl, rs, 0), getPosition(), 0);
+        regionRenderer.draw(gl, regionButton.getRegion(gl, rs, 0), getPosition(), null);
 //        regionRenderer.translate(gl, button.getPosition()[0], button.getPosition()[1], button.getPosition()[2]);
         regionRenderer.setColorStatic(gl, lColor[0], lColor[1], lColor[2]);
-        regionRenderer.draw(gl, regionLabel.getRegion(gl, rs, 0), getPosition(), 0);
+        regionRenderer.draw(gl, regionLabel.getRegion(gl, rs, 0), getPosition(), null);
     }        
     
     public void dispose(GLAutoDrawable drawable) {
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java
index 0fe48e5..d0093ad 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIListenerBase01.java
@@ -179,9 +179,10 @@ public abstract class UIListenerBase01 implements GLEventListener {
         PrintWriter pw = new PrintWriter(sw);
         pw.printf("-%03dx%03d-Z%04d-T%04d-%s", drawable.getWidth(), drawable.getHeight(), (int)Math.abs(zoom), 0, objName);
         
-        final String filename = dir + tech + sw +".tga";
-        screenshot.readPixels(drawable.getGL(), drawable, false);
-        screenshot.write(new File(filename));
+        final String filename = dir + tech + sw +".png";
+        if(screenshot.readPixels(drawable.getGL(), drawable, false)) {
+            screenshot.write(new File(filename));
+        }
     }
     
     int screenshot_num = 0;
diff --git a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIShape.java b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIShape.java
index c04fa8b..2f87fab 100644
--- a/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIShape.java
+++ b/src/test/com/jogamp/opengl/test/junit/graph/demos/ui/UIShape.java
@@ -55,7 +55,7 @@ public abstract class UIShape {
         shape.clear();
     }
     
-    public abstract void render(GL2ES2 gl, RenderState rs, RegionRenderer renderer, int renderModes, int texSize, boolean selection);
+    public abstract void render(GL2ES2 gl, RenderState rs, RegionRenderer renderer, int renderModes, int[/*1*/] texSize, boolean selection);
     
     protected boolean positionDirty = false;
     
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAWTCloseX11DisplayBug565.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAWTCloseX11DisplayBug565.java
new file mode 100644
index 0000000..8df5498
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestAWTCloseX11DisplayBug565.java
@@ -0,0 +1,89 @@
+package com.jogamp.opengl.test.junit.jogl.acore;
+
+import jogamp.nativewindow.x11.X11Util;
+import org.junit.Assert;
+import org.junit.Test;
+
+import javax.media.nativewindow.NativeWindowFactory;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesImmutable;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.awt.GLCanvas;
+import java.awt.Frame;
+
+/**
+ * Tests the closing the device of GLCanvas in JOGL
+ */
+public class TestAWTCloseX11DisplayBug565 {
+
+  @Test
+  public void testX11WindowMemoryLeak() throws Exception {
+    GLProfile.initSingleton(); // ensure shared resource runner is done
+    try {
+      for ( int j = 0; j < 10; j++ ) {
+        final int open0;
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {        
+            open0 = X11Util.getOpenDisplayConnectionNumber();
+        } else {
+            open0 = 0;
+        }
+                
+        GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault( ) );
+        Frame frame = new Frame( "AWT Resource X11 Leak - #" + j );
+  
+        GLCanvas glCanvas = new GLCanvas( caps );
+        frame.add( glCanvas );
+        frame.setSize( 128, 128 );
+  
+        final Frame _frame = frame;
+        final GLCanvas _glCanvas = glCanvas;
+  
+        try {
+          javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
+            public void run() {
+              _frame.setVisible( true );
+            }
+          } );
+        }
+        catch ( Throwable t ) {
+          t.printStackTrace();
+          Assert.fail(t.getMessage());
+        }
+        glCanvas.display();
+        try {
+          javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
+            public void run() {
+              _frame.setVisible( false );
+              _frame.remove( _glCanvas );
+              _frame.dispose();
+            }
+          } );
+        }
+        catch ( Throwable t ) {
+          t.printStackTrace();
+          Assert.fail(t.getMessage());
+        }
+
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {
+            final int openD = X11Util.getOpenDisplayConnectionNumber() - open0;
+            if(openD>1) {
+                X11Util.dumpOpenDisplayConnections();
+                X11Util.dumpPendingDisplayConnections();
+                Assert.assertTrue("More than 1 new open display connections", false);
+            }
+        }
+      }
+    }
+    catch ( Exception e ) {
+      e.printStackTrace();
+      Assert.fail(e.getMessage());
+    }
+  }
+
+
+  public static void main(String args[]) {
+    org.junit.runner.JUnitCore.main(TestAWTCloseX11DisplayBug565.class.getName());
+  }
+  
+}
+
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLProfile01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLProfile01NEWT.java
index 6a5f76f..2c89ec7 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLProfile01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGLProfile01NEWT.java
@@ -29,7 +29,6 @@
 package com.jogamp.opengl.test.junit.jogl.acore;
 
 import java.io.IOException;
-import java.util.List;
 
 import org.junit.Assert;
 import org.junit.Test;
@@ -48,25 +47,19 @@ import com.jogamp.newt.*;
 public class TestGLProfile01NEWT extends UITestCase {
 
     @Test
-    public void test00Version() throws InterruptedException {
+    public void testVersion() throws InterruptedException {
         System.err.println(VersionUtil.getPlatformInfo());
         System.err.println(GlueGenVersion.getInstance());
         System.err.println(NativeWindowVersion.getInstance());
         System.err.println(JoglVersion.getInstance());
         System.err.println(NewtVersion.getInstance());
 
-        GLDrawableFactory factory = GLDrawableFactory.getFactory(GLProfile.getDefault());
-        List<GLCapabilitiesImmutable> availCaps = factory.getAvailableCapabilities(null);
-        for(int i=0; i<availCaps.size(); i++) {
-            System.err.println(availCaps.get(i));
-        }
+        System.err.println(JoglVersion.getDefaultOpenGLInfo(null).toString());        
     }
 
     @Test
-    public void test01GLProfileDefault() throws InterruptedException {
+    public void testGLProfileDefault() throws InterruptedException {
         System.out.println("GLProfile "+GLProfile.glAvailabilityToString());
-        System.out.println("GLProfile.getDefaultDesktopDevice(): "+GLProfile.getDefaultDesktopDevice());
-        System.out.println("GLProfile.getDefaultEGLDevice(): "+GLProfile.getDefaultEGLDevice());
         System.out.println("GLProfile.getDefaultDevice(): "+GLProfile.getDefaultDevice());        
         GLProfile glp = GLProfile.getDefault();
         System.out.println("GLProfile.getDefault(): "+glp);
@@ -92,15 +85,9 @@ public class TestGLProfile01NEWT extends UITestCase {
     }
 
     @Test
-    public void test02GL2() throws InterruptedException {
-        GLProfile glp = GLProfile.get(GLProfile.GL2);
-        dumpVersion(glp);
-    }
-
-    @Test
-    public void test03GLProfileMaxProgrammable() throws InterruptedException {
+    public void testGLProfileMaxProgrammable() throws InterruptedException {
         // Assuming at least one programmable profile is available
-        GLProfile glp = GLProfile.getMaxProgrammable();
+        GLProfile glp = GLProfile.getMaxProgrammable(true);
         System.out.println("GLProfile.getMaxProgrammable(): "+glp);
         if(glp.getName().equals(GLProfile.GL4)) {
             Assert.assertTrue(GLProfile.isAvailable(GLProfile.GL4));
@@ -116,7 +103,7 @@ public class TestGLProfile01NEWT extends UITestCase {
     }
 
     @Test
-    public void test04GLProfileGL2ES1() throws InterruptedException {
+    public void testGLProfileGL2ES1() throws InterruptedException {
         if(!GLProfile.isAvailable(GLProfile.GL2ES1)) {
             System.out.println("GLProfile GL2ES1 n/a");
             return;
@@ -127,7 +114,7 @@ public class TestGLProfile01NEWT extends UITestCase {
     }
 
     @Test
-    public void test05GLProfileGL2ES2() throws InterruptedException {
+    public void testGLProfileGL2ES2() throws InterruptedException {
         if(!GLProfile.isAvailable(GLProfile.GL2ES2)) {
             System.out.println("GLProfile GL2ES2 n/a");
             return;
@@ -137,8 +124,52 @@ public class TestGLProfile01NEWT extends UITestCase {
         dumpVersion(glp);
     }
     
+    void testSpecificProfile(String glps) throws InterruptedException {
+        if(GLProfile.isAvailable(glps)) {
+            GLProfile glp = GLProfile.get(glps);
+            dumpVersion(glp);
+        } else {
+            System.err.println("Profile "+glps+" n/a");
+        }
+    }
+    
+    @Test
+    public void testGL4bc() throws InterruptedException {
+        testSpecificProfile(GLProfile.GL4bc);
+    }
+
+    @Test
+    public void testGL3bc() throws InterruptedException {
+        testSpecificProfile(GLProfile.GL3bc);
+    }
+
+    @Test
+    public void testGL2() throws InterruptedException {
+        testSpecificProfile(GLProfile.GL2);
+    }
+    
+    @Test
+    public void testGL4() throws InterruptedException {
+        testSpecificProfile(GLProfile.GL4);
+    }
+
+    @Test
+    public void testGL3() throws InterruptedException {
+        testSpecificProfile(GLProfile.GL3);
+    }
+
+    @Test
+    public void testGLES1() throws InterruptedException {
+        testSpecificProfile(GLProfile.GLES1);
+    }
+
+    @Test
+    public void testGLES2() throws InterruptedException {
+        testSpecificProfile(GLProfile.GLES2);
+    }
+    
     protected void dumpVersion(GLProfile glp) throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(glp);
+        GLCapabilities caps = new GLCapabilities(glp);        
         GLWindow glWindow = GLWindow.create(caps);
         Assert.assertNotNull(glWindow);
         glWindow.setTitle("TestGLProfile01NEWT");
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGPUMemSec01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGPUMemSec01NEWT.java
index a369f54..4fa587e 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGPUMemSec01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestGPUMemSec01NEWT.java
@@ -55,8 +55,8 @@ public class TestGPUMemSec01NEWT extends UITestCase {
              ", rowlenA1 "+rl1+", rowlenA4 "+rl4+", rowlenA8 "+rl8;        
     }
     
-    static NEWTGLContext.WindowContext createCurrentGLOffscreenWindow(int width, int height) throws GLException, InterruptedException {
-        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOffscreenWindow(GLProfile.getGL2ES2(), width, height, true);
+    static NEWTGLContext.WindowContext createCurrentGLOffscreenWindow(GLProfile glp, int width, int height) throws GLException, InterruptedException {
+        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOffscreenWindow(glp, width, height, true);
         final GL gl = winctx.context.getGL();
 
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
@@ -229,12 +229,59 @@ public class TestGPUMemSec01NEWT extends UITestCase {
     }
     
     @Test
-    public void testReadPixels_640x480xRGBxUB() throws InterruptedException {
+    public void testReadPixelsGL_640x480xRGBAxUB() throws InterruptedException {
+        GLProfile glp = GLProfile.getDefault();
         final int width = 640;
         final int height= 480;
         
         // preset ..
-        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(width, height);
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, width, height);
+        final GLDrawable drawable = winctx.context.getGLDrawable();
+        final GL gl = winctx.context.getGL();
+        
+        // 2 x too small - 0 x alignment
+        Assert.assertEquals(2, readPixelsCheck(gl, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, 4, width, height));
+                        
+        drawable.swapBuffers();
+        Thread.sleep(50);
+        
+        NEWTGLContext.destroyWindow(winctx);
+    }
+    
+    @Test
+    public void testReadPixelsGL_99x100xRGBxUB() throws InterruptedException {
+        GLProfile glp = GLProfile.getGL2ES2();
+        final int wwidth = 640;
+        final int wheight= 480;
+        final int rwidth =  99;
+        final int rheight= 100;
+        
+        // preset ..
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, wwidth, wheight);
+        final GLDrawable drawable = winctx.context.getGLDrawable();
+        final GL gl = winctx.context.getGL();
+        
+        // 2 x too small - 1 x alignment
+        Assert.assertEquals(3, readPixelsCheck(gl, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, 4, rwidth, rheight));
+                        
+        drawable.swapBuffers();
+        Thread.sleep(50);
+        
+        NEWTGLContext.destroyWindow(winctx);
+    }
+    
+    @Test
+    public void testReadPixelsGL2GL3_640x480xRGBxUB() throws InterruptedException {
+        GLProfile glp = GLProfile.getGL2ES2();
+        if(!glp.isGL2GL3()) {
+            System.err.println("GL2GL3 n/a skip test");
+            return;
+        }
+        final int width = 640;
+        final int height= 480;
+        
+        // preset ..
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, width, height);
         final GLDrawable drawable = winctx.context.getGLDrawable();
         final GL gl = winctx.context.getGL();
         
@@ -248,14 +295,19 @@ public class TestGPUMemSec01NEWT extends UITestCase {
     }
     
     @Test
-    public void testReadPixels_102x100xRGBxUB() throws InterruptedException {
+    public void testReadPixelsGL2GL3_99x100xRGBxUB() throws InterruptedException {
+        GLProfile glp = GLProfile.getGL2ES2();
+        if(!glp.isGL2GL3()) {
+            System.err.println("GL2GL3 n/a skip test");
+            return;
+        }
         final int wwidth = 640;
         final int wheight= 480;
-        final int rwidth = 102;
+        final int rwidth =  99;
         final int rheight= 100;
         
         // preset ..
-        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(wwidth, wheight);
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, wwidth, wheight);
         final GLDrawable drawable = winctx.context.getGLDrawable();
         final GL gl = winctx.context.getGL();
         
@@ -270,7 +322,8 @@ public class TestGPUMemSec01NEWT extends UITestCase {
     
     @Test
     public void testReadPixelsGL2GL3_640x480xREDxUB() throws InterruptedException {
-        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+        GLProfile glp = GLProfile.getGL2ES2();
+        if(!glp.isGL2GL3()) {
             System.err.println("GL2GL3 n/a skip test");
             return;
         }
@@ -278,7 +331,7 @@ public class TestGPUMemSec01NEWT extends UITestCase {
         final int height= 480;
 
         // preset ..
-        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(width, height);
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, width, height);
         final GLDrawable drawable = winctx.context.getGLDrawable();
         final GL2GL3 gl = winctx.context.getGL().getGL2GL3();
         
@@ -293,7 +346,8 @@ public class TestGPUMemSec01NEWT extends UITestCase {
 
     @Test
     public void testReadPixelsGL2GL3_102x100xREDxUB() throws InterruptedException {
-        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+        GLProfile glp = GLProfile.getGL2ES2();
+        if(!glp.isGL2GL3()) {
             System.err.println("GL2GL3 n/a skip test");
             return;
         }
@@ -303,7 +357,7 @@ public class TestGPUMemSec01NEWT extends UITestCase {
         int rheight= 100;
 
         // preset ..
-        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(wwidth, wheight);
+        final NEWTGLContext.WindowContext winctx = createCurrentGLOffscreenWindow(glp, wwidth, wheight);
         final GLDrawable drawable = winctx.context.getGLDrawable();
         final GL2GL3 gl = winctx.context.getGL().getGL2GL3();
         
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrentNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrentNEWT.java
index fc025d0..8c0213e 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrentNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestInitConcurrentNEWT.java
@@ -39,6 +39,7 @@ import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.NewtFactory;
 import com.jogamp.newt.Window;
 import com.jogamp.newt.opengl.GLWindow;
@@ -90,7 +91,7 @@ public class TestInitConcurrentNEWT extends UITestCase {
             glWindow.setTitle("Task "+id);
             glWindow.setPosition(x + insets.getLeftWidth(), y + insets.getTopHeight() );
     
-            glWindow.addGLEventListener(new GearsES2(0));
+            glWindow.addGLEventListener(new GearsES2(1));
     
             Animator animator = new Animator(glWindow);
     
@@ -135,7 +136,7 @@ public class TestInitConcurrentNEWT extends UITestCase {
         return true;
     }
     protected static String doneDump(JOGLTask[] tasks) {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("[");
         for(int i=0; i<tasks.length; i++) {
             if(i>0) {
@@ -156,7 +157,7 @@ public class TestInitConcurrentNEWT extends UITestCase {
         return true;
     }
     protected static String isAliveDump(Thread[] threads) {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         sb.append("[");
         for(int i=0; i<threads.length; i++) {
             if(i>0) {
@@ -211,7 +212,11 @@ public class TestInitConcurrentNEWT extends UITestCase {
     
     @Test
     public void test16SixteenThreads() throws InterruptedException {
-        runJOGLTasks(16);
+        if( Platform.getCPUFamily() == Platform.CPUFamily.ARM ) {
+            runJOGLTasks(8);
+        } else {
+            runJOGLTasks(16);
+        }
     }
     
     public static void main(String args[]) throws IOException {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBuffer01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java
similarity index 85%
rename from src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBuffer01NEWT.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java
index bad04ad..d264d42 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBuffer01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestMapBufferRead01NEWT.java
@@ -46,23 +46,31 @@ import org.junit.Test;
  *
  * @author Luz, et.al.
  */
-public class TestMapBuffer01NEWT extends UITestCase {
+public class TestMapBufferRead01NEWT extends UITestCase {
     static final boolean DEBUG = false;
     
     @Test
     public void testWriteRead01a() throws InterruptedException {
+        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+            System.err.println("Test requires GL2/GL3 profile.");
+            return;
+        }
         ByteBuffer verticiesBB = ByteBuffer.allocate(4*9);
         verticiesBB.order(ByteOrder.nativeOrder());
         testWriteRead01(verticiesBB);
     }
     @Test
     public void testWriteRead01b() throws InterruptedException {
+        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+            System.err.println("Test requires GL2/GL3 profile.");
+            return;
+        }
         ByteBuffer verticiesBB = Buffers.newDirectByteBuffer(4*9);
         testWriteRead01(verticiesBB);
     }
 
     private void testWriteRead01(ByteBuffer verticiesBB) throws InterruptedException {
-        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOffscreenWindow(GLProfile.getDefault(), 800, 600, true);
+        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOffscreenWindow(GLProfile.getGL2GL3(), 800, 600, true);
         final GL gl = winctx.context.getGL();
 
         int[] vertexBuffer = new int[1];
@@ -89,11 +97,12 @@ public class TestMapBuffer01NEWT extends UITestCase {
 
         gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBuffer[0]);
 
-        // gl.glBufferData(GL3.GL_ARRAY_BUFFER, verticiesBB.capacity(), verticiesBB, GL3.GL_STATIC_READ);
+        // gl.glBufferData(GL.GL_ARRAY_BUFFER, verticiesBB.capacity(), verticiesBB, GL.GL_STATIC_READ);
         gl.glBufferData(GL.GL_ARRAY_BUFFER, verticiesBB.capacity(), verticiesBB, GL.GL_STATIC_DRAW);
         
         ByteBuffer bb = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL2GL3.GL_READ_ONLY);
-        // gl.glUnmapBuffer(GL3.GL_ARRAY_BUFFER);
+        Assert.assertNotNull(bb);
+        
         if(DEBUG) {
             for(int i=0; i < bb.capacity(); i+=4) {
                 System.out.println("gpu "+i+": "+bb.getFloat(i));
@@ -102,10 +111,11 @@ public class TestMapBuffer01NEWT extends UITestCase {
         for(int i=0; i < bb.capacity(); i+=4) {
             Assert.assertEquals(verticiesBB.getFloat(i), bb.getFloat(i), 0.0);
         }
+        gl.glUnmapBuffer(GL.GL_ARRAY_BUFFER);
         NEWTGLContext.destroyWindow(winctx);
     }
     public static void main(String args[]) throws IOException {
-        String tstname = TestMapBuffer01NEWT.class.getName();
+        String tstname = TestMapBufferRead01NEWT.class.getName();
         org.junit.runner.JUnitCore.main(tstname);
     }    
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java
new file mode 100644
index 0000000..e14d5b8
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNEWTCloseX11DisplayBug565.java
@@ -0,0 +1,108 @@
+package com.jogamp.opengl.test.junit.jogl.acore;
+
+import jogamp.nativewindow.x11.X11Util;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.jogamp.newt.opengl.GLWindow;
+
+import javax.media.nativewindow.NativeWindowFactory;
+import javax.media.opengl.DefaultGLCapabilitiesChooser;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesImmutable;
+import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLPbuffer;
+import javax.media.opengl.GLProfile;
+
+/**
+ * Tests the closing the device of GLWindow and GLPBuffer in JOGL
+ */
+public class TestNEWTCloseX11DisplayBug565 {
+
+  @Test
+  public void testX11WindowMemoryLeak() throws Exception {
+    GLProfile.initSingleton(); // ensure shared resource runner is done
+    try {
+      for ( int j = 0; j < 10; j++ ) {
+        final int open0;
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {        
+            open0 = X11Util.getOpenDisplayConnectionNumber();
+        } else {
+            open0 = 0;
+        }
+                
+        GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault( ) );
+        
+        GLWindow window = GLWindow.create(caps);
+        window.setTitle("NEWT Resource X11 Leak - #" + j );  
+        window.setSize( 128, 128 );
+        window.setVisible(true);
+        window.display();
+        window.setVisible(false);
+        window.destroy();
+
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {
+            final int openD = X11Util.getOpenDisplayConnectionNumber() - open0;
+            if(openD>1) {
+                X11Util.dumpOpenDisplayConnections();
+                X11Util.dumpPendingDisplayConnections();
+                Assert.assertTrue("More than 1 new open display connections", false);
+            }
+        }
+      }
+    }
+    catch ( Exception e ) {
+      e.printStackTrace();
+      Assert.fail(e.getMessage());
+    }
+  }
+
+
+  @Test
+  public void testX11WindowMemoryLeakOffscreenWindow() throws Exception {
+    GLProfile.initSingleton(); // ensure shared resource runner is done
+    try {
+      for ( int j = 0; j < 10; j++ ) {
+        final int open0;
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {        
+            open0 = X11Util.getOpenDisplayConnectionNumber();
+        } else {
+            open0 = 0;
+        }
+        final GLProfile glp = GLProfile.getDefault( );
+        GLCapabilitiesImmutable caps = new GLCapabilities( glp );
+
+
+        GLPbuffer buffer = GLDrawableFactory.getFactory( glp ).createGLPbuffer(
+            null,
+            caps,
+            new DefaultGLCapabilitiesChooser(),
+            256,
+            256,
+            null
+        );
+        buffer.display();
+        buffer.destroy();
+
+        if(NativeWindowFactory.TYPE_X11 == NativeWindowFactory.getNativeWindowType(false)) {
+            final int openD = X11Util.getOpenDisplayConnectionNumber() - open0;
+            if(openD>1) {
+                X11Util.dumpOpenDisplayConnections();
+                X11Util.dumpPendingDisplayConnections();
+                Assert.assertTrue("More than 1 new open display connections", false);
+            }
+        }
+      }
+    }
+    catch ( Exception e ) {
+      e.printStackTrace();
+      Assert.fail(e.getMessage());
+    }
+  }
+
+  public static void main(String args[]) {
+    org.junit.runner.JUnitCore.main(TestNEWTCloseX11DisplayBug565.class.getName());
+  }
+  
+}
+
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java
index 05f122b..54f9943 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java
@@ -52,7 +52,7 @@ public class TestNVSwapGroupNEWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
+        glp = GLProfile.getGL2ES2();
         Assert.assertNotNull(glp);
         caps = new GLCapabilities(glp);
         Assert.assertNotNull(caps);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestPBufferDeadlockAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestPBufferDeadlockAWT.java
index 5f04ed6..3a25d12 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestPBufferDeadlockAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestPBufferDeadlockAWT.java
@@ -51,14 +51,14 @@ public class TestPBufferDeadlockAWT extends UITestCase {
 
   @BeforeClass
   public static void initClass() {
-    glp = GLProfile.getDefault();
+    glp = GLProfile.getGL2ES2();
     Assert.assertNotNull( glp );
     width = 512;
     height = 512;
   }
 
   protected void runTestGL( GLCapabilities caps ) throws InterruptedException, InvocationTargetException {
-    final GLPbuffer pbuffer = GLDrawableFactory.getFactory( GLProfile.get( "GL2" ) ).createGLPbuffer(
+    final GLPbuffer pbuffer = GLDrawableFactory.getFactory( GLProfile.getGL2ES2() ).createGLPbuffer(
         null,
         caps, new DefaultGLCapabilitiesChooser(),
         512, 512,
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListAWT.java
index dc08229..60502ba 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListAWT.java
@@ -33,6 +33,8 @@ import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLPbuffer;
 import javax.media.opengl.GLProfile;
 import javax.media.opengl.awt.GLCanvas;
+
+import com.jogamp.common.os.Platform;
 import com.jogamp.opengl.util.Animator;
 
 import com.jogamp.opengl.test.junit.util.UITestCase;
@@ -56,12 +58,22 @@ public class TestSharedContextListAWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT.java
index 3080947..39367d1 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT.java
@@ -30,6 +30,7 @@ package com.jogamp.opengl.test.junit.jogl.acore;
 
 import java.io.IOException;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.opengl.GLWindow;
 
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -56,12 +57,22 @@ public class TestSharedContextListNEWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT2.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT2.java
index 4281572..7dca314 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT2.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextListNEWT2.java
@@ -30,6 +30,7 @@ package com.jogamp.opengl.test.junit.jogl.acore;
 
 import java.io.IOException;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.opengl.GLWindow;
 
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -54,12 +55,22 @@ public class TestSharedContextListNEWT2 extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.get(GLProfile.GL2);
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
@@ -108,7 +119,7 @@ public class TestSharedContextListNEWT2 extends UITestCase {
         return glWindow;
     }
 
-    @Test
+    @Test(timeout=10000)
     public void test01() throws InterruptedException {
         initShared();
         GLWindow f1 = runTestGL(new Animator(), 0, 0, true, false);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextNewtAWTBug523.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextNewtAWTBug523.java
index 60f46fe..bc2eddb 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextNewtAWTBug523.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextNewtAWTBug523.java
@@ -60,9 +60,11 @@ import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
 
 import org.junit.Assert;
+import org.junit.BeforeClass;
 import org.junit.Test;
 
 import com.jogamp.common.nio.Buffers;
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.awt.NewtCanvasAWT;
 import com.jogamp.newt.opengl.GLWindow;
 import com.jogamp.opengl.test.junit.util.AWTRobotUtil;
@@ -114,6 +116,19 @@ public class TestSharedContextNewtAWTBug523 extends UITestCase {
     private static FloatBuffer sharedVertexBuffer;
     private static IntBuffer sharedIndexBuffer;
 
+    @BeforeClass
+    public static void initClass() {
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(!GLProfile.isAvailable(GLProfile.GL2)) {
+            setTestSupported(false);
+        }
+    }
+    
     static private GLPbuffer initShared(GLCapabilities caps) {
         GLPbuffer sharedDrawable = GLDrawableFactory.getFactory(caps.getGLProfile()).createGLPbuffer(null, caps, null, 64, 64, null);
         Assert.assertNotNull(sharedDrawable);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES1NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES1NEWT.java
index 6e48e44..707bd5a 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES1NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES1NEWT.java
@@ -28,6 +28,7 @@
  
 package com.jogamp.opengl.test.junit.jogl.acore;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.opengl.GLWindow;
 
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -54,12 +55,22 @@ public class TestSharedContextVBOES1NEWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2ES1)) {
+            glp = GLProfile.get(GLProfile.GL2ES1);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT.java
index 022ef21..ce2bd77 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT.java
@@ -28,6 +28,7 @@
  
 package com.jogamp.opengl.test.junit.jogl.acore;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.opengl.GLWindow;
 
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -54,12 +55,22 @@ public class TestSharedContextVBOES2NEWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2ES2)) {
+            glp = GLProfile.get(GLProfile.GL2ES2);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT2.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT2.java
index 5b2cb25..8911e73 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT2.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestSharedContextVBOES2NEWT2.java
@@ -30,6 +30,7 @@ package com.jogamp.opengl.test.junit.jogl.acore;
 
 import java.io.IOException;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.opengl.GLWindow;
 
 import javax.media.nativewindow.util.InsetsImmutable;
@@ -54,12 +55,22 @@ public class TestSharedContextVBOES2NEWT2 extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.get(GLProfile.GL2);
-        Assert.assertNotNull(glp);
-        caps = new GLCapabilities(glp);
-        Assert.assertNotNull(caps);
-        width  = 256;
-        height = 256;
+        if(Platform.CPUFamily.X86 != Platform.CPU_ARCH.family) { // FIXME
+            // FIXME: Turns out on some mobile GL drivers and platforms 
+            // using shared context is instable, Linux ARM (Omap4, Tegra2, Mesa3d, ..)
+            setTestSupported(false);
+            return;
+        }
+        if(GLProfile.isAvailable(GLProfile.GL2ES2)) {
+            glp = GLProfile.get(GLProfile.GL2ES2);
+            Assert.assertNotNull(glp);
+            caps = new GLCapabilities(glp);
+            Assert.assertNotNull(caps);
+            width  = 256;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     private void initShared() {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteAWT.java
index 322ce36..9f2820a 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteAWT.java
@@ -39,7 +39,7 @@ import javax.media.opengl.awt.GLCanvas;
 import org.junit.Assert;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.util.Animator;
 
@@ -51,12 +51,12 @@ public class TestShutdownCompleteAWT extends UITestCase {
         final Frame frame = new Frame("Gears AWT Test");
         Assert.assertNotNull(frame);
 
-        final GLCanvas glCanvas = new GLCanvas(new GLCapabilities(GLProfile.getDefault()));
+        final GLCanvas glCanvas = new GLCanvas(new GLCapabilities(GLProfile.getGL2ES2()));
         Assert.assertNotNull(glCanvas);
         frame.add(glCanvas);
         frame.setSize(256, 256);
 
-        glCanvas.addGLEventListener(new Gears(1));
+        glCanvas.addGLEventListener(new GearsES2(1));
 
         Animator animator = new Animator(glCanvas);
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteNEWT.java
index 1abac10..4592841 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownCompleteNEWT.java
@@ -39,7 +39,7 @@ import org.junit.Assert;
 import org.junit.Test;
 
 import com.jogamp.newt.opengl.GLWindow;
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.util.Animator;
 
@@ -48,11 +48,11 @@ public class TestShutdownCompleteNEWT extends UITestCase {
     static long duration = 300; // ms
     
     protected void runTestGL() throws InterruptedException {
-        GLWindow glWindow = GLWindow.create(new GLCapabilities(GLProfile.getDefault()));
+        GLWindow glWindow = GLWindow.create(new GLCapabilities(GLProfile.getGL2ES2()));
         Assert.assertNotNull(glWindow);
         glWindow.setTitle("Gears NEWT Test");
 
-        glWindow.addGLEventListener(new Gears());
+        glWindow.addGLEventListener(new GearsES2());
 
         Animator animator = new Animator(glWindow);
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedAWT.java
index a12ef23..3274ea8 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedAWT.java
@@ -39,7 +39,7 @@ import javax.media.opengl.awt.GLCanvas;
 import org.junit.Assert;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.util.Animator;
 
@@ -51,12 +51,12 @@ public class TestShutdownSharedAWT extends UITestCase {
         final Frame frame = new Frame("Gears AWT Test");
         Assert.assertNotNull(frame);
 
-        final GLCanvas glCanvas = new GLCanvas(new GLCapabilities(GLProfile.getDefault()));
+        final GLCanvas glCanvas = new GLCanvas(new GLCapabilities(GLProfile.getGL2ES2()));
         Assert.assertNotNull(glCanvas);
         frame.add(glCanvas);
         frame.setSize(256, 256);
 
-        glCanvas.addGLEventListener(new Gears(1));
+        glCanvas.addGLEventListener(new GearsES2(1));
 
         Animator animator = new Animator(glCanvas);
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedNEWT.java
index 99b5a6c..8db7dff 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestShutdownSharedNEWT.java
@@ -39,7 +39,7 @@ import org.junit.Assert;
 import org.junit.Test;
 
 import com.jogamp.newt.opengl.GLWindow;
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.util.Animator;
 
@@ -48,11 +48,11 @@ public class TestShutdownSharedNEWT extends UITestCase {
     static long duration = 300; // ms
     
     protected void runTestGL() throws InterruptedException {
-        GLWindow glWindow = GLWindow.create(new GLCapabilities(GLProfile.getDefault()));
+        GLWindow glWindow = GLWindow.create(new GLCapabilities(GLProfile.getGL2ES2()));
         Assert.assertNotNull(glWindow);
         glWindow.setTitle("Gears NEWT Test");
 
-        glWindow.addGLEventListener(new Gears());
+        glWindow.addGLEventListener(new GearsES2());
 
         Animator animator = new Animator(glWindow);
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWT01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWT01GLn.java
index 55bdb95..64a1a01 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWT01GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWT01GLn.java
@@ -116,16 +116,24 @@ public class TestAWT01GLn extends UITestCase {
     public void test01GLDefault() throws InterruptedException {
         GLProfile glp = GLProfile.getDefault();
         System.out.println("GLProfile Default: "+glp);
-        GLCapabilities caps = new GLCapabilities(glp);
-        runTestGL(caps);
+        if(glp.isGL2ES2()) {
+            GLCapabilities caps = new GLCapabilities(glp);
+            runTestGL(caps);
+        } else {
+            System.out.println("not a GL2ES2 profile");
+        }
     }
 
     @Test
     public void test02GL2() throws InterruptedException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
-        GLCapabilities caps = new GLCapabilities(glprofile);
-        runTestGL(caps);
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            GLProfile glprofile = GLProfile.get(GLProfile.GL2);
+            System.out.println( "GLProfile GL2: " + glprofile );
+            GLCapabilities caps = new GLCapabilities(glprofile);
+            runTestGL(caps);
+        } else {
+            System.out.println("GL2 n/a");
+        }
     }
 
     public static void main(String args[]) {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWTCardLayoutAnimatorStartStopBug532.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWTCardLayoutAnimatorStartStopBug532.java
new file mode 100644
index 0000000..8384e5b
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestAWTCardLayoutAnimatorStartStopBug532.java
@@ -0,0 +1,229 @@
+package com.jogamp.opengl.test.junit.jogl.awt;
+
+import java.awt.BorderLayout;
+import java.awt.CardLayout;
+import java.awt.Dimension;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.lang.reflect.InvocationTargetException;
+
+import javax.media.nativewindow.NativeWindow;
+import javax.media.opengl.GLAnimatorControl;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.awt.GLCanvas;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+
+import jogamp.nativewindow.windows.GDI;
+
+import org.junit.Test;
+
+import com.jogamp.common.os.Platform;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
+import com.jogamp.opengl.test.junit.util.UITestCase;
+import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.FPSAnimator;
+
+public class TestAWTCardLayoutAnimatorStartStopBug532 extends UITestCase {
+    static final String LABEL = "Label"; 
+    static final String CANVAS = "GLCanvas";
+    
+    public enum AnimatorControlBehavior {
+        StartStop, PauseResume, Continue;
+    }
+    
+    static long durationPerTest = 200*4; // ms    
+    static boolean manual = false;
+    static volatile boolean shouldStop = false;
+    
+    private String selected = LABEL;
+    
+    @Test
+    public void testFPSAnimatorStartStop() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.StartStop, true);
+    }
+    
+    @Test
+    public void testFPSAnimatorResumePause() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.PauseResume, true);
+    }
+    
+    @Test
+    public void testFPSAnimatorContinue() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.Continue, true);
+    }
+    
+    @Test
+    public void testAnimatorStartStop() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.StartStop, false);
+    }
+    
+    @Test
+    public void testAnimatorResumePause() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.PauseResume, false);
+    }
+    
+    @Test
+    public void testAnimatorContinue() throws InterruptedException, InvocationTargetException {
+        testImpl(AnimatorControlBehavior.Continue, false);
+    }
+    
+    void testImpl(final AnimatorControlBehavior animCtrl, boolean useFPSAnimator) throws InterruptedException, InvocationTargetException {
+      final GLProfile glp = GLProfile.get(GLProfile.GL2); 
+      final GLCapabilities caps = new GLCapabilities(glp); 
+      final GLCanvas canvas = new GLCanvas(caps); 
+      canvas.setPreferredSize(new Dimension(640, 480));
+      
+      final GLAnimatorControl animatorCtrl = useFPSAnimator ? new FPSAnimator(canvas, 60) : new Animator(canvas);
+      animatorCtrl.setUpdateFPSFrames(60, System.err);
+      switch (animCtrl) {
+          case PauseResume:
+              animatorCtrl.start();
+              animatorCtrl.pause();
+              break;
+          case Continue:
+              animatorCtrl.start();
+              break;
+      }
+
+      canvas.addGLEventListener(new GearsES2(1));
+      /* if(Platform.OS_TYPE == Platform.OSType.WINDOWS) {
+          canvas.addGLEventListener(new GLEventListener() {
+            public void init(GLAutoDrawable drawable) { } 
+            public void dispose(GLAutoDrawable drawable) { }
+            public void display(GLAutoDrawable drawable) {
+                final NativeWindow win = (NativeWindow) drawable.getNativeSurface();
+                long hdc = win.getSurfaceHandle();
+                long hdw = win.getWindowHandle();
+                long hdw_hdc = GDI.WindowFromDC(hdc);
+                System.err.println("*** hdc 0x"+Long.toHexString(hdc)+", hdw(hdc) 0x"+Long.toHexString(hdw_hdc)+", hdw 0x"+Long.toHexString(hdw) + " - " + Thread.currentThread().getName() + ", " + animatorCtrl);
+                // System.err.println(drawable.getNativeSurface().toString());
+            }
+            public void reshape(GLAutoDrawable drawable, int x, int y, int width,
+                    int height) { }
+          });
+      } */
+
+      final JFrame frame = new JFrame();
+      frame.setTitle(getSimpleTestName(" - "));
+      frame.addWindowListener(new WindowAdapter() { 
+         public void windowClosing(WindowEvent e) {
+            animatorCtrl.stop();
+            shouldStop = true;
+         } 
+      });
+      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+      
+      final JPanel cards = new JPanel(new CardLayout());      
+      final JPanel comboBoxPanel = new JPanel(); // nicer look ..
+      final JComboBox comboBox = new JComboBox(new String[] { LABEL, CANVAS });
+      comboBox.setEditable(false);
+      comboBox.addItemListener(new ItemListener() {
+        public void itemStateChanged(final ItemEvent evt) {
+            final CardLayout cl = (CardLayout)(cards.getLayout());
+            final String newSelection = (String)evt.getItem();
+            if(!newSelection.equals(selected)) {
+                final String oldSelected = selected;
+                if(newSelection.equals(CANVAS)) {
+                    cl.show(cards, CANVAS); 
+                    switch (animCtrl) {
+                       case StartStop:
+                           animatorCtrl.start();
+                           break;
+                       case PauseResume:
+                           animatorCtrl.resume();
+                           break;
+                    }
+                    selected = CANVAS;
+                } else if(newSelection.equals(LABEL)) {
+                    switch (animCtrl) {
+                       case StartStop:
+                           animatorCtrl.stop();
+                           break;
+                       case PauseResume:
+                           animatorCtrl.pause();
+                           break;
+                    }
+                    cl.show(cards, LABEL); 
+                    selected = LABEL;
+                } else {
+                    throw new RuntimeException("oops .. unexpected item: "+evt);
+                }
+                System.err.println("Item Change: "+oldSelected+" -> "+selected+", "+animatorCtrl);                
+            } else {
+                System.err.println("Item Stays: "+selected+", "+animatorCtrl);
+            }
+        }
+      });
+      comboBoxPanel.add(comboBox);            
+
+      cards.add(new JLabel("A label to cover the canvas"), LABEL); 
+      cards.add(canvas, CANVAS);
+      
+      frame.add(comboBoxPanel, BorderLayout.PAGE_START);
+      frame.add(cards, BorderLayout.CENTER);
+      
+      frame.pack(); 
+      
+      javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+        public void run() {
+            frame.setVisible(true);
+        }});
+    
+      if(manual) {
+          for(long w=durationPerTest; !shouldStop && w>0; w-=100) {
+              Thread.sleep(100);
+          }
+      } else {
+          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                comboBox.setSelectedItem(LABEL);
+            }});
+          Thread.sleep(durationPerTest/4);
+          
+          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                comboBox.setSelectedItem(CANVAS);
+            }});
+          Thread.sleep(durationPerTest/4);
+          
+          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                comboBox.setSelectedItem(LABEL);
+            }});
+          Thread.sleep(durationPerTest/4);
+          
+          javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                comboBox.setSelectedItem(CANVAS);
+            }});
+          Thread.sleep(durationPerTest/4);
+      }
+      
+      javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+        public void run() {
+            frame.setVisible(false);
+            frame.dispose();
+        }});
+      
+    }
+    
+    public static void main(String args[]) {
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-time")) {
+                durationPerTest = MiscUtils.atoi(args[++i], (int)durationPerTest);
+            } else if(args[i].equals("-manual")) {
+                manual = true;
+            }
+        }
+        org.junit.runner.JUnitCore.main(TestAWTCardLayoutAnimatorStartStopBug532.class.getName());
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461OffscreenSupersamplingSwingAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461OffscreenSupersamplingSwingAWT.java
index 284122b..6a315c6 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461OffscreenSupersamplingSwingAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug461OffscreenSupersamplingSwingAWT.java
@@ -125,7 +125,7 @@ public class TestBug461OffscreenSupersamplingSwingAWT extends UITestCase impleme
         GLDrawableFactory fac = GLDrawableFactory.getFactory(glp);
         Assert.assertNotNull(fac);
         
-        Assert.assertTrue( fac.canCreateGLPbuffer(GLProfile.getDefaultDesktopDevice()) );
+        Assert.assertTrue( fac.canCreateGLPbuffer(GLProfile.getDefaultDevice()) );
         
         GLCapabilities glCap = new GLCapabilities(glp);
         Assert.assertNotNull(glCap);
@@ -140,7 +140,7 @@ public class TestBug461OffscreenSupersamplingSwingAWT extends UITestCase impleme
         glCap.setStencilBits(1);
 
         //makes a new buffer
-        offScreenBuffer = fac.createGLPbuffer(GLProfile.getDefaultDesktopDevice(), glCap, null, 200, 200, null);
+        offScreenBuffer = fac.createGLPbuffer(GLProfile.getDefaultDevice(), glCap, null, 200, 200, null);
         Assert.assertNotNull(offScreenBuffer);
         offScreenBuffer.addGLEventListener(this);        
         offScreenBuffer.display();
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug551AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug551AWT.java
new file mode 100644
index 0000000..e68ddb4
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestBug551AWT.java
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2010 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+ 
+package com.jogamp.opengl.test.junit.jogl.awt;
+
+import java.lang.reflect.InvocationTargetException;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.awt.GLCanvas;
+import com.jogamp.opengl.util.Animator;
+
+import com.jogamp.opengl.test.junit.util.UITestCase;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
+
+
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Rectangle;
+import java.awt.Window;
+import javax.swing.JFrame;
+
+import org.junit.Test;
+
+import static org.junit.Assume.*;
+import static javax.swing.SwingUtilities.*;
+
+/**
+ * Tests context creation + display on various kinds of Window implementations.
+ * @author Michael Bien, et. al.
+ */
+public class TestBug551AWT extends UITestCase {
+
+    static void checkGraphicsEnvironment() {
+        Rectangle virtualBounds = new Rectangle();
+        GraphicsEnvironment ge =GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gs = ge.getScreenDevices();
+
+        //write graphics devices to log 
+        System.err.println("number of graphics devices " + gs.length);
+        for(int i =0 ; i < gs.length; i++) {
+            System.err.println(gs[i].toString());
+        }
+
+        //check for bounds
+        for (int j = 0; j < gs.length; j++) { 
+            GraphicsDevice gd = gs[j];
+            GraphicsConfiguration[] gc = gd.getConfigurations();
+            for (int i=0; i < gc.length; i++) {
+                System.err.println("graphics configuration for device " + j + " is: " + gc[i].getBounds());
+                virtualBounds = virtualBounds.union(gc[i].getBounds());
+            }            
+        }
+
+    }
+    
+    protected void runTestGL() throws InterruptedException, InvocationTargetException {
+        final Window window = new JFrame(this.getSimpleTestName(" - "));
+        final GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2());
+        
+        // final array as mutable container hack
+        final GLCanvas[] glCanvas = new GLCanvas[1];
+
+        Runnable test = new Runnable() {
+            public void run() {
+                glCanvas[0] = new GLCanvas(caps);
+                glCanvas[0].addGLEventListener(new GearsES2());
+                window.add(glCanvas[0]);
+
+                // Revalidate size/layout.
+                // Always validate if component added/removed.
+                // Ensure 1st paint of GLCanvas will have a valid size, hence drawable gets created.
+                window.setSize(512, 512);
+                window.validate();
+
+                window.setVisible(true);
+                glCanvas[0].display();
+            }
+        };
+
+        Runnable cleanup = new Runnable() {
+            public void run() {
+                System.out.println("cleaning up...");
+                window.setVisible(false);
+                try {
+                    window.removeAll();
+                } catch (Throwable t) {
+                    assumeNoException(t);
+                    t.printStackTrace();
+                }
+                window.dispose();
+            }
+
+        };
+
+        // AWT / Swing on EDT..
+        invokeAndWait(test);
+
+        Animator animator = new Animator(glCanvas[0]);
+        animator.start();
+        Thread.sleep(1000);
+        animator.stop();
+
+        // AWT / Swing on EDT..
+        invokeAndWait(cleanup);
+    }
+
+    // @Test
+    public void test01Plain() throws InterruptedException, InvocationTargetException {
+        runTestGL();
+    }
+
+    @Test
+    public void test02WithCheckGraphicsEnvironment() throws InterruptedException, InvocationTargetException {
+        checkGraphicsEnvironment();
+        runTestGL();
+    }
+
+    public static void main(String args[]) {
+        org.junit.runner.JUnitCore.main(TestBug551AWT.class.getName());
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestSwingAWT01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestSwingAWT01GLn.java
index 29f83fc..007df9f 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestSwingAWT01GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/awt/TestSwingAWT01GLn.java
@@ -129,16 +129,24 @@ public class TestSwingAWT01GLn extends UITestCase {
     public void test01GLDefault() throws InterruptedException, InvocationTargetException {
         GLProfile glp = GLProfile.getDefault();
         System.out.println("GLProfile Default: "+glp);
-        GLCapabilities caps = new GLCapabilities(glp);
-        runTestGL(caps);
+        if(glp.isGL2ES2()) {
+            GLCapabilities caps = new GLCapabilities(glp);
+            runTestGL(caps);
+        } else {
+            System.out.println("not a GL2ES2 profile");
+        }
     }
 
     @Test
     public void test02GL2() throws InterruptedException, InvocationTargetException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
-        GLCapabilities caps = new GLCapabilities(glprofile);
-        runTestGL(caps);
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            GLProfile glprofile = GLProfile.get(GLProfile.GL2);
+            System.out.println( "GLProfile GL2: " + glprofile );
+            GLCapabilities caps = new GLCapabilities(glprofile);
+            runTestGL(caps);
+        } else {
+            System.out.println("GL2 n/a");
+        }
     }
 
     public static void main(String args[]) {
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemo01.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemoES1.java
similarity index 70%
rename from src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemo01.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemoES1.java
index ab0171c..0aaf4b0 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemo01.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/MultisampleDemoES1.java
@@ -45,29 +45,33 @@ import jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration;
 import javax.media.nativewindow.AbstractGraphicsConfiguration;
 import javax.media.nativewindow.NativeWindowFactory;
 import javax.media.opengl.GL;
-import javax.media.opengl.GL2;
 import javax.media.opengl.GL2ES1;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLEventListener;
 import javax.media.opengl.GLPipelineFactory;
 
-class MultisampleDemo01 implements GLEventListener {
+import com.jogamp.opengl.util.ImmModeSink;
+
+class MultisampleDemoES1 implements GLEventListener {
 
     static boolean glDebug = false;
     static boolean glTrace = false;
 
     boolean multisample;
+    ImmModeSink immModeSink;
 
-    public MultisampleDemo01(boolean multisample) {
+    public MultisampleDemoES1(boolean multisample) {
         this.multisample = multisample;
     }
 
     public void init(GLAutoDrawable drawable) {
-        AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration();
         System.err.println();
-        System.err.println("Info: " + config);
+        System.err.println("Requested: " + drawable.getNativeSurface().getGraphicsConfiguration().getRequestedCapabilities());
+        System.err.println();
+        System.err.println("Chosen   : " + drawable.getChosenGLCapabilities());
         System.err.println();
-        if (NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(false))) {
+        if (!drawable.getGL().isGLES() && NativeWindowFactory.TYPE_X11.equals(NativeWindowFactory.getNativeWindowType(false))) {
+            AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration();
             X11GLXGraphicsConfiguration x11config = (X11GLXGraphicsConfiguration) config;
             long display = drawable.getNativeSurface().getDisplayHandle();
             int[] foo = new int[1];
@@ -80,16 +84,16 @@ class MultisampleDemo01 implements GLEventListener {
         if (glDebug) {
             try {
                 // Debug ..
-                _gl = _gl.getContext().setGL(GLPipelineFactory.create("javax.media.opengl.Debug", GL2.class, _gl, null));
+                _gl = _gl.getContext().setGL(GLPipelineFactory.create("javax.media.opengl.Debug", GL2ES1.class, _gl, null));
                 if (glTrace) {
                     // Trace ..
-                    _gl = _gl.getContext().setGL(GLPipelineFactory.create("javax.media.opengl.Trace", GL2.class, _gl, new Object[]{System.err}));
+                    _gl = _gl.getContext().setGL(GLPipelineFactory.create("javax.media.opengl.Trace", GL2ES1.class, _gl, new Object[]{System.err}));
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
-        GL2 gl = _gl.getGL2();
+        GL2ES1 gl = _gl.getGL2ES1();
         if (multisample) {
             gl.glEnable(GL.GL_MULTISAMPLE);
         }
@@ -104,26 +108,38 @@ class MultisampleDemo01 implements GLEventListener {
         if (multisample) {
             gl.glDisable(GL.GL_MULTISAMPLE);
         }
+        immModeSink = ImmModeSink.createFixed(gl, GL.GL_STATIC_DRAW, 40, 
+                                              3, GL.GL_FLOAT,  // vertex
+                                              0, GL.GL_FLOAT,  // color
+                                              0, GL.GL_FLOAT,// normal
+                                              0, GL.GL_FLOAT); // texture
+        final int numSteps = 20;
+        final double increment = Math.PI / numSteps;
+        final double radius = 1;
+        immModeSink.glBegin(GL.GL_LINES);
+        for (int i = numSteps - 1; i >= 0; i--) {
+            immModeSink.glVertex3f((float) (radius * Math.cos(i * increment)), 
+                                   (float) (radius * Math.sin(i * increment)), 
+                                   0f);
+            immModeSink.glVertex3f((float) (-1.0 * radius * Math.cos(i * increment)), 
+                                   (float) (-1.0 * radius * Math.sin(i * increment)), 
+                                   0f);
+        }
+        immModeSink.glEnd(gl, false);
     }
 
     public void dispose(GLAutoDrawable drawable) {
+        immModeSink.destroy(drawable.getGL());
+        immModeSink = null;
     }
 
     public void display(GLAutoDrawable drawable) {
-        GL2 gl = drawable.getGL().getGL2();
+        GL2ES1 gl = drawable.getGL().getGL2ES1();
         if (multisample) {
             gl.glEnable(GL.GL_MULTISAMPLE);
         }
         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
-        int numSteps = 20;
-        double increment = Math.PI / numSteps;
-        double radius = 1;
-        gl.glBegin(GL.GL_LINES);
-        for (int i = numSteps - 1; i >= 0; i--) {
-            gl.glVertex3d(radius * Math.cos(i * increment), radius * Math.sin(i * increment), 0);
-            gl.glVertex3d(-1.0 * radius * Math.cos(i * increment), -1.0 * radius * Math.sin(i * increment), 0);
-        }
-        gl.glEnd();
+        immModeSink.draw(gl, true);
         if (multisample) {
             gl.glDisable(GL.GL_MULTISAMPLE);
         }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java
similarity index 92%
rename from src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleAWT.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java
index 786fd60..517d125 100755
--- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1AWT.java
@@ -46,6 +46,7 @@ import java.awt.Frame;
 
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLCapabilitiesChooser;
+import javax.media.opengl.GLProfile;
 import javax.media.opengl.awt.GLCanvas;
 
 import com.jogamp.opengl.test.junit.util.MiscUtils;
@@ -54,7 +55,7 @@ import com.jogamp.opengl.test.junit.util.UITestCase;
 import org.junit.Test;
 
 
-public class TestMultisampleAWT extends UITestCase {
+public class TestMultisampleES1AWT extends UITestCase {
   static long durationPerTest = 250; // ms
   private GLCanvas canvas;
 
@@ -65,7 +66,7 @@ public class TestMultisampleAWT extends UITestCase {
         }
      }
      System.out.println("durationPerTest: "+durationPerTest);
-     String tstname = TestMultisampleAWT.class.getName();
+     String tstname = TestMultisampleES1AWT.class.getName();
      org.junit.runner.JUnitCore.main(tstname);
   }
 
@@ -80,7 +81,8 @@ public class TestMultisampleAWT extends UITestCase {
   }
 
   private void testMultiSampleAAImpl(int samples) throws InterruptedException, InvocationTargetException {
-    GLCapabilities caps = new GLCapabilities(null);
+    GLProfile glp = GLProfile.getMaxFixedFunc(true);
+    GLCapabilities caps = new GLCapabilities(glp);
     GLCapabilitiesChooser chooser = new MultisampleChooser01();
 
     if(samples>0) {
@@ -92,7 +94,7 @@ public class TestMultisampleAWT extends UITestCase {
     }
 
     canvas = new GLCanvas(caps, chooser, null, null);
-    canvas.addGLEventListener(new MultisampleDemo01(samples>0?true:false));
+    canvas.addGLEventListener(new MultisampleDemoES1(samples>0?true:false));
     
     final Frame frame = new Frame("Multi Samples "+samples);
     frame.setLayout(new BorderLayout());
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java
similarity index 89%
rename from src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleNEWT.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java
index 1e3274d..cdfeb2b 100755
--- a/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/caps/TestMultisampleES1NEWT.java
@@ -40,12 +40,16 @@
 
 package com.jogamp.opengl.test.junit.jogl.caps;
 
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesChooser;
+import javax.media.opengl.GLProfile;
+
+import org.junit.Test;
+
 import com.jogamp.newt.opengl.GLWindow;
 import com.jogamp.opengl.test.junit.util.MiscUtils;
-import javax.media.opengl.*;
-import org.junit.Test;
 
-public class TestMultisampleNEWT {
+public class TestMultisampleES1NEWT {
   static long durationPerTest = 500; // ms
   private GLWindow window;
 
@@ -56,7 +60,7 @@ public class TestMultisampleNEWT {
         }
      }
      System.out.println("durationPerTest: "+durationPerTest);
-     String tstname = TestMultisampleNEWT.class.getName();
+     String tstname = TestMultisampleES1NEWT.class.getName();
      org.junit.runner.JUnitCore.main(tstname);
   }
 
@@ -71,7 +75,8 @@ public class TestMultisampleNEWT {
   }
 
   private void testMultiSampleAAImpl(int samples) throws InterruptedException {
-    GLCapabilities caps = new GLCapabilities(null);
+    GLProfile glp = GLProfile.getMaxFixedFunc(true);
+    GLCapabilities caps = new GLCapabilities(glp);
     GLCapabilitiesChooser chooser = new MultisampleChooser01();
 
     if(samples>0) {
@@ -85,14 +90,12 @@ public class TestMultisampleNEWT {
 
     window = GLWindow.create(caps);
     window.setCapabilitiesChooser(chooser);
-    window.addGLEventListener(new MultisampleDemo01(samples>0?true:false));
+    window.addGLEventListener(new MultisampleDemoES1(samples>0?true:false));
     window.setSize(512, 512);
     window.setVisible(true);
     window.setPosition(0, 0);
     window.requestFocus();
 
-    GLCapabilitiesImmutable capsChosen0 = window.getChosenGLCapabilities();
-
     Thread.sleep(durationPerTest);
 
     window.destroy();
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/TestTextureSequence.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/TestTextureSequence.java
new file mode 100644
index 0000000..6dfb118
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/TestTextureSequence.java
@@ -0,0 +1,120 @@
+package com.jogamp.opengl.test.junit.jogl.demos;
+
+import java.net.URLConnection;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+import jogamp.opengl.util.av.NullGLMediaPlayer;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureData;
+import com.jogamp.opengl.util.texture.TextureIO;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+public class TestTextureSequence implements TextureSequence {
+    TextureSequence.TextureFrame frame = null;    
+    int textureUnit = 0;
+    protected int[] texMinMagFilter = { GL.GL_NEAREST, GL.GL_NEAREST };
+    protected int[] texWrapST = { GL.GL_CLAMP_TO_EDGE, GL.GL_CLAMP_TO_EDGE };
+    final boolean useBuildInTexLookup;
+    
+    public TestTextureSequence(boolean useBuildInTexLookup) {
+        this.useBuildInTexLookup = useBuildInTexLookup;
+    }
+    
+    public void initGLResources(GL gl) throws GLException {
+        if(null == frame) {
+            TextureData texData = null;
+            try {
+                URLConnection urlConn = IOUtil.getResource("jogl/util/data/av/test-ntsc01-160x90.png", NullGLMediaPlayer.class.getClassLoader());
+                if(null != urlConn) {
+                    texData = TextureIO.newTextureData(GLProfile.getGL2ES2(), urlConn.getInputStream(), false, TextureIO.PNG);
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+            final Texture tex = new Texture(gl, texData);
+            frame = new TextureSequence.TextureFrame(tex);
+            tex.bind(gl);
+            gl.glTexParameteri(tex.getTarget(), GL.GL_TEXTURE_MIN_FILTER, texMinMagFilter[0]);
+            gl.glTexParameteri(tex.getTarget(), GL.GL_TEXTURE_MAG_FILTER, texMinMagFilter[1]);        
+            gl.glTexParameteri(tex.getTarget(), GL.GL_TEXTURE_WRAP_S, texWrapST[0]);
+            gl.glTexParameteri(tex.getTarget(), GL.GL_TEXTURE_WRAP_T, texWrapST[1]);
+        }
+    }
+    
+    public void destroyGLResources(GL gl) {
+        if(null != frame) {
+            frame.getTexture().destroy(gl);
+            frame = null;
+        }
+    }
+    
+    public void destroy(GL gl) throws GLException {
+        frame.getTexture().destroy(gl);
+        frame = null;        
+    }
+    
+    @Override
+    public int getTextureUnit() {
+        return textureUnit;
+    }
+
+    @Override
+    public int[] getTextureMinMagFilter() {
+        return texMinMagFilter;
+    }
+
+    @Override
+    public int[] getTextureWrapST() {
+        return texWrapST;
+    }
+
+    @Override
+    public TextureSequence.TextureFrame getLastTexture() throws IllegalStateException {
+        return frame; // may return null
+    }
+
+    @Override
+    public TextureSequence.TextureFrame getNextTexture(GL gl, boolean blocking) throws IllegalStateException {
+        return frame;
+    }
+    
+    @Override
+    public String getRequiredExtensionsShaderStub() throws IllegalStateException {
+        return "// TextTextureSequence: No extensions required\n";
+    }
+    
+    @Override
+    public String getTextureSampler2DType() throws IllegalStateException {
+        return "sampler2D" ;
+    }    
+    
+    private String textureLookupFunctionName = "myTexture2D";
+    
+    @Override
+    public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException {
+        if(useBuildInTexLookup) {
+            return "texture2D";
+        }
+        if(null != desiredFuncName && desiredFuncName.length()>0) {
+            textureLookupFunctionName = desiredFuncName;
+        }
+        return textureLookupFunctionName;
+    }
+    
+    @Override
+    public String getTextureLookupFragmentShaderImpl() throws IllegalStateException {
+        if(useBuildInTexLookup) {
+          return "";
+        }
+        return
+          "\n"+
+          "vec4 "+textureLookupFunctionName+"(in "+getTextureSampler2DType()+" image, in vec2 texCoord) {\n"+
+          "  return texture2D(image, texCoord);\n"+
+          "}\n\n";
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java
index b5a729e..fb2c9c7 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/GearsES1.java
@@ -48,7 +48,6 @@ public class GearsES1 implements GLEventListener {
   private GearsObject gear1=null, gear2=null, gear3=null;
   private float angle = 0.0f;
   private int swapInterval;
-  private boolean initialized = false;
 
   private int prevMouseX, prevMouseY;
 
@@ -83,7 +82,6 @@ public class GearsES1 implements GLEventListener {
   
   public void init(GLAutoDrawable drawable) {
     System.err.println(Thread.currentThread()+" GearsES1.init ...");
-    initialized = true;
     
     // Use debug pipeline
     // drawable.setGL(new DebugGL(drawable.getGL()));
@@ -150,12 +148,16 @@ public class GearsES1 implements GLEventListener {
 
     gl.setSwapInterval(swapInterval);
 
-    float h = (float)height / (float)width;
-            
     gl.glMatrixMode(GL2ES1.GL_PROJECTION);
 
     gl.glLoadIdentity();
-    gl.glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
+    if(height>width) {
+        float h = (float)height / (float)width;
+        gl.glFrustumf(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
+    } else {
+        float h = (float)width / (float)height;
+        gl.glFrustumf(-h, h, -1.0f, 1.0f, 5.0f, 60.0f);
+    }
     gl.glMatrixMode(GL2ES1.GL_MODELVIEW);
     gl.glLoadIdentity();
     gl.glTranslatef(0.0f, 0.0f, -40.0f);
@@ -164,7 +166,6 @@ public class GearsES1 implements GLEventListener {
 
   public void dispose(GLAutoDrawable drawable) {
     System.err.println(Thread.currentThread()+" GearsES1.dispose ... ");
-    initialized = false;
     GL gl = drawable.getGL();
     gear1.destroy(gl);
     gear1 = null;
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/OneTriangle.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/OneTriangle.java
similarity index 61%
rename from src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/OneTriangle.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/OneTriangle.java
index fa4d819..a2455e7 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/OneTriangle.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/OneTriangle.java
@@ -26,11 +26,14 @@
  * or implied, of JogAmp Community.
  */
 
-package com.jogamp.opengl.test.junit.jogl.demos.gl2;
+package com.jogamp.opengl.test.junit.jogl.demos.es1;
 
 import javax.media.opengl.GL;
-import javax.media.opengl.GL2;
+import javax.media.opengl.GL2ES1;
 import javax.media.opengl.glu.GLU;
+import javax.media.opengl.glu.gl2es1.GLUgl2es1;
+
+import com.jogamp.opengl.util.ImmModeSink;
 
 /**
  * A utility class to encapsulate drawing a single triangle for unit tests.
@@ -38,32 +41,38 @@ import javax.media.opengl.glu.GLU;
  */
 public class OneTriangle {
 
-    public static void setup( GL2 gl, int width, int height ) {
-        gl.glMatrixMode( GL2.GL_PROJECTION );
+    public static void setup( GL2ES1 gl, int width, int height ) {
+        gl.glMatrixMode( GL2ES1.GL_PROJECTION );
         gl.glLoadIdentity();
 
         // coordinate system origin at lower left with width and height same as the window
-        GLU glu = new GLU();
+        GLU glu = new GLUgl2es1();
         glu.gluOrtho2D( 0.0f, width, 0.0f, height );
 
-        gl.glMatrixMode( GL2.GL_MODELVIEW );
+        gl.glMatrixMode( GL2ES1.GL_MODELVIEW );
         gl.glLoadIdentity();
 
-        gl.glViewport( 0, 0, width, height );
+        gl.glViewport( 0, 0, width, height );        
     }
 
-    public static void render( GL2 gl, int width, int height) {
+    public static void render( GL2ES1 gl, int width, int height) {
         gl.glClear( GL.GL_COLOR_BUFFER_BIT );
 
         // draw a triangle filling the window
         gl.glLoadIdentity();
-        gl.glBegin( GL.GL_TRIANGLES );
-        gl.glColor3f( 1, 0, 0 );
-        gl.glVertex2f( 0, 0 );
-        gl.glColor3f( 0, 1, 0 );
-        gl.glVertex2f( width, 0 );
-        gl.glColor3f( 0, 0, 1 );
-        gl.glVertex2f( width / 2, height );
-        gl.glEnd();
+        
+        ImmModeSink immModeSink = ImmModeSink.createFixed(gl, GL.GL_STATIC_DRAW, 3, 
+                                              3, GL.GL_FLOAT,  // vertex
+                                              3, GL.GL_FLOAT,  // color
+                                              0, GL.GL_FLOAT,// normal
+                                              0, GL.GL_FLOAT); // texture
+        immModeSink.glBegin(GL.GL_TRIANGLES);
+        immModeSink.glColor3f( 1, 0, 0 );
+        immModeSink.glVertex2f( 0, 0 );
+        immModeSink.glColor3f( 0, 1, 0 );
+        immModeSink.glVertex2f( width, 0 );
+        immModeSink.glColor3f( 0, 0, 1 );
+        immModeSink.glVertex2f( width / 2, height );
+        immModeSink.glEnd(gl, true);
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestGearsES1NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestGearsES1NEWT.java
index 8b41141..dffe61f 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestGearsES1NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestGearsES1NEWT.java
@@ -47,19 +47,10 @@ import org.junit.AfterClass;
 import org.junit.Test;
 
 public class TestGearsES1NEWT extends UITestCase {
-    static GLProfile glp;
     static int width, height;
 
     @BeforeClass
     public static void initClass() {
-        /* if(GLProfile.isAvailable(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1)) {
-            // exact match
-            glp = GLProfile.get(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1);
-        } else */ {
-            // default device, somehow ES1 compatible
-            glp = GLProfile.getGL2ES1(); 
-        }
-        Assert.assertNotNull(glp);
         width  = 512;
         height = 512;
     }
@@ -115,7 +106,7 @@ public class TestGearsES1NEWT extends UITestCase {
 
     @Test
     public void test01() throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(glp);
+        GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES1());
         runTestGL(caps);
     }
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestRedSquareES1NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestRedSquareES1NEWT.java
index 13aafe4..c327a30 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestRedSquareES1NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es1/newt/TestRedSquareES1NEWT.java
@@ -47,19 +47,10 @@ import org.junit.AfterClass;
 import org.junit.Test;
 
 public class TestRedSquareES1NEWT extends UITestCase {
-    static GLProfile glp;
     static int width, height;
 
     @BeforeClass
     public static void initClass() {
-        /* if(GLProfile.isAvailable(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1)) {
-            // exact match
-            glp = GLProfile.get(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1);
-        } else */ {
-            // default device, somehow ES1 compatible
-            glp = GLProfile.getGL2ES1(); 
-        }
-        Assert.assertNotNull(glp);
         width  = 512;
         height = 512;
     }
@@ -115,7 +106,7 @@ public class TestRedSquareES1NEWT extends UITestCase {
 
     @Test
     public void test01() throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(glp);
+        GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES1());
         runTestGL(caps);
     }
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/ElektronenMultiplizierer.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/ElektronenMultiplizierer.java
index 52a98fd..cb3eb43 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/ElektronenMultiplizierer.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/ElektronenMultiplizierer.java
@@ -231,16 +231,15 @@ public class ElektronenMultiplizierer implements GLEventListener {
         gl.setSwapInterval(1);
 
         st = new ShaderState();        
-        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "default");
-        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "elektronenmultiplizierer_development");
-          //    "shader", "shader/bin", "elektronenmultiplizierer_port");
+        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
+                "shader/bin", "default", false);
+        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
+                "shader/bin", "elektronenmultiplizierer_development", false);
+          //    "shader", "shader/bin", "elektronenmultiplizierer_port", false);
         final ShaderProgram sp0 = new ShaderProgram();
         sp0.add(gl, vp0, System.err);
         sp0.add(gl, fp0, System.err);       
-        st.attachShaderProgram(gl, sp0);
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp0, true);
                 
         final float XRESf = (float) drawable.getWidth();
         final float YRESf = (float) drawable.getHeight();
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java
index 51bc7d1..de9a047 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/GearsES2.java
@@ -114,15 +114,14 @@ public class GearsES2 implements GLEventListener {
         
         st = new ShaderState();
         // st.setVerbose(true);
-        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "gears");
-        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "gears");
+        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
+                "shader/bin", "gears", false);
+        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
+                "shader/bin", "gears", false);
         final ShaderProgram sp0 = new ShaderProgram();
         sp0.add(gl, vp0, System.err);
         sp0.add(gl, fp0, System.err);
-        st.attachShaderProgram(gl, sp0);
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp0, true);
         // Use debug pipeline
         // drawable.setGL(new DebugGL(drawable.getGL()));
 
@@ -188,12 +187,18 @@ public class GearsES2 implements GLEventListener {
         System.err.println(Thread.currentThread()+" GearsES2.reshape "+x+"/"+y+" "+width+"x"+height+", swapInterval "+swapInterval);
         GL2ES2 gl = drawable.getGL().getGL2ES2();
 
-        float h = (float)height / (float)width;
-
         st.useProgram(gl, true);
         pmvMatrix.glMatrixMode(PMVMatrix.GL_PROJECTION);
         pmvMatrix.glLoadIdentity();
-        pmvMatrix.glFrustumf(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
+        
+        if(height>width) {
+            float h = (float)height / (float)width;
+            pmvMatrix.glFrustumf(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
+        } else {
+            float h = (float)width / (float)height;
+            pmvMatrix.glFrustumf(-h, h, -1.0f, 1.0f, 5.0f, 60.0f);
+        }
+
         pmvMatrix.glMatrixMode(PMVMatrix.GL_MODELVIEW);
         pmvMatrix.glLoadIdentity();
         pmvMatrix.glTranslatef(0.0f, 0.0f, -40.0f);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java
index d645fb9..a246625 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java
@@ -78,15 +78,14 @@ public class RedSquareES2 implements GLEventListener {
         
         st = new ShaderState();
         st.setVerbose(true);
-        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, this.getClass(),
-                "shader", "shader/bin", "RedSquareShader");
+        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
+                "shader/bin", "RedSquareShader", false);
         final ShaderProgram sp0 = new ShaderProgram();
         sp0.add(gl, vp0, System.err);
         sp0.add(gl, fp0, System.err);
-        st.attachShaderProgram(gl, sp0);
-        st.useProgram(gl, true);        
+        st.attachShaderProgram(gl, sp0, true);
         
         // setup mgl_PMVMatrix
         pmvMatrix = new PMVMatrix();
@@ -123,6 +122,8 @@ public class RedSquareES2 implements GLEventListener {
         gl.glEnable(GL2ES2.GL_DEPTH_TEST);
         st.useProgram(gl, false);        
 
+        gl.setSwapInterval(swapInterval);
+        
         if (glad instanceof GLWindow) {
             glWindow = (GLWindow) glad;
             glWindow.addMouseListener(myMouse);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TexCubeES2.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TexCubeES2.java
new file mode 100644
index 0000000..e85468b
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/TexCubeES2.java
@@ -0,0 +1,507 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+package com.jogamp.opengl.test.junit.jogl.demos.es2;
+
+import java.nio.ByteBuffer;
+import java.nio.FloatBuffer;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLES2;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.GLUniformData;
+import javax.media.opengl.fixedfunc.GLMatrixFunc;
+
+import com.jogamp.newt.Window;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.newt.event.MouseListener;
+import com.jogamp.newt.event.WindowAdapter;
+import com.jogamp.newt.event.WindowEvent;
+import com.jogamp.newt.opengl.GLWindow;
+import com.jogamp.opengl.JoglVersion;
+import com.jogamp.opengl.test.junit.jogl.demos.TestTextureSequence;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
+import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.GLArrayDataServer;
+import com.jogamp.opengl.util.PMVMatrix;
+import com.jogamp.opengl.util.glsl.ShaderCode;
+import com.jogamp.opengl.util.glsl.ShaderProgram;
+import com.jogamp.opengl.util.glsl.ShaderState;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureCoords;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+public class TexCubeES2 implements GLEventListener {
+    public TexCubeES2 (TextureSequence texSource, boolean innerCube, float zoom0, float rotx, float roty) {
+        this.texSeq = texSource;
+        this.innerCube = innerCube;
+        this.zoom0     = zoom0;
+        this.view_rotx = rotx;
+        this.view_roty = roty;
+    }
+
+    private TextureSequence texSeq;
+    private ShaderState st;
+    private PMVMatrix pmvMatrix;
+    private GLUniformData pmvMatrixUniform;
+    // private TextureCoords[] textureCoords = null;
+    private float nearPlaneNormalized;
+    // private float zoom0=-5.0f, zoom=zoom0;
+    // private float view_rotx = 20.0f, view_roty = 30.0f, view_rotz = 0.0f;
+    private float zoom0=-2.3f, zoom=zoom0;
+    private float view_rotx = 0.0f, view_roty = 0.0f, view_rotz = 0.0f;
+    int[] vboNames = new int[4];
+    boolean innerCube;
+    boolean initialized = false;
+    private ByteBuffer cubeIndices;
+        
+    private final MouseListener mouseAction = new MouseAdapter() {
+        int lx = 0;
+        int ly = 0;
+        boolean first = false;
+
+        public void mousePressed(MouseEvent e) {
+            first = true;  
+        }
+        public void mouseMoved(MouseEvent e) {          
+            first = false;
+        }
+        public void mouseDragged(MouseEvent e) {
+            int width, height;
+            Object source = e.getSource();
+            Window window = null;
+            if(source instanceof Window) {
+                window = (Window) source;
+                width=window.getWidth();
+                height=window.getHeight();
+            } else if (GLProfile.isAWTAvailable() && source instanceof java.awt.Component) {
+                java.awt.Component comp = (java.awt.Component) source;
+                width=comp.getWidth();
+                height=comp.getHeight();
+            } else {
+                throw new RuntimeException("Event source neither Window nor Component: "+source);
+            }           
+            if(e.getPointerCount()==2) {
+                // 2 pointers zoom ..
+                if(first) {
+                    lx = Math.abs(e.getY(0)-e.getY(1));
+                    first=false;
+                    return;
+                }
+                int nv = Math.abs(e.getY(0)-e.getY(1));
+                int dy = nv - lx;
+                
+                zoom += 40f*Math.signum(dy)/(float)height;
+                
+                lx = nv;
+            } else {
+                // 1 pointer rotate
+                if(first) {
+                    lx = e.getX();
+                    ly = e.getY();
+                    first=false;
+                    return;
+                }
+                int nx = e.getX();
+                int ny = e.getY();
+                view_roty += 360f * ( (float)( nx - lx ) / (float)width );
+                view_rotx += 360f * ( (float)( ny - ly ) / (float)height );
+                lx = nx;
+                ly = ny;
+            }
+        }        
+        public void mouseWheelMoved(MouseEvent e) {
+            zoom += e.getWheelRotation()/10f;
+            System.err.println("zoom: "+zoom);
+        }
+    };
+    
+    static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" };
+    static final String gl2_prelude = "#version 110\n";
+    static final String shaderBasename = "texsequence_xxx";
+    static final String myTextureLookupName = "myTexture2D";
+    
+    private void initShader(GL2ES2 gl) {
+        // Create & Compile the shader objects
+        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, TexCubeES2.class, 
+                                            "shader", "shader/bin", shaderBasename, true);
+        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, TexCubeES2.class, 
+                                            "shader", "shader/bin", shaderBasename, true);
+        
+        // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ]
+        int rsFpPos;
+        if(gl.isGLES2()) {
+            rsVp.insertShaderSource(0, 0, es2_prelude[0]);
+            rsFpPos = rsFp.insertShaderSource(0, 0, es2_prelude[0]);
+        } else {
+            rsVp.insertShaderSource(0, 0, gl2_prelude);
+            rsFpPos = rsFp.insertShaderSource(0, 0, gl2_prelude);
+        }
+        rsFpPos = rsFp.insertShaderSource(0, rsFpPos, texSeq.getRequiredExtensionsShaderStub());
+        if(gl.isGLES2()) {
+            rsFpPos = rsFp.insertShaderSource(0, rsFpPos, es2_prelude[1]);
+        }        
+        final String texLookupFuncName = texSeq.getTextureLookupFunctionName(myTextureLookupName);        
+        rsFp.replaceInShaderSource(myTextureLookupName, texLookupFuncName);
+        
+        // Inject TextureSequence shader details
+        final StringBuilder sFpIns = new StringBuilder();
+        sFpIns.append("uniform ").append(texSeq.getTextureSampler2DType()).append(" mgl_ActiveTexture;\n");
+        sFpIns.append(texSeq.getTextureLookupFragmentShaderImpl());
+        rsFp.insertShaderSource(0, "TEXTURE-SEQUENCE-CODE-BEGIN", 0, sFpIns);
+        
+        // Create & Link the shader program
+        ShaderProgram sp = new ShaderProgram();
+        sp.add(rsVp);
+        sp.add(rsFp);
+        if(!sp.link(gl, System.err)) {
+            throw new GLException("Couldn't link program: "+sp);
+        }
+
+        // Let's manage all our states using ShaderState.
+        st = new ShaderState();
+        st.attachShaderProgram(gl, sp, false);
+    }
+    
+    GLArrayDataServer interleavedVBO;
+    
+    public void init(GLAutoDrawable drawable) {
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+        System.err.println(JoglVersion.getGLInfo(gl, null));
+        final Texture tex= texSeq.getLastTexture().getTexture();
+        
+        final boolean useExternalTexture = GLES2.GL_TEXTURE_EXTERNAL_OES == tex.getTarget();
+        if(useExternalTexture && !gl.isExtensionAvailable("GL_OES_EGL_image_external")) {
+            throw new GLException("GL_OES_EGL_image_external requested but not available");
+        }
+        
+        initShader(gl);
+
+        // Push the 1st uniform down the path 
+        st.useProgram(gl, true);
+
+        pmvMatrix = new PMVMatrix();
+        reshapePMV(drawable.getWidth(), drawable.getHeight());
+        pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf());
+        if(!st.uniform(gl, pmvMatrixUniform)) {
+            throw new GLException("Error setting PMVMatrix in shader: "+st);
+        }
+        if(!st.uniform(gl, new GLUniformData("mgl_ActiveTexture", texSeq.getTextureUnit()))) {
+            throw new GLException("Error setting mgl_ActiveTexture in shader: "+st);
+        }
+        
+        
+        {
+            final float aspect = tex.getAspectRatio();
+            final TextureCoords tc = tex.getImageTexCoords();
+            System.err.println("XXX0: aspect: "+aspect);
+            System.err.println("XXX0: y-flip: "+tex.getMustFlipVertically());
+            System.err.println("XXX0: "+tc);
+            final float tc_x1 = Math.max(tc.left(), tc.right());
+            final float tc_y1 = Math.max(tc.bottom(), tc.top());
+            final float ss=1f, ts=aspect; // scale tex-coord
+            final float dy = ( 1f - aspect ) / 2f ;
+            for(int i=0; i<s_cubeTexCoords.length; i+=2) {
+                final float tx = s_cubeTexCoords[i+0];
+                final float ty = s_cubeTexCoords[i+1];
+                if(tx!=0) {
+                    s_cubeTexCoords[i+0] = tc_x1 * ss;
+                }
+                if(ty==0 && !tex.getMustFlipVertically() || ty!=0 && tex.getMustFlipVertically()) {
+                    s_cubeTexCoords[i+1] = 0f         + dy;
+                } else {
+                    s_cubeTexCoords[i+1] = tc_y1 * ts + dy;
+                }
+            }
+        }
+        
+        
+        interleavedVBO = GLArrayDataServer.createGLSLInterleaved(3+4+2, GL.GL_FLOAT, false, 3*6*4, GL.GL_STATIC_DRAW);
+        {        
+            interleavedVBO.addGLSLSubArray("mgl_Vertex",        3, GL.GL_ARRAY_BUFFER);            
+            interleavedVBO.addGLSLSubArray("mgl_Color",         4, GL.GL_ARRAY_BUFFER);            
+            //interleavedVBO.addGLSLSubArray("mgl_Normal",        3, GL.GL_ARRAY_BUFFER);
+            interleavedVBO.addGLSLSubArray("mgl_MultiTexCoord", 2, GL.GL_ARRAY_BUFFER);
+
+            FloatBuffer ib = (FloatBuffer)interleavedVBO.getBuffer();
+            
+            for(int i=0; i<6*4; i++) {
+                ib.put(s_cubeVertices,  i*3, 3);
+                ib.put(s_cubeColors,    i*4, 4);  
+                //ib.put(s_cubeNormals,   i*3, 3);
+                ib.put(s_cubeTexCoords, i*2, 2);
+            }                        
+        }
+        interleavedVBO.seal(gl, true);
+        interleavedVBO.enableBuffer(gl, false);
+        st.ownAttribute(interleavedVBO, true);
+        cubeIndices = ByteBuffer.wrap(s_cubeIndices);
+        
+        gl.glEnable(GL2ES2.GL_DEPTH_TEST);
+
+        st.useProgram(gl, false);
+
+        if (drawable instanceof Window) {
+            Window window = (Window) drawable;
+            window.addMouseListener(mouseAction);
+        }
+        
+        // Let's show the completed shader state ..
+        System.out.println("iVBO: "+interleavedVBO);
+        System.out.println(st);
+    }
+    
+    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+
+        gl.glViewport(0, 0, width, height);
+
+        if(innerCube) {
+            // Clear background to white
+            gl.glClearColor(1.0f, 1.0f, 1.0f, 0.4f);
+        } else {
+            // Clear background to blue
+            gl.glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
+        }
+
+        if(!innerCube) {
+            // lights on
+        } else {
+            // lights off
+        }
+        // gl.glEnable(GL.GL_CULL_FACE);
+        // gl.glDisable(GL.GL_DITHER);
+
+        if(null != st) {
+            reshapePMV(width, height);
+            st.useProgram(gl, true);
+            st.uniform(gl, pmvMatrixUniform);
+            st.useProgram(gl, false);
+        }
+    }
+    
+    
+    private void reshapePMV(int width, int height) {
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
+        pmvMatrix.glLoadIdentity();
+        if(!innerCube) {
+            pmvMatrix.gluPerspective(45.0f, (float)width / (float)height, 1f, 10.0f);
+            nearPlaneNormalized = 1f/(100f-1f);
+        } else {
+            pmvMatrix.glOrthof(-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 10.0f);
+            nearPlaneNormalized = 0f;
+        }
+        System.err.println("XXX0: Perspective nearPlaneNormalized: "+nearPlaneNormalized);
+
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
+        pmvMatrix.glLoadIdentity();
+        pmvMatrix.glTranslatef(0, 0, zoom0);
+    }
+
+
+    public void dispose(GLAutoDrawable drawable) {
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+
+        texSeq = null;        
+        pmvMatrixUniform = null;
+        pmvMatrix.destroy();
+        pmvMatrix=null;
+        st.destroy(gl);
+        st=null;
+    }
+
+    public void display(GLAutoDrawable drawable) {
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+
+        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
+
+        st.useProgram(gl, true);
+        
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
+        pmvMatrix.glLoadIdentity();
+        pmvMatrix.glTranslatef(0, 0, zoom);
+        pmvMatrix.glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
+        pmvMatrix.glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
+        pmvMatrix.glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
+        st.uniform(gl, pmvMatrixUniform);
+        interleavedVBO.enableBuffer(gl, true);
+        Texture tex = null;
+        if(null!=texSeq) {
+            final TextureSequence.TextureFrame texFrame = texSeq.getNextTexture(gl, true);
+            if(null != texFrame) {
+                tex = texFrame.getTexture();
+                gl.glActiveTexture(GL.GL_TEXTURE0+texSeq.getTextureUnit());
+                tex.enable(gl);
+                tex.bind(gl);                
+            }
+        }
+        gl.glDrawElements(GL.GL_TRIANGLES, 6 * 6, GL.GL_UNSIGNED_BYTE, cubeIndices);
+        if(null != tex) {
+            tex.disable(gl);                                
+        }
+        interleavedVBO.enableBuffer(gl, false);
+        st.useProgram(gl, false);        
+    }
+
+    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
+    }
+    
+    static final float[] light_position = { -50.f, 50.f, 50.f, 0.f };
+    static final float[] light_ambient = { 0.125f, 0.125f, 0.125f, 1.f };
+    static final float[] light_diffuse = { 1.0f, 1.0f, 1.0f, 1.f };
+    static final float[] material_spec = { 1.0f, 1.0f, 1.0f, 0.f };
+    static final float[] zero_vec4 = { 0.0f, 0.0f, 0.0f, 0.f };
+
+    private static final float[] s_cubeVertices = /* f b t b r l */
+        {
+            -1f,  1f,  1f,    1f, -1f,  1f,    1f,  1f,  1f,   -1f, -1f,  1f,
+            
+            -1f,  1f, -1f,    1f, -1f, -1f,    1f,  1f, -1f,   -1f, -1f, -1f,
+            
+            -1f, -1f,  1f,    1f, -1f, -1f,    1f, -1f,  1f,   -1f, -1f, -1f,
+            
+            -1f,  1f,  1f,    1f,  1f, -1f,    1f,  1f,  1f,   -1f,  1f, -1f,
+            
+             1f, -1f,  1f,    1f,  1f, -1f,    1f,  1f,  1f,    1f, -1f, -1f,
+            
+            -1f, -1f,  1f,   -1f,  1f, -1f,   -1f,  1f,  1f,   -1f, -1f, -1f
+        };
+    
+    private static final float[] s_cubeTexCoords =
+        { // LT       RB        RT       LB
+            0f, 1f,   1f, 0f,   1f, 1f,   0f, 0f,
+
+            0f, 1f,   1f, 0f,   1f, 1f,   0f, 0f,
+
+            0f, 1f,   1f, 0f,   1f, 1f,   0f, 0f,
+
+            0f, 1f,   1f, 0f,   1f, 1f,   0f, 0f,
+
+            0f, 0f,   1f, 1f,   0f, 1f,   1f, 0f,
+
+            0f, 0f,   1f, 1f,   0f, 1f,   1f, 0f,
+        };
+
+    private static final float[] s_cubeColors =
+        {
+            1f, 1f, 1f, 1f,     1f, 1f, 1f, 1f,            1f, 1f, 1f, 1f,     1f, 1f, 1f, 1f,
+            
+            40f/255f, 80f/255f, 160f/255f, 255f/255f,      40f/255f, 80f/255f, 160f/255f, 255f/255f,
+            40f/255f, 80f/255f, 160f/255f, 255f/255f,      40f/255f, 80f/255f, 160f/255f, 255f/255f,
+            
+            40f/255f, 80f/255f, 160f/255f, 255f/255f,      40f/255f, 80f/255f, 160f/255f, 255f/255f,
+            40f/255f, 80f/255f, 160f/255f, 255f/255f,      40f/255f, 80f/255f, 160f/255f, 255f/255f,            
+            
+            128f/255f, 128f/255f, 128f/255f, 255f/255f,   128f/255f, 128f/255f, 128f/255f, 255f/255f,
+            128f/255f, 128f/255f, 128f/255f, 255f/255f,   128f/255f, 128f/255f, 128f/255f, 255f/255f,
+            
+            255f/255f, 110f/255f, 10f/255f, 255f/255f,    255f/255f, 110f/255f, 10f/255f, 255f/255f,
+            255f/255f, 110f/255f, 10f/255f, 255f/255f,    255f/255f, 110f/255f, 10f/255f, 255f/255f,
+            
+            255f/255f, 70f/255f, 60f/255f, 255f/255f,     255f/255f, 70f/255f, 60f/255f, 255f/255f,
+            255f/255f, 70f/255f, 60f/255f, 255f/255f,     255f/255f, 70f/255f, 60f/255f, 255f/255f
+        };
+    
+    private static final float[] s_cubeNormals =
+        {
+             0f,  0f,  1f,    0f,  0f,  1f,    0f,  0f,  1f,    0f,  0f,  1f,
+            
+             0f,  0f, -1f,    0f,  0f, -1f,    0f,  0f, -1f,    0f,  0f, -1f,
+            
+             0f, -1f,  0f,    0f, -1f,  0f,    0f, -1f,  0f,    0f, -1f,  0f,
+            
+             0f,  1f,  0f,    0f,  1f,  0f,    0f,  1f,  0f,    0f,  1f,  0f,
+            
+             1f,  0f,  0f,    1f,  0f,  0f,    1f,  0f,  0f,    1f,  0f,  0f,
+            
+            -1f,  0f,  0f,   -1f,  0f,  0f,   -1f,  0f,  0f,   -1f,  0f,  0f
+        };
+    private static final byte[] s_cubeIndices =  
+        {
+             0,  3,  1,  2,  0,  1, /* front  */
+             6,  5,  4,  5,  7,  4, /* back   */
+             8, 11,  9, 10,  8,  9, /* top    */
+            15, 12, 13, 12, 14, 13, /* bottom */
+            16, 19, 17, 18, 16, 17, /* right  */
+            23, 20, 21, 20, 22, 21  /* left   */
+        };
+
+    public static void main(String[] args) {
+        int width = 510;
+        int height = 300;
+        boolean useBuildInTexLookup = false;
+        System.err.println("TexCubeES2.run()");
+
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-width")) {
+                i++;
+                width = MiscUtils.atoi(args[i], width);
+            } else if(args[i].equals("-height")) {
+                i++;
+                height = MiscUtils.atoi(args[i], height);
+            } else if(args[i].equals("-shaderBuildIn")) {
+                useBuildInTexLookup = true;
+            }
+        }
+        
+        final GLWindow window = GLWindow.create(new GLCapabilities(GLProfile.getGL2ES2()));
+        // Size OpenGL to Video Surface
+        window.setSize(width, height);
+        window.setFullscreen(false);
+        window.setSize(width, height);
+        final TestTextureSequence texSource = new TestTextureSequence(useBuildInTexLookup);
+        window.addGLEventListener(new GLEventListener() {
+            @Override
+            public void init(GLAutoDrawable drawable) {
+                texSource.initGLResources(drawable.getGL());
+            }
+            @Override
+            public void dispose(GLAutoDrawable drawable) { }
+            @Override
+            public void display(GLAutoDrawable drawable) { }
+            @Override
+            public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }            
+        });
+        window.addGLEventListener(new TexCubeES2(texSource, false, -2.3f, 0f, 0f));
+        window.setVisible(true);
+        final Animator anim = new Animator(window);
+        // anim.setUpdateFPSFrames(60, System.err);
+        anim.start();
+        window.addWindowListener(new WindowAdapter() {
+            public void windowDestroyed(WindowEvent e) {
+                anim.stop();
+            }                
+        });
+    }
+}
+
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java
new file mode 100755
index 0000000..bb0d841
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieCube.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ * 
+ * - Redistribution of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * 
+ * - Redistribution in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * 
+ * Neither the name of Sun Microsystems, Inc. or the names of
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ * 
+ * This software is provided "AS IS," without a warranty of any kind. ALL
+ * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
+ * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
+ * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
+ * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
+ * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
+ * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
+ * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
+ * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
+ * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
+ * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ * 
+ */
+
+package com.jogamp.opengl.test.junit.jogl.demos.es2.av;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+
+import com.jogamp.newt.Window;
+import com.jogamp.newt.event.KeyAdapter;
+import com.jogamp.newt.event.KeyEvent;
+import com.jogamp.newt.event.KeyListener;
+import com.jogamp.newt.event.WindowAdapter;
+import com.jogamp.newt.event.WindowEvent;
+import com.jogamp.newt.opengl.GLWindow;
+import com.jogamp.opengl.JoglVersion;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.TexCubeES2;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
+import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.av.GLMediaPlayer;
+import com.jogamp.opengl.util.av.GLMediaPlayer.GLMediaEventListener;
+import com.jogamp.opengl.util.av.GLMediaPlayerFactory;
+
+public class MovieCube implements GLEventListener, GLMediaEventListener {
+    static boolean waitForKey = false;
+    final URLConnection stream;
+    final float zoom0, rotx, roty;
+    TexCubeES2 cube=null;
+    GLMediaPlayer mPlayer=null;
+    
+    public MovieCube() throws IOException {
+        this(new URL("http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4").openConnection(), 
+             -2.3f, 0f, 0f);        
+    }
+    
+    public MovieCube(URLConnection stream, float zoom0, float rotx, float roty) throws IOException {
+        this.stream = stream;
+        this.zoom0 = zoom0;
+        this.rotx = rotx;
+        this.roty = roty;
+    }
+
+    private final KeyListener keyAction = new KeyAdapter() {
+        public void keyTyped(KeyEvent e)  {
+            System.err.println("MC "+e);
+            int pts0 = mPlayer.getCurrentPosition();
+            int pts1 = 0;
+            switch(e.getKeyCode()) {
+                case KeyEvent.VK_3:
+                case KeyEvent.VK_RIGHT:      pts1 = pts0 +  1000; break;
+                case KeyEvent.VK_4:
+                case KeyEvent.VK_UP:         pts1 = pts0 + 10000; break;
+                case KeyEvent.VK_2:
+                case KeyEvent.VK_LEFT:       pts1 = pts0 -  1000; break;
+                case KeyEvent.VK_1:
+                case KeyEvent.VK_DOWN:       pts1 = pts0 - 10000; break;
+                case KeyEvent.VK_ESCAPE:
+                case KeyEvent.VK_DELETE:
+                case KeyEvent.VK_BACK_SPACE: {
+                    mPlayer.seek(0);
+                    mPlayer.setPlaySpeed(1.0f);
+                    mPlayer.start();
+                    break;
+                }
+                case KeyEvent.VK_SPACE: {
+                    if(GLMediaPlayer.State.Paused == mPlayer.getState()) {
+                        mPlayer.start();
+                    } else {
+                        mPlayer.pause();
+                    }
+                    break;
+                }
+                case KeyEvent.VK_S: mPlayer.setPlaySpeed(mPlayer.getPlaySpeed()/2.0f); break;
+                case KeyEvent.VK_F: mPlayer.setPlaySpeed(mPlayer.getPlaySpeed()*2.0f); break;
+            }
+            
+            if( 0 != pts1 ) {
+                mPlayer.seek(pts1);
+            }
+        }        
+    };
+    
+    @Override
+    public void attributesChanges(GLMediaPlayer mp, int event_mask, long when) {
+        System.out.println("attributesChanges: "+mp+", 0x"+Integer.toHexString(event_mask)+", when "+when);        
+    }
+
+    @Override
+    public void newFrameAvailable(GLMediaPlayer mp, long when) {
+        // System.out.println("newFrameAvailable: "+mp+", when "+when);
+    }
+
+    public void init(GLAutoDrawable drawable) {
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+        System.err.println(JoglVersion.getGLInfo(gl, null));
+
+        mPlayer = GLMediaPlayerFactory.create();
+        mPlayer.addEventListener(this);
+        cube = new TexCubeES2(mPlayer, false, zoom0, rotx, roty);        
+        
+        if(waitForKey) {
+            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
+            System.err.println("Press enter to continue");
+            try {
+                System.err.println(stdin.readLine());
+            } catch (IOException e) { }
+        }
+        try {
+            System.out.println("p0 "+mPlayer);
+            mPlayer.initGLStream(gl, stream);
+            System.out.println("p1 "+mPlayer);
+        } catch (Exception e) { 
+            e.printStackTrace(); 
+            if(null != mPlayer) {
+                mPlayer.destroy(gl);
+                mPlayer = null;
+            }
+            throw new GLException(e);
+        }
+        
+        cube.init(drawable);
+        mPlayer.start();
+
+        boolean added;
+        if (drawable instanceof Window) {
+            Window window = (Window) drawable;
+            window.addKeyListener(keyAction);
+            added = true;
+        } else { added = false; }       
+        System.err.println("MC.init: kl-added "+added+", "+drawable.getClass().getName());
+    }
+
+    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
+        if(null == mPlayer) { return; }
+        cube.reshape(drawable, x, y, width, height);
+    }
+
+    public void dispose(GLAutoDrawable drawable) {
+        System.err.println(Thread.currentThread()+" MovieCube.dispose ... ");
+        if(null == mPlayer) { return; }
+        mPlayer.stop();
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+        mPlayer.destroy(gl);
+        mPlayer=null;
+        cube.dispose(drawable);
+        cube=null;
+    }
+
+    public void display(GLAutoDrawable drawable) {
+        if(null == mPlayer) { return; }
+        cube.display(drawable);
+    }
+
+    public void displayChanged(javax.media.opengl.GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
+    }
+    
+    public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {
+        int width = 510;
+        int height = 300;
+        System.err.println("TexCubeES2.run()");
+
+        String url_s="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";        
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-width")) {
+                i++;
+                width = MiscUtils.atoi(args[i], width);
+            } else if(args[i].equals("-height")) {
+                i++;
+                height = MiscUtils.atoi(args[i], height);
+            } else if(args[i].equals("-url")) {
+                i++;
+                url_s = args[i];
+            } else if(args[i].equals("-wait")) {
+                waitForKey = true;
+            }
+        }
+        final MovieCube mc = new MovieCube(new URL(url_s).openConnection(), -2.3f, 0f, 0f);
+        
+        final GLWindow window = GLWindow.create(new GLCapabilities(GLProfile.getGL2ES2()));
+        // Size OpenGL to Video Surface
+        window.setSize(width, height);
+        window.setFullscreen(false);
+        window.setSize(width, height);
+        window.addGLEventListener(mc);
+        final Animator anim = new Animator(window);
+        window.addWindowListener(new WindowAdapter() {
+            public void windowDestroyed(WindowEvent e) {
+                anim.stop();
+            }                
+        });
+        // anim.setUpdateFPSFrames(60, System.err);
+        anim.start();
+        window.setVisible(true);
+    }
+}
+
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java
new file mode 100755
index 0000000..8210065
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/av/MovieSimple.java
@@ -0,0 +1,559 @@
+/**
+ * Copyright 2012 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+
+package com.jogamp.opengl.test.junit.jogl.demos.es2.av;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.FloatBuffer;
+
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES2;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLES2;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLException;
+import javax.media.opengl.GLProfile;
+import javax.media.opengl.GLUniformData;
+import javax.media.opengl.fixedfunc.GLMatrixFunc;
+
+import com.jogamp.newt.Window;
+import com.jogamp.newt.event.MouseAdapter;
+import com.jogamp.newt.event.MouseEvent;
+import com.jogamp.newt.event.MouseListener;
+import com.jogamp.newt.event.WindowAdapter;
+import com.jogamp.newt.event.WindowEvent;
+import com.jogamp.newt.opengl.GLWindow;
+import com.jogamp.opengl.JoglVersion;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
+import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.GLArrayDataServer;
+import com.jogamp.opengl.util.PMVMatrix;
+import com.jogamp.opengl.util.av.GLMediaPlayer;
+import com.jogamp.opengl.util.av.GLMediaPlayer.GLMediaEventListener;
+import com.jogamp.opengl.util.av.GLMediaPlayerFactory;
+import com.jogamp.opengl.util.glsl.ShaderCode;
+import com.jogamp.opengl.util.glsl.ShaderProgram;
+import com.jogamp.opengl.util.glsl.ShaderState;
+import com.jogamp.opengl.util.texture.Texture;
+import com.jogamp.opengl.util.texture.TextureCoords;
+import com.jogamp.opengl.util.texture.TextureSequence;
+
+public class MovieSimple implements GLEventListener, GLMediaEventListener {
+    private int winWidth, winHeight;
+    private int prevMouseX; // , prevMouseY;
+    private int rotate = 0;
+    private boolean  orthoProjection = true;
+    private float nearPlaneNormalized;
+    private float zoom0;
+    private float zoom1;
+    private float zoom;
+    private long startTime;
+    private int effects = EFFECT_NORMAL;
+    private float alpha = 1.0f;
+
+    public static final int EFFECT_NORMAL                  =    0;
+    public static final int EFFECT_GRADIENT_BOTTOM2TOP     = 1<<1;
+    public static final int EFFECT_TRANSPARENT             = 1<<3; 
+
+    /** defaults to true */
+    public void setOrthoProjection(boolean v) { orthoProjection=v; }
+    public boolean getOrthoProjection() { return orthoProjection; }
+    
+    public boolean hasEffect(int e) { return 0 != ( effects & e ) ; }
+    public void setEffects(int e) { effects = e; };
+    public void setTransparency(float alpha) {
+        this.effects |= EFFECT_TRANSPARENT;
+        this.alpha = alpha;
+    }    
+
+    GLMediaPlayer mPlayer;
+    URLConnection stream = null;
+    boolean mPlayerExternal;
+    boolean mPlayerShared;
+    boolean mPlayerScaleOrig;
+    GLArrayDataServer interleavedVBO;
+
+    private final MouseListener mouseAction = new MouseAdapter() {
+        public void mousePressed(MouseEvent e) {
+            if(e.getY()<=winHeight/2 && null!=mPlayer && 1 == e.getClickCount()) {
+                if(GLMediaPlayer.State.Playing == mPlayer.getState()) {
+                    mPlayer.pause();
+                } else {
+                    mPlayer.start();
+                }
+            }
+        }
+        public void mouseReleased(MouseEvent e) {
+            if(e.getY()<=winHeight/2) {
+                rotate = -1;
+                zoom = zoom0;
+                System.err.println("zoom: "+zoom);
+            }
+        }
+        public void mouseMoved(MouseEvent e) {
+            prevMouseX = e.getX();
+            // prevMouseY = e.getY();
+        }
+        public void mouseDragged(MouseEvent e) {
+            int x = e.getX();
+            int y = e.getY();
+            
+            if(y>winHeight/2) {
+                final float dp  = (float)(x-prevMouseX)/(float)winWidth;
+                mPlayer.seek(mPlayer.getCurrentPosition() + (int) (mPlayer.getDuration() * dp));                
+            } else {
+                mPlayer.start();
+                rotate = 1;                
+                zoom = zoom1;
+            }
+            
+            prevMouseX = x;
+            // prevMouseY = y;
+        }
+        public void mouseWheelMoved(MouseEvent e) {
+            zoom += e.getWheelRotation()/10f;
+            System.err.println("zoom: "+zoom);
+        }
+    };
+    
+    public MovieSimple(URLConnection stream) throws IOException {
+        mPlayerScaleOrig = false;
+        mPlayerShared = false;
+        mPlayerExternal = false;
+        mPlayer = GLMediaPlayerFactory.create();
+        mPlayer.addEventListener(this);
+        this.stream = stream;
+        System.out.println("pC.1 "+mPlayer);
+    }
+
+    public MovieSimple(GLMediaPlayer sharedMediaPlayer) throws IllegalStateException {
+        mPlayerScaleOrig = false;
+        mPlayerShared = true;
+        mPlayerExternal = true;
+        mPlayer = sharedMediaPlayer;
+        mPlayer.addEventListener(this);
+        this.stream = null;
+        System.out.println("pC.2 shared "+mPlayerShared+", "+mPlayer);
+    }
+    
+    public GLMediaPlayer getGLMediaPlayer() { return mPlayer; }
+    
+    public void setScaleOrig(boolean v) {
+        mPlayerScaleOrig = v;
+    }
+    
+    @Override
+    public void attributesChanges(GLMediaPlayer mp, int event_mask, long when) {
+        System.out.println("attributesChanges: "+mp+", 0x"+Integer.toHexString(event_mask)+", when "+when);        
+    }
+
+    @Override
+    public void newFrameAvailable(GLMediaPlayer mp, long when) {
+        // System.out.println("newFrameAvailable: "+mp+", when "+when);        
+    }
+
+    public void start() {
+        if(null!=mPlayer) {
+            mPlayer.start();
+            System.out.println("pStart "+mPlayer);
+        }        
+    }
+
+    public void stop() {
+        if(null!=mPlayer) {
+            mPlayer.stop();
+            System.out.println("pStop "+mPlayer);
+        }        
+    }
+    
+    ShaderState st;
+    PMVMatrix pmvMatrix;
+    GLUniformData pmvMatrixUniform;
+    static final String[] es2_prelude = { "#version 100\n", "precision mediump float;\n" };
+    static final String gl2_prelude = "#version 110\n";
+    static final String shaderBasename = "texsequence_xxx";
+    static final String myTextureLookupName = "myTexture2D";
+    
+    private void initShader(GL2ES2 gl) {
+        // Create & Compile the shader objects
+        ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, MovieSimple.class, 
+                                            "../shader", "../shader/bin", shaderBasename, true);
+        ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, MovieSimple.class, 
+                                            "../shader", "../shader/bin", shaderBasename, true);
+
+        // Prelude shader code w/ GLSL profile specifics [ 1. pre-proc, 2. other ]
+        int rsFpPos;
+        if(gl.isGLES2()) {
+            rsVp.insertShaderSource(0, 0, es2_prelude[0]);
+            rsFpPos = rsFp.insertShaderSource(0, 0, es2_prelude[0]);
+        } else {
+            rsVp.insertShaderSource(0, 0, gl2_prelude);
+            rsFpPos = rsFp.insertShaderSource(0, 0, gl2_prelude);
+        }
+        rsFpPos = rsFp.insertShaderSource(0, rsFpPos, mPlayer.getRequiredExtensionsShaderStub());
+        if(gl.isGLES2()) {
+            rsFpPos = rsFp.insertShaderSource(0, rsFpPos, es2_prelude[1]);
+        }
+        final String texLookupFuncName = mPlayer.getTextureLookupFunctionName(myTextureLookupName);        
+        rsFp.replaceInShaderSource(myTextureLookupName, texLookupFuncName);
+        
+        // Inject TextureSequence shader details
+        final StringBuilder sFpIns = new StringBuilder();
+        sFpIns.append("uniform ").append(mPlayer.getTextureSampler2DType()).append(" mgl_ActiveTexture;\n");
+        sFpIns.append(mPlayer.getTextureLookupFragmentShaderImpl());
+        rsFp.insertShaderSource(0, "TEXTURE-SEQUENCE-CODE-BEGIN", 0, sFpIns);
+
+        // Create & Link the shader program
+        ShaderProgram sp = new ShaderProgram();
+        sp.add(rsVp);
+        sp.add(rsFp);
+        if(!sp.link(gl, System.err)) {
+            throw new GLException("Couldn't link program: "+sp);
+        }
+
+        // Let's manage all our states using ShaderState.
+        st = new ShaderState();
+        st.attachShaderProgram(gl, sp, false);
+    }
+
+    public void init(GLAutoDrawable drawable) {
+        zoom0 =  orthoProjection ? 0f : -2.5f;
+        zoom1 = orthoProjection ? 0f : -5f;
+        zoom = zoom0;        
+
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+        System.err.println(JoglVersion.getGLInfo(gl, null));
+        System.err.println("Alpha: "+alpha+", opaque "+drawable.getChosenGLCapabilities().isBackgroundOpaque()+
+                           ", "+drawable.getClass().getName()+", "+drawable);
+        
+        final Texture tex;
+        boolean useExternalTexture = false;
+        try {
+            System.out.println("p0 "+mPlayer+", shared "+mPlayerShared);
+            if(!mPlayerShared) {
+                mPlayer.initGLStream(gl, stream);
+            }
+            tex = mPlayer.getLastTexture().getTexture();
+            System.out.println("p1 "+mPlayer+", shared "+mPlayerShared);
+            useExternalTexture = GLES2.GL_TEXTURE_EXTERNAL_OES == tex.getTarget();
+            if(useExternalTexture && !gl.isExtensionAvailable("GL_OES_EGL_image_external")) {
+                throw new GLException("GL_OES_EGL_image_external requested but not available");
+            }
+            if(!mPlayerShared) {
+                mPlayer.setTextureMinMagFilter( new int[] { GL.GL_NEAREST, GL.GL_LINEAR } );
+            }
+        } catch (Exception glex) { 
+            if(!mPlayerShared && null != mPlayer) {
+                mPlayer.destroy(gl);
+                mPlayer = null;
+            }
+            throw new GLException(glex);
+        }
+        
+        initShader(gl);
+
+        // Push the 1st uniform down the path 
+        st.useProgram(gl, true);
+
+        int[] viewPort = new int[] { 0, 0, drawable.getWidth(), drawable.getHeight()};
+        pmvMatrix = new PMVMatrix();
+        reshapePMV(viewPort[2], viewPort[3]);        
+        pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf());
+        if(!st.uniform(gl, pmvMatrixUniform)) {
+            throw new GLException("Error setting PMVMatrix in shader: "+st);
+        }
+        if(!st.uniform(gl, new GLUniformData("mgl_ActiveTexture", mPlayer.getTextureUnit()))) {
+            throw new GLException("Error setting mgl_ActiveTexture in shader: "+st);
+        }
+        
+        float dWidth = drawable.getWidth();
+        float dHeight = drawable.getHeight();
+        float mWidth = mPlayer.getWidth();
+        float mHeight = mPlayer.getHeight();        
+        float mAspect = mWidth/mHeight;
+        System.err.println("XXX0: mov aspect: "+mAspect);
+        float[] verts;
+        float xs, ys;
+        if(orthoProjection) {
+            if(mPlayerScaleOrig && mWidth < dWidth && mHeight < dHeight) {
+                xs   = mWidth/2f;                ys   = xs / mAspect;                                
+            } else {
+                xs   = dWidth/2f;                ys   = xs / mAspect; // w>h
+            }
+        } else {
+            if(mPlayerScaleOrig && mWidth < dWidth && mHeight < dHeight) {
+                xs   = mAspect * ( mWidth / dWidth ) ; ys   =  xs / mAspect ;
+            } else {
+                xs   = mAspect; ys   = 1f; // b>h
+            }
+        }
+        verts = new float[] { -1f*xs, -1f*ys, 0f, // LB
+                               1f*xs,  1f*ys, 0f  // RT
+                            };
+        {
+            System.err.println("XXX0: pixel  LB: "+verts[0]+", "+verts[1]+", "+verts[2]);
+            System.err.println("XXX0: pixel  RT: "+verts[3]+", "+verts[4]+", "+verts[5]);
+            float[] winLB = new float[3];
+            float[] winRT = new float[3];
+            pmvMatrix.gluProject(verts[0], verts[1], verts[2], viewPort, 0, winLB, 0);
+            pmvMatrix.gluProject(verts[3], verts[4], verts[5], viewPort, 0, winRT, 0);
+            System.err.println("XXX0: win   LB: "+winLB[0]+", "+winLB[1]+", "+winLB[2]);
+            System.err.println("XXX0: win   RT: "+winRT[0]+", "+winRT[1]+", "+winRT[2]);
+        }
+        final float ss = 1f, ts = 1f; // scale tex-coord
+
+        interleavedVBO = GLArrayDataServer.createGLSLInterleaved(3+4+2, GL.GL_FLOAT, false, 3*4, GL.GL_STATIC_DRAW);
+        {        
+            interleavedVBO.addGLSLSubArray("mgl_Vertex",        3, GL.GL_ARRAY_BUFFER);            
+            interleavedVBO.addGLSLSubArray("mgl_Color",         4, GL.GL_ARRAY_BUFFER);            
+            interleavedVBO.addGLSLSubArray("mgl_MultiTexCoord", 2, GL.GL_ARRAY_BUFFER);
+            
+            final FloatBuffer ib = (FloatBuffer)interleavedVBO.getBuffer();
+            final TextureCoords tc = tex.getImageTexCoords();                                   
+            final float aspect = tex.getAspectRatio();
+            System.err.println("XXX0: tex aspect: "+aspect);
+            System.err.println("XXX0: tex y-flip: "+tex.getMustFlipVertically());
+            System.err.println("XXX0: "+tex.getImageTexCoords());
+            
+             // left-bottom
+            ib.put(verts[0]);  ib.put(verts[1]);  ib.put(verts[2]);
+            if( hasEffect(EFFECT_GRADIENT_BOTTOM2TOP) ) {
+                ib.put( 0);    ib.put( 0);     ib.put( 0);    ib.put(alpha);
+            } else {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            }
+            ib.put( tc.left()   *ss);  ib.put( tc.bottom() *ts);
+            
+             // right-bottom
+            ib.put(verts[3]);  ib.put(verts[1]);  ib.put(verts[2]);
+            if( hasEffect(EFFECT_GRADIENT_BOTTOM2TOP) ) {
+                ib.put( 0);    ib.put( 0);     ib.put( 0);    ib.put(alpha); 
+            } else {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            }
+            ib.put( tc.right()  *ss);  ib.put( tc.bottom() *ts);
+
+             // left-top
+            ib.put(verts[0]);  ib.put(verts[4]);  ib.put(verts[2]);
+            if( hasEffect(EFFECT_GRADIENT_BOTTOM2TOP) ) {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            } else {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            }
+            ib.put( tc.left()   *ss);  ib.put( tc.top()    *ts);
+            
+             // right-top
+            ib.put(verts[3]);  ib.put(verts[4]);  ib.put(verts[2]);
+            if( hasEffect(EFFECT_GRADIENT_BOTTOM2TOP) ) {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            } else {
+                ib.put( 1);    ib.put( 1);     ib.put( 1);    ib.put(alpha);
+            } 
+            ib.put( tc.right()  *ss);  ib.put( tc.top()    *ts);            
+        }
+        interleavedVBO.seal(gl, true);
+        interleavedVBO.enableBuffer(gl, false);
+        st.ownAttribute(interleavedVBO, true);
+        gl.glClearColor(0.3f, 0.3f, 0.3f, 0.3f);
+        
+        gl.glEnable(GL2ES2.GL_DEPTH_TEST);
+
+        st.useProgram(gl, false);
+
+        // Let's show the completed shader state ..
+        System.out.println("iVBO: "+interleavedVBO);
+        System.out.println(st);
+
+        if(null!=mPlayer) {
+            start();
+            System.out.println("p2 "+mPlayer);
+        }
+        
+        startTime = System.currentTimeMillis();
+        
+        if (drawable instanceof Window) {
+            Window window = (Window) drawable;
+            window.addMouseListener(mouseAction);
+            winWidth = window.getWidth();
+            winHeight = window.getHeight();
+        }
+    }
+    
+    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
+        if(null == mPlayer) { return; }
+        winWidth = width;
+        winHeight = height;
+                
+        if(null != st) {
+            reshapePMV(width, height);
+            GL2ES2 gl = drawable.getGL().getGL2ES2();
+            st.useProgram(gl, true);
+            st.uniform(gl, pmvMatrixUniform);
+            st.useProgram(gl, false);
+        }
+        
+        System.out.println("pR "+mPlayer);
+    }
+    
+    private void reshapePMV(int width, int height) {
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
+        pmvMatrix.glLoadIdentity();
+        if(orthoProjection) {
+            final float fw = (float) width / 2f;
+            final float fh = (float) height/ 2f;
+            pmvMatrix.glOrthof(-fw, fw, -fh, fh, -1.0f, 1.0f);
+            nearPlaneNormalized = 0f;
+        } else {
+            pmvMatrix.gluPerspective(45.0f, (float)width / (float)height, 1f, 10.0f);
+            nearPlaneNormalized = 1f/(10f-1f);
+        }
+        System.err.println("XXX0: Perspective nearPlaneNormalized: "+nearPlaneNormalized);
+
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
+        pmvMatrix.glLoadIdentity();
+        pmvMatrix.glTranslatef(0, 0, zoom0);        
+    }
+
+    public void dispose(GLAutoDrawable drawable) {
+        if(null == mPlayer) { return; }
+        
+        stop();
+        System.out.println("pD.1 "+mPlayer);
+        
+        GL2ES2 gl = drawable.getGL().getGL2ES2();
+
+        mPlayer.removeEventListener(this);
+        if(!mPlayerExternal) {
+            mPlayer.destroy(gl);
+        }
+        System.out.println("pD.X "+mPlayer);
+        mPlayer=null;
+        pmvMatrixUniform = null;
+        pmvMatrix.destroy();
+        pmvMatrix=null;
+        st.destroy(gl);
+        st=null;
+    }
+
+    public void display(GLAutoDrawable drawable) {
+        if(null == mPlayer) { return; }
+        
+        GL2ES2 gl = drawable.getGL().getGL2ES2();        
+
+        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
+
+        st.useProgram(gl, true);
+
+        pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
+        pmvMatrix.glLoadIdentity();
+        pmvMatrix.glTranslatef(0, 0, zoom);
+        if(rotate > 0) {
+            final float ang = ((float) (System.currentTimeMillis() - startTime) * 360.0f) / 8000.0f;
+            pmvMatrix.glRotatef(ang, 0, 0, 1);
+        } else {
+            rotate = 0;
+        }
+        st.uniform(gl, pmvMatrixUniform);
+        interleavedVBO.enableBuffer(gl, true);
+        Texture tex = null; 
+        if(null!=mPlayer) {
+            final TextureSequence.TextureFrame texFrame;
+            if(mPlayerShared) {
+                texFrame=mPlayer.getLastTexture();
+            } else {
+                texFrame=mPlayer.getNextTexture(gl, true);
+            }
+            if(null != texFrame) {
+                tex = texFrame.getTexture();
+                gl.glActiveTexture(GL.GL_TEXTURE0+mPlayer.getTextureUnit());
+                tex.enable(gl);
+                tex.bind(gl);
+            }
+        }
+        gl.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4);
+        if(null != tex) {
+            tex.disable(gl);
+        }
+        interleavedVBO.enableBuffer(gl, false);
+        st.useProgram(gl, false);
+    }
+
+    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
+    }
+
+    public static void main(String[] args) throws IOException, MalformedURLException {
+        int width = 640;
+        int height = 600;
+        boolean ortho = true;
+        boolean zoom = false;
+        
+        String url_s="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";        
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-width")) {
+                i++;
+                width = MiscUtils.atoi(args[i], width);
+            } else if(args[i].equals("-height")) {
+                i++;
+                height = MiscUtils.atoi(args[i], height);
+            } else if(args[i].equals("-projection")) {
+                ortho=false;
+            } else if(args[i].equals("-zoom")) {
+                zoom=true;
+            } else if(args[i].equals("-url")) {
+                i++;
+                url_s = args[i];
+            }
+        }
+        final MovieSimple ms = new MovieSimple(new URL(url_s).openConnection());
+        ms.setScaleOrig(!zoom);
+        ms.setOrthoProjection(ortho);
+        
+        try {
+            GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2());
+            GLWindow window = GLWindow.create(caps);            
+
+            window.addGLEventListener(ms);
+
+            window.setSize(width, height);
+            window.setVisible(true);
+            final Animator anim = new Animator(window);
+            anim.start();
+            window.addWindowListener(new WindowAdapter() {
+                public void windowDestroyed(WindowEvent e) {
+                    anim.stop();
+                }                
+            });
+        } catch (Throwable t) {
+            t.printStackTrace();
+        }
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java
similarity index 68%
copy from src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java
copy to src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java
index 4b670f0..c6e2245 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/awt/TestGearsES2AWT.java
@@ -26,7 +26,7 @@
  * or implied, of JogAmp Community.
  */
  
-package com.jogamp.opengl.test.junit.jogl.demos.gl2.awt;
+package com.jogamp.opengl.test.junit.jogl.demos.es2.awt;
 
 import javax.media.opengl.*;
 
@@ -37,7 +37,8 @@ import com.jogamp.newt.event.awt.AWTWindowAdapter;
 import com.jogamp.newt.event.TraceKeyAdapter;
 import com.jogamp.newt.event.TraceWindowAdapter;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.util.QuitAdapter;
 import java.awt.Frame;
@@ -51,18 +52,16 @@ import org.junit.BeforeClass;
 import org.junit.AfterClass;
 import org.junit.Test;
 
-public class TestGearsAWTAnalyzeBug455 extends UITestCase {
-    static long duration = 500; // ms
-    static boolean waitForKey = false; // for manual profiling
-    static boolean altSwap = true;     // using alternate GL swap method (copy pixel) no [auto-]swap
-
-    static GLProfile glp;
+public class TestGearsES2AWT extends UITestCase {
     static int width, height;
+    static boolean firstUIActionOnProcess = false;
+    static boolean forceES2 = false;
+    static boolean shallUseOffscreenLayer = false;
+    static int swapInterval = 1;
+    static boolean showFPS = false;    
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
         width  = 512;
         height = 512;
     }
@@ -71,40 +70,18 @@ public class TestGearsAWTAnalyzeBug455 extends UITestCase {
     public static void releaseClass() {
     }
 
-    static class Swapper implements GLEventListener {
-        public void init(GLAutoDrawable drawable) {
-            System.err.println("auto-swap: "+drawable.getAutoSwapBufferMode());
-        }
-        public void dispose(GLAutoDrawable drawable) {
-        }
-        public void display(GLAutoDrawable drawable) {
-            if(!drawable.getAutoSwapBufferMode()) {
-                GL2 gl = drawable.getGL().getGL2();
-                // copy the colored content of the back buffer into the front buffer
-                // gl.glPushAttrib(GL.GL_COLOR_BUFFER_BIT);
-                gl.glReadBuffer(GL.GL_BACK);  // def. in dbl buff mode: GL_BACK
-                gl.glDrawBuffer(GL.GL_FRONT); // def. in dbl buff mode: GL_BACK
-                gl.glCopyPixels(0, 0, drawable.getWidth(), drawable.getHeight(), GL2.GL_COLOR);
-                // gl.glPopAttrib();
-                gl.glDrawBuffer(GL.GL_BACK); // def. in dbl buff mode: GL_BACK
-            }            
-        }
-        public void reshape(GLAutoDrawable drawable, int x, int y, int width,
-                int height) {
-        }        
-    }
     protected void runTestGL(GLCapabilities caps) throws InterruptedException, InvocationTargetException {
-        final Frame frame = new Frame("Gears AWT Test");
+        final Frame frame = new Frame("GearsES2 AWT Test");
         Assert.assertNotNull(frame);
 
         final GLCanvas glCanvas = new GLCanvas(caps);
         Assert.assertNotNull(glCanvas);
-        glCanvas.setAutoSwapBufferMode(!altSwap);
+        glCanvas.setShallUseOffscreenLayer(shallUseOffscreenLayer);
         frame.add(glCanvas);
         frame.setSize(512, 512);
+        frame.setTitle("Gears AWT Test (translucent "+!caps.isBackgroundOpaque()+"), swapInterval "+swapInterval);
 
-        glCanvas.addGLEventListener(new Gears(0));
-        glCanvas.addGLEventListener(new Swapper());
+        glCanvas.addGLEventListener(new GearsES2(swapInterval));
 
         Animator animator = new Animator(glCanvas);
         QuitAdapter quitAdapter = new QuitAdapter();
@@ -116,7 +93,7 @@ public class TestGearsAWTAnalyzeBug455 extends UITestCase {
             public void run() {
                 frame.setVisible(true);
             }});
-        animator.setUpdateFPSFrames(60, System.err);        
+        animator.setUpdateFPSFrames(60, System.err);
         animator.start();
 
         while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()<duration) {
@@ -140,25 +117,40 @@ public class TestGearsAWTAnalyzeBug455 extends UITestCase {
 
     @Test
     public void test01() throws InterruptedException, InvocationTargetException {
-        GLCapabilities caps = new GLCapabilities(glp);
-        caps.setDoubleBuffered(true); // code assumes dbl buffer setup
+        GLCapabilities caps = new GLCapabilities(forceES2 ? GLProfile.get(GLProfile.GLES2) : GLProfile.getGL2ES2());        
         runTestGL(caps);
     }
 
+    static long duration = 500; // ms
+
     public static void main(String args[]) {
+        boolean waitForKey = false;
+        
         for(int i=0; i<args.length; i++) {
             if(args[i].equals("-time")) {
                 i++;
                 try {
                     duration = Integer.parseInt(args[i]);
                 } catch (Exception ex) { ex.printStackTrace(); }
+            } else if(args[i].equals("-es2")) {
+                forceES2 = true;
+            } else if(args[i].equals("-vsync")) {
+                i++;
+                swapInterval = MiscUtils.atoi(args[i], swapInterval);
+            } else if(args[i].equals("-layered")) {
+                shallUseOffscreenLayer = true;
+            } else if(args[i].equals("-showFPS")) {
+                showFPS = true;
+            } else if(args[i].equals("-firstUIAction")) {
+                firstUIActionOnProcess = true;
             } else if(args[i].equals("-wait")) {
                 waitForKey = true;
-            } else if(args[i].equals("-autoswap")) {
-                altSwap = false;
             }
         }
-        System.err.println("altSwap "+altSwap);
+        System.err.println("forceES2 "+forceES2);
+        System.err.println("swapInterval "+swapInterval);
+        System.err.println("shallUseOffscreenLayer "+shallUseOffscreenLayer);
+        
         if(waitForKey) {
             BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
             System.err.println("Press enter to continue");
@@ -166,6 +158,6 @@ public class TestGearsAWTAnalyzeBug455 extends UITestCase {
                 System.err.println(stdin.readLine());
             } catch (IOException e) { }
         }
-        org.junit.runner.JUnitCore.main(TestGearsAWTAnalyzeBug455.class.getName());
+        org.junit.runner.JUnitCore.main(TestGearsES2AWT.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestElektronenMultipliziererNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestElektronenMultipliziererNEWT.java
index fb63590..ed308bd 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestElektronenMultipliziererNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestElektronenMultipliziererNEWT.java
@@ -28,6 +28,7 @@
  
 package com.jogamp.opengl.test.junit.jogl.demos.es2.newt;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.event.KeyAdapter;
 import com.jogamp.newt.event.KeyEvent;
 import com.jogamp.newt.event.TraceWindowAdapter;
@@ -65,10 +66,16 @@ public class TestElektronenMultipliziererNEWT extends UITestCase {
     static int startFrame = 1700;
     static long duration = 5000; // ms
     
-    @AfterClass
-    public static void releaseClass() {
+    @BeforeClass
+    public static void initClass() {
+        GLProfile glp = GLProfile.getDefault();
+        if( ! ( glp.isHardwareRasterizer() && glp.isGL2GL3() ) ) {
+            // Sorry .. mobile is too slow for this one.
+            setTestSupported(false);
+            return;
+        }
     }
-
+    
     protected void run() throws InterruptedException {
         final ElektronenMultiplizierer demo = new ElektronenMultiplizierer(
                 tRoutineClassName,
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java
index e57b26f..3fe0706 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestGearsES2NEWT.java
@@ -32,9 +32,16 @@ import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 
+import com.jogamp.newt.Display;
+import com.jogamp.newt.NewtFactory;
+import com.jogamp.newt.Screen;
 import com.jogamp.newt.event.KeyAdapter;
 import com.jogamp.newt.event.KeyEvent;
+import com.jogamp.newt.event.WindowEvent;
+import com.jogamp.newt.event.WindowAdapter;
 import com.jogamp.newt.opengl.GLWindow;
+import com.jogamp.opengl.test.junit.util.AWTRobotUtil;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.util.QuitAdapter;
 
@@ -42,9 +49,15 @@ import com.jogamp.opengl.util.Animator;
 
 import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 
+import javax.media.nativewindow.util.Dimension;
+import javax.media.nativewindow.util.Point;
+import javax.media.nativewindow.util.PointImmutable;
+import javax.media.nativewindow.util.DimensionImmutable;
+
 import javax.media.opengl.GLAnimatorControl;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesImmutable;
 import javax.media.opengl.GLEventListener;
 import javax.media.opengl.GLProfile;
 
@@ -53,44 +66,55 @@ import org.junit.BeforeClass;
 import org.junit.AfterClass;
 import org.junit.Test;
 
-public class TestGearsES2NEWT extends UITestCase {
-    static GLProfile glp;
-    static int width, height;
+public class TestGearsES2NEWT extends UITestCase {    
+    static int screenIdx = 0;
+    static PointImmutable wpos;
+    static DimensionImmutable wsize;
 
+    static long duration = 500; // ms
+    static boolean opaque = true;
+    static boolean undecorated = false;
+    static boolean alwaysOnTop = false;
+    static boolean fullscreen = false;
+    static boolean pmvUseBackingArray = true;
+    static int swapInterval = 1;
+    static boolean waitForKey = false;
+    static boolean mouseVisible = true;
+    static boolean mouseConfined = false;
+    static boolean showFPS = false;
+    static int loops = 1;
+    static GLProfile.ShutdownType loop_shutdown = null;
+    static boolean forceES2 = false;
+    
     @BeforeClass
     public static void initClass() {
-        /*if(GLProfile.isAvailable(GLProfile.getDefaultEGLDevice(), GLProfile.GLES2)) {
-            // exact match
-            glp = GLProfile.get(GLProfile.getDefaultEGLDevice(), GLProfile.GLES2);
-        } else */ {
-            // default device, somehow ES2 compatible
-            glp = GLProfile.getGL2ES2(); 
+        if(null == wsize) {
+            wsize = new Dimension(200, 200);
         }
-        Assert.assertNotNull(glp);
-        // width  = 512;
-        // height = 512;
-        width  = 200;
-        height = 200;
     }
 
     @AfterClass
     public static void releaseClass() {
     }
 
-    protected void runTestGL(GLCapabilities caps, boolean undecorated) throws InterruptedException {
-        System.err.println("requested: "+caps);
-        final GLWindow glWindow = GLWindow.create(caps);
+    protected void runTestGL(GLCapabilitiesImmutable caps, boolean undecorated) throws InterruptedException {
+        System.err.println("requested: vsync "+swapInterval+", "+caps);
+        Display dpy = NewtFactory.createDisplay(null);
+        Screen screen = NewtFactory.createScreen(dpy, screenIdx);
+        final GLWindow glWindow = GLWindow.create(screen, caps);
         Assert.assertNotNull(glWindow);
-        glWindow.setTitle("Gears NEWT Test (translucent "+!caps.isBackgroundOpaque()+")");
-        glWindow.setSize(width, height);
-        glWindow.setPosition(100, 100);
+        glWindow.setTitle("Gears NEWT Test (translucent "+!caps.isBackgroundOpaque()+"), swapInterval "+swapInterval+", size "+wsize+", pos "+wpos);
+        glWindow.setSize(wsize.getWidth(), wsize.getHeight());
+        if(null != wpos) {
+            glWindow.setPosition(wpos.getX(), wpos.getY());
+        }
         glWindow.setUndecorated(undecorated);
         glWindow.setAlwaysOnTop(alwaysOnTop);
         glWindow.setFullscreen(fullscreen);
         glWindow.setPointerVisible(mouseVisible);
         glWindow.confinePointer(mouseConfined);
 
-        final GearsES2 demo = new GearsES2(vsync ? 1 : 0);
+        final GearsES2 demo = new GearsES2(swapInterval);
         demo.setPMVUseBackingArray(pmvUseBackingArray);
         glWindow.addGLEventListener(demo);
         if(waitForKey) {
@@ -122,21 +146,30 @@ public class TestGearsES2NEWT extends UITestCase {
         glWindow.addKeyListener(quitAdapter);
         glWindow.addWindowListener(quitAdapter);
 
+        glWindow.addWindowListener(new WindowAdapter() {
+            public void windowResized(WindowEvent e) {
+                System.err.println("window resized: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight());
+            }
+            public void windowMoved(WindowEvent e) {
+                System.err.println("window moved:   "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight());
+            }            
+        });
+        
         glWindow.addKeyListener(new KeyAdapter() {
             public void keyTyped(KeyEvent e) {
                 if(e.getKeyChar()=='f') {
                     new Thread() {
                         public void run() {
-                            System.err.println("[set fullscreen  pre]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", "+glWindow.getInsets());
+                            System.err.println("[set fullscreen  pre]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
                             glWindow.setFullscreen(!glWindow.isFullscreen());
-                            System.err.println("[set fullscreen post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", "+glWindow.getInsets());
+                            System.err.println("[set fullscreen post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
                     } }.start();
                 } else if(e.getKeyChar()=='a') {
                     new Thread() {
                         public void run() {
-                            System.err.println("[set alwaysontop pre]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
+                            System.err.println("[set alwaysontop pre]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
                             glWindow.setAlwaysOnTop(!glWindow.isAlwaysOnTop());
-                            System.err.println("[set alwaysontop post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
+                            System.err.println("[set alwaysontop post]: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", f "+glWindow.isFullscreen()+", a "+glWindow.isAlwaysOnTop()+", "+glWindow.getInsets());
                     } }.start();
                 } else if(e.getKeyChar()=='d') {
                     new Thread() {
@@ -188,49 +221,50 @@ public class TestGearsES2NEWT extends UITestCase {
             }
         });
 
-        animator.setUpdateFPSFrames(60, System.err);
         animator.start();
         // glWindow.setSkipContextReleaseThread(animator.getThread());
 
         glWindow.setVisible(true);
         
-        System.err.println("size/pos: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets());
-        System.err.println("chosen: "+glWindow.getChosenCapabilities());
+        System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities());
+        System.err.println("GL chosen: "+glWindow.getChosenCapabilities());
+        System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets());
+        
+        animator.setUpdateFPSFrames(60, showFPS ? System.err : null);
         
         while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()<duration) {
             Thread.sleep(100);
         }
 
         animator.stop();
+        Assert.assertFalse(animator.isAnimating());
+        Assert.assertFalse(animator.isStarted());
         glWindow.destroy();
+        Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glWindow, false));
     }
 
     @Test
-    public void test01() throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(glp);
-        caps.setBackgroundOpaque(opaque);
-        runTestGL(caps, undecorated);
+    public void test01GL2ES2() throws InterruptedException {
+        for(int i=1; i<=loops; i++) {
+            System.err.println("Loop "+i+"/"+loops);
+            GLCapabilities caps = new GLCapabilities(forceES2 ? GLProfile.get(GLProfile.GLES2) : GLProfile.getGL2ES2());
+            caps.setBackgroundOpaque(opaque);
+            runTestGL(caps, undecorated);
+            if(null != loop_shutdown) {
+                GLProfile.shutdown(loop_shutdown);
+            }
+        }
     }
 
-    static long duration = 500; // ms
-    static boolean opaque = true;
-    static boolean undecorated = false;
-    static boolean alwaysOnTop = false;
-    static boolean fullscreen = false;
-    static boolean pmvUseBackingArray = true;
-    static boolean vsync = false;
-    static boolean waitForKey = false;
-    static boolean mouseVisible = true;
-    static boolean mouseConfined = false;
-
-    public static void main(String args[]) throws IOException {
+    public static void main(String args[]) throws IOException {        
+        int x=0, y=0, w=200, h=200;
+        boolean useSize = false;
+        boolean usePos = false;
         
         for(int i=0; i<args.length; i++) {
             if(args[i].equals("-time")) {
                 i++;
-                try {
-                    duration = Integer.parseInt(args[i]);
-                } catch (Exception ex) { ex.printStackTrace(); }
+                duration = MiscUtils.atol(args[i], duration);
             } else if(args[i].equals("-translucent")) {
                 opaque = false;
             } else if(args[i].equals("-undecorated")) {
@@ -242,23 +276,69 @@ public class TestGearsES2NEWT extends UITestCase {
             } else if(args[i].equals("-pmvDirect")) {
                 pmvUseBackingArray = false;
             } else if(args[i].equals("-vsync")) {
-                vsync = true;
+                i++;
+                swapInterval = MiscUtils.atoi(args[i], swapInterval);
+            } else if(args[i].equals("-es2")) {
+                forceES2 = true;
             } else if(args[i].equals("-wait")) {
                 waitForKey = true;
             } else if(args[i].equals("-mouseInvisible")) {
                 mouseVisible = false;
             } else if(args[i].equals("-mouseConfine")) {
                 mouseConfined = true;
+            } else if(args[i].equals("-showFPS")) {
+                showFPS = true;
+            } else if(args[i].equals("-width")) {
+                i++;
+                w = MiscUtils.atoi(args[i], w);
+                useSize = true;
+            } else if(args[i].equals("-height")) {
+                i++;
+                h = MiscUtils.atoi(args[i], h);
+                useSize = true;
+            } else if(args[i].equals("-x")) {
+                i++;
+                x = MiscUtils.atoi(args[i], x);
+                usePos = true;
+            } else if(args[i].equals("-y")) {
+                i++;
+                y = MiscUtils.atoi(args[i], y);
+                usePos = true;
+            } else if(args[i].equals("-screen")) {
+                i++;
+                screenIdx = MiscUtils.atoi(args[i], 0);
+            } else if(args[i].equals("-loops")) {
+                i++;
+                loops = MiscUtils.atoi(args[i], 1);
+            } else if(args[i].equals("-loop-shutdown")) {
+                i++;
+                switch(MiscUtils.atoi(args[i], 0)) {
+                    case 1: loop_shutdown = GLProfile.ShutdownType.SHARED_ONLY; break; 
+                    case 2: loop_shutdown = GLProfile.ShutdownType.COMPLETE; break;
+                    default: throw new IllegalArgumentException("should be [0..2], 0-off, 1-shared, 2-complete");
+                }
             }
         }
+        if(useSize) {
+            wsize = new Dimension(w, h);
+        }
+        if(usePos) {
+            wpos = new Point(x, y);
+        }
+        System.err.println("position "+wpos);
+        System.err.println("size "+wsize);
+        System.err.println("screen "+screenIdx);
         System.err.println("translucent "+(!opaque));
         System.err.println("undecorated "+undecorated);
         System.err.println("atop "+alwaysOnTop);
         System.err.println("fullscreen "+fullscreen);
         System.err.println("pmvDirect "+(!pmvUseBackingArray));
-        System.err.println("vsync "+vsync);
+        System.err.println("swapInterval "+swapInterval);
         System.err.println("mouseVisible "+mouseVisible);
         System.err.println("mouseConfined "+mouseConfined);
+        System.err.println("loops "+loops);
+        System.err.println("loop shutdown "+loop_shutdown);
+        System.err.println("forceES2 "+forceES2);
 
         if(waitForKey) {
             BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestRedSquareES2NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestRedSquareES2NEWT.java
index f3bad28..74d52c3 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestRedSquareES2NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/newt/TestRedSquareES2NEWT.java
@@ -31,6 +31,8 @@ package com.jogamp.opengl.test.junit.jogl.demos.es2.newt;
 import com.jogamp.newt.event.KeyAdapter;
 import com.jogamp.newt.event.KeyEvent;
 import com.jogamp.newt.opengl.GLWindow;
+import com.jogamp.opengl.test.junit.util.AWTRobotUtil;
+import com.jogamp.opengl.test.junit.util.MiscUtils;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.util.QuitAdapter;
 
@@ -47,19 +49,14 @@ import org.junit.AfterClass;
 import org.junit.Test;
 
 public class TestRedSquareES2NEWT extends UITestCase {
-    static GLProfile glp;
     static int width, height;
+    static int loops = 1;
+    static GLProfile.ShutdownType loop_shutdown = null;
+    static boolean vsync = false;
+    static boolean forceES2 = false;
 
     @BeforeClass
     public static void initClass() {
-        /* if(GLProfile.isAvailable(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1)) {
-            // exact match
-            glp = GLProfile.get(GLProfile.getDefaultEGLDevice(), GLProfile.GLES1);
-        } else */ {
-            // default device, somehow ES1 compatible
-            glp = GLProfile.getGL2ES2(); 
-        }
-        Assert.assertNotNull(glp);
         width  = 512;
         height = 512;
     }
@@ -69,11 +66,13 @@ public class TestRedSquareES2NEWT extends UITestCase {
     }
 
     protected void runTestGL(GLCapabilities caps) throws InterruptedException {
+        System.err.println("requested: vsync "+vsync+", "+caps);
         GLWindow glWindow = GLWindow.create(caps);
         Assert.assertNotNull(glWindow);
         glWindow.setTitle("Gears NEWT Test");
+        glWindow.setSize(width, height);
 
-        glWindow.addGLEventListener(new RedSquareES2());
+        glWindow.addGLEventListener(new RedSquareES2(vsync ? 1 : -1));
 
         Animator animator = new Animator(glWindow);
         QuitAdapter quitAdapter = new QuitAdapter();
@@ -100,23 +99,37 @@ public class TestRedSquareES2NEWT extends UITestCase {
             }
         });
 
-        glWindow.setSize(width, height);
-        glWindow.setVisible(true);
-        animator.setUpdateFPSFrames(60, System.err);
         animator.start();
+        
+        glWindow.setVisible(true);
 
+        System.err.println("NW chosen: "+glWindow.getDelegatedWindow().getChosenCapabilities());
+        System.err.println("GL chosen: "+glWindow.getChosenCapabilities());
+        System.err.println("window pos/siz: "+glWindow.getX()+"/"+glWindow.getY()+" "+glWindow.getWidth()+"x"+glWindow.getHeight()+", "+glWindow.getInsets());
+        
+        animator.setUpdateFPSFrames(60, System.err);
+        
         while(!quitAdapter.shouldQuit() && animator.isAnimating() && animator.getTotalFPSDuration()<duration) {
             Thread.sleep(100);
         }
 
         animator.stop();
+        Assert.assertFalse(animator.isAnimating());
+        Assert.assertFalse(animator.isStarted());
         glWindow.destroy();
+        Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glWindow, false));
     }
 
     @Test
-    public void test01() throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(glp);
-        runTestGL(caps);
+    public void test01GL2ES2() throws InterruptedException {
+        for(int i=1; i<=loops; i++) {
+            System.err.println("Loop "+i+"/"+loops);
+            GLCapabilities caps = new GLCapabilities(forceES2 ? GLProfile.get(GLProfile.GLES2) : GLProfile.getGL2ES2());
+            runTestGL(caps);
+            if(null != loop_shutdown) {
+                GLProfile.shutdown(loop_shutdown);
+            }
+        }
     }
 
     static long duration = 500; // ms
@@ -128,8 +141,23 @@ public class TestRedSquareES2NEWT extends UITestCase {
                 try {
                     duration = Integer.parseInt(args[i]);
                 } catch (Exception ex) { ex.printStackTrace(); }
+            } else if(args[i].equals("-es2")) {
+                forceES2 = true;
+            } else if(args[i].equals("-loops")) {
+                i++;
+                loops = MiscUtils.atoi(args[i], 1);
+            } else if(args[i].equals("-loop-shutdown")) {
+                i++;
+                switch(MiscUtils.atoi(args[i], 0)) {
+                    case 1: loop_shutdown = GLProfile.ShutdownType.SHARED_ONLY; break; 
+                    case 2: loop_shutdown = GLProfile.ShutdownType.COMPLETE; break;
+                    default: throw new IllegalArgumentException("should be [0..2], 0-off, 1-shared, 2-complete");
+                }
             }
         }
+        System.err.println("loops "+loops);
+        System.err.println("loop shutdown "+loop_shutdown);
+        System.err.println("forceES2 "+forceES2);
         org.junit.runner.JUnitCore.main(TestRedSquareES2NEWT.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.fp b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.fp
new file mode 100644
index 0000000..adde23d
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.fp
@@ -0,0 +1,22 @@
+// Copyright 2012 JogAmp Community. All rights reserved.
+
+varying  vec2          mgl_texCoord;
+varying  vec4          frontColor;
+
+// Insert dynamic code after the following tag:
+// TEXTURE-SEQUENCE-CODE-BEGIN
+// TEXTURE-SEQUENCE-CODE-END
+
+void main (void)
+{
+  vec4 texColor;
+  if(0.0 <= mgl_texCoord.t && mgl_texCoord.t<=1.0) {
+    texColor = myTexture2D(mgl_ActiveTexture, mgl_texCoord);
+  } else {
+    texColor = vec4(1, 1, 1, 1);
+  }
+
+  // mix frontColor with texture ..
+  gl_FragColor = vec4(frontColor*texColor);
+}
+
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.vp b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.vp
new file mode 100644
index 0000000..c521e37
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader/texsequence_xxx.vp
@@ -0,0 +1,17 @@
+// Copyright 2012 JogAmp Community. All rights reserved.
+
+uniform   mat4    mgl_PMVMatrix[2];
+// uniform  mat4  mgl_STMatrix;
+attribute vec4    mgl_Vertex;
+attribute vec4    mgl_Color;
+attribute vec4    mgl_MultiTexCoord;
+varying   vec4    frontColor;
+varying   vec2    mgl_texCoord;
+
+void main(void)
+{
+  frontColor=mgl_Color;
+  // mgl_texCoord = (mgl_STMatrix * mgl_MultiTexCoord).st;
+  mgl_texCoord = mgl_MultiTexCoord.st;
+  gl_Position = mgl_PMVMatrix[0] * mgl_PMVMatrix[1] * mgl_Vertex;
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWT.java
index f032696..ff24979 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWT.java
@@ -41,6 +41,9 @@ import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.util.QuitAdapter;
 import java.awt.Frame;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
 import java.lang.reflect.InvocationTargetException;
 
 import org.junit.Assert;
@@ -51,14 +54,20 @@ import org.junit.Test;
 public class TestGearsAWT extends UITestCase {
     static GLProfile glp;
     static int width, height;
-    static boolean firstUIActionOnProcess = false;
+    static boolean waitForKey = false;
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        width  = 512;
-        height = 512;
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            width  = 512;
+            height = 512;
+        } else {
+            setTestSupported(false);
+        }
+        // Runtime.getRuntime().traceInstructions(true);
+        // Runtime.getRuntime().traceMethodCalls(true);
     }
 
     @AfterClass
@@ -123,10 +132,17 @@ public class TestGearsAWT extends UITestCase {
                 try {
                     duration = Integer.parseInt(args[i]);
                 } catch (Exception ex) { ex.printStackTrace(); }
-            } else if(args[i].equals("-firstUIAction")) {
-                firstUIActionOnProcess = true;
+            } else if(args[i].equals("-wait")) {
+                waitForKey = true;
             }
         }
+        if(waitForKey) {
+            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
+            System.err.println("Press enter to continue");
+            try {
+                System.err.println(stdin.readLine());
+            } catch (IOException e) { }
+        }
         org.junit.runner.JUnitCore.main(TestGearsAWT.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java
index 4b670f0..4807e5d 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsAWTAnalyzeBug455.java
@@ -61,10 +61,14 @@ public class TestGearsAWTAnalyzeBug455 extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        width  = 512;
-        height = 512;
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            width  = 512;
+            height = 512;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     @AfterClass
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWT.java
index 59d54c3..c7254dd 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWT.java
@@ -44,7 +44,6 @@ import javax.swing.SwingUtilities;
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.AfterClass;
-import org.junit.Ignore;
 import org.junit.Test;
 
 public class TestGearsGLJPanelAWT extends UITestCase {
@@ -53,10 +52,14 @@ public class TestGearsGLJPanelAWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        width  = 512;
-        height = 512;
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            width  = 512;
+            height = 512;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     @AfterClass
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWTBug450.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWTBug450.java
index 7a4645b..7207e78 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWTBug450.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/awt/TestGearsGLJPanelAWTBug450.java
@@ -68,10 +68,14 @@ public class TestGearsGLJPanelAWTBug450 extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        width  = 512;
-        height = 256;
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            width  = 512;
+            height = 256;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     @AfterClass
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNEWT.java
index f410baf..0f3c7e2 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNEWT.java
@@ -38,11 +38,8 @@ import com.jogamp.opengl.util.Animator;
 
 import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
 
-import javax.media.opengl.FPSCounter;
-import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLProfile;
-import javax.media.opengl.GLRunnable;
 
 import org.junit.Assert;
 import org.junit.BeforeClass;
@@ -55,10 +52,14 @@ public class TestGearsNEWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
-        Assert.assertNotNull(glp);
-        width  = 512;
-        height = 512;
+        if(GLProfile.isAvailable(GLProfile.GL2)) {
+            glp = GLProfile.get(GLProfile.GL2);
+            Assert.assertNotNull(glp);
+            width  = 512;
+            height = 512;
+        } else {
+            setTestSupported(false);
+        }
     }
 
     @AfterClass
@@ -112,7 +113,7 @@ public class TestGearsNEWT extends UITestCase {
 
     @Test
     public void test01() throws InterruptedException {
-        GLCapabilities caps = new GLCapabilities(GLProfile.getDefault());
+        GLCapabilities caps = new GLCapabilities(glp);
         runTestGL(caps);
     }
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNewtAWTWrapper.java b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNewtAWTWrapper.java
index e05c588..54cfd0a 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNewtAWTWrapper.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/demos/gl2/newt/TestGearsNewtAWTWrapper.java
@@ -35,7 +35,7 @@ import com.jogamp.opengl.util.Animator;
 
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.util.QuitAdapter;
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.Gears;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 import com.jogamp.newt.*;
 import com.jogamp.newt.event.*;
 import com.jogamp.newt.opengl.*;
@@ -51,7 +51,7 @@ public class TestGearsNewtAWTWrapper extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.getDefault();
+        glp = GLProfile.getGL2ES2();
         Assert.assertNotNull(glp);
         width  = 512;
         height = 512;
@@ -70,7 +70,7 @@ public class TestGearsNewtAWTWrapper extends UITestCase {
         Assert.assertNotNull(glWindow);
         glWindow.setTitle("Gears NewtAWTWrapper Test");
 
-        glWindow.addGLEventListener(new Gears());
+        glWindow.addGLEventListener(new GearsES2(1));
 
         Animator animator = new Animator(glWindow);
         QuitAdapter quitAdapter = new QuitAdapter();
@@ -93,7 +93,7 @@ public class TestGearsNewtAWTWrapper extends UITestCase {
 
     @Test
     public void test01() throws InterruptedException {
-        GLCapabilitiesImmutable caps = new GLCapabilities(GLProfile.getDefault());
+        GLCapabilitiesImmutable caps = new GLCapabilities(glp);
         runTestGL(caps);
     }
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestFBOMRTNEWT01.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestFBOMRTNEWT01.java
index aca1e66..9b26b46 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestFBOMRTNEWT01.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestFBOMRTNEWT01.java
@@ -27,7 +27,6 @@
  */
 package com.jogamp.opengl.test.junit.jogl.glsl;
 
-import com.jogamp.common.os.Platform;
 import com.jogamp.opengl.util.FBObject;
 import com.jogamp.opengl.util.GLArrayDataServer;
 import com.jogamp.opengl.util.PMVMatrix;
@@ -51,7 +50,6 @@ import javax.media.opengl.GLUniformData;
 
 import org.junit.Assert;
 import org.junit.Test;
-import org.junit.BeforeClass;
 
 public class TestFBOMRTNEWT01 extends UITestCase {
     static long durationPerTest = 10; // ms
@@ -59,13 +57,14 @@ public class TestFBOMRTNEWT01 extends UITestCase {
     @Test
     public void test01() throws InterruptedException {
         // preset ..
-        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOnscreenWindow(GLProfile.getGL2ES2(), 640, 480, true);        
+        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+            System.err.println("Test requires GL2/GL3 profile.");
+            return;
+        }
+        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOnscreenWindow(GLProfile.getGL2GL3(), 640, 480, true);        
         final GLDrawable drawable = winctx.context.getGLDrawable();
-        GL _gl = winctx.context.getGL();
-        Assert.assertTrue(_gl.isGL2GL3());
-        _gl = _gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, _gl, null) );
-        Assert.assertTrue(_gl.isGL2GL3());
-        final GL2GL3 gl = _gl.getGL2GL3();
+        GL2GL3 gl = winctx.context.getGL().getGL2GL3();
+        gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, gl, null) ).getGL2GL3();
         System.err.println(winctx.context);
 
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
@@ -73,10 +72,10 @@ public class TestFBOMRTNEWT01 extends UITestCase {
         final ShaderState st = new ShaderState();
         // st.setVerbose(true);
         
-        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "fbo-mrt-1");
-        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "fbo-mrt-1");
+        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "fbo-mrt-1", false);
+        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "fbo-mrt-1", false);
         final ShaderProgram sp0 = new ShaderProgram();
         sp0.add(gl, vp0, System.err);
         sp0.add(gl, fp0, System.err);       
@@ -84,12 +83,12 @@ public class TestFBOMRTNEWT01 extends UITestCase {
         Assert.assertTrue(!sp0.inUse());
         Assert.assertTrue(!sp0.linked());
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());        
-        st.attachShaderProgram(gl, sp0);
+        st.attachShaderProgram(gl, sp0, false);
         
-        final ShaderCode vp1 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "fbo-mrt-2");
-        final ShaderCode fp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "fbo-mrt-2");
+        final ShaderCode vp1 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "fbo-mrt-2", false);
+        final ShaderCode fp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "fbo-mrt-2", false);
         final ShaderProgram sp1 = new ShaderProgram();
         sp1.add(gl, vp1, System.err);
         sp1.add(gl, fp1, System.err);       
@@ -97,8 +96,7 @@ public class TestFBOMRTNEWT01 extends UITestCase {
         Assert.assertTrue(!sp1.inUse());
         Assert.assertTrue(!sp1.linked());
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());        
-        st.attachShaderProgram(gl, sp1);
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp1, true);
                         
         final PMVMatrix pmvMatrix = new PMVMatrix();
         final GLUniformData pmvMatrixUniform = new GLUniformData("gcu_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf());
@@ -175,7 +173,7 @@ public class TestFBOMRTNEWT01 extends UITestCase {
         
         for(int i=0; i<durationPerTest; i+=50) {
             // pass 1 - MRT: Red -> buffer0, Green -> buffer1
-            st.attachShaderProgram(gl, sp0);           
+            st.attachShaderProgram(gl, sp0, true);           
             vertices0.enableBuffer(gl, true);
             colors0.enableBuffer(gl, true);
             
@@ -191,7 +189,7 @@ public class TestFBOMRTNEWT01 extends UITestCase {
             
             // pass 2 - mix buffer0, buffer1 and blue
             // rg = buffer0.rg + buffer1.rg, b = Blue - length(rg);
-            st.attachShaderProgram(gl, sp1);
+            st.attachShaderProgram(gl, sp1, true);
             vertices0.enableBuffer(gl, true);
             colors0.enableBuffer(gl, true);
             texCoords0.enableBuffer(gl, true);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState01NEWT.java
index ea29069..fb05e26 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState01NEWT.java
@@ -72,10 +72,10 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
+        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
 
         final ShaderProgram sp = new ShaderProgram();
         Assert.assertTrue(0>sp.program());
@@ -88,7 +88,9 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         Assert.assertTrue(!sp.linked());
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
         
-        st.attachShaderProgram(gl, sp);
+        st.attachShaderProgram(gl, sp, false);
+        Assert.assertTrue(!sp.inUse());
+        Assert.assertTrue(!sp.linked());
         
         Assert.assertEquals(null, ShaderState.getShaderState(gl));
         st.setShaderState(gl); // pre-use attach
@@ -199,10 +201,10 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
+        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
 
         final ShaderProgram sp = new ShaderProgram();
         sp.add(rsVp);
@@ -211,8 +213,7 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         sp.init(gl);
         Assert.assertTrue(sp.link(gl, System.err));
         
-        st.attachShaderProgram(gl, sp);        
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp, true);        
         
         // setup mgl_PMVMatrix
         final PMVMatrix pmvMatrix = new PMVMatrix();
@@ -288,10 +289,10 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
+        final ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
 
         final ShaderProgram sp = new ShaderProgram();
         sp.add(rsVp);
@@ -300,8 +301,7 @@ public class TestGLSLShaderState01NEWT extends UITestCase {
         sp.init(gl);
         Assert.assertTrue(sp.link(gl, System.err));
         
-        st.attachShaderProgram(gl, sp);        
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp, true);        
         
         // setup mgl_PMVMatrix
         final PMVMatrix pmvMatrix = new PMVMatrix();
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState02NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState02NEWT.java
index fb52ff0..6450965 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState02NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLShaderState02NEWT.java
@@ -79,12 +79,12 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode rsVp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader2");
+        final ShaderCode rsVp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader2", false);
 
         final ShaderProgram sp1 = new ShaderProgram();
         sp1.add(rsVp0);
@@ -114,7 +114,9 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         Assert.assertTrue(!sp0.linked());
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());        
                 
-        st.attachShaderProgram(gl, sp0);
+        st.attachShaderProgram(gl, sp0, false);
+        Assert.assertTrue(!sp0.inUse());
+        Assert.assertTrue(!sp0.linked());
         Assert.assertEquals(null, ShaderState.getShaderState(gl));
         st.setShaderState(gl); // pre-use attach
         Assert.assertEquals(st, ShaderState.getShaderState(gl));
@@ -200,7 +202,9 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         GLSLMiscHelper.displayVCArrays(drawable, gl, true, vertices1, colors1, true, 4, durationPerTest);
         
         // SP1
-        st.attachShaderProgram(gl, sp1);
+        st.attachShaderProgram(gl, sp1, true);        
+        Assert.assertTrue(sp1.inUse());
+        Assert.assertTrue(sp1.linked());
         
         if(!linkSP1) {
             // all attribute locations shall be same now, due to impl. glBindAttributeLocation
@@ -245,12 +249,12 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode rsVp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader");
-        final ShaderCode rsFp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "RedSquareShader2");
+        final ShaderCode rsVp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader", false);
+        final ShaderCode rsFp1 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "RedSquareShader2", false);
 
         final ShaderProgram sp1 = new ShaderProgram();
         sp1.add(rsVp0);
@@ -267,8 +271,7 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         sp0.init(gl);
         Assert.assertTrue(sp0.link(gl, System.err));
         
-        st.attachShaderProgram(gl, sp0);        
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp0, true);        
         
         // setup mgl_PMVMatrix
         final PMVMatrix pmvMatrix = new PMVMatrix();
@@ -313,20 +316,20 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         gl.setSwapInterval(0);
         
         // validation ..
-        st.attachShaderProgram(gl, sp0);
+        st.attachShaderProgram(gl, sp0, true);
         GLSLMiscHelper.displayVCArrays(drawable, gl, true, vertices0, colors0, true, 1, 0);
         GLSLMiscHelper.displayVCArrays(drawable, gl, true, vertices1, colors1, true, 2, 0);
-        st.attachShaderProgram(gl, sp1);
+        st.attachShaderProgram(gl, sp1, true);
         GLSLMiscHelper.displayVCArrays(drawable, gl, true, vertices0, colors0, true, 1, 0);
         GLSLMiscHelper.displayVCArrays(drawable, gl, true, vertices1, colors1, true, 2, 0);
         
         // warmup ..        
         for(int frames=0; frames<GLSLMiscHelper.frames_warmup; frames+=2) {
             // SP0
-            st.attachShaderProgram(gl, sp0);
+            st.attachShaderProgram(gl, sp0, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices0, colors0, true);
             // SP1
-            st.attachShaderProgram(gl, sp1);
+            st.attachShaderProgram(gl, sp1, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices1, colors1, true);
         }
         
@@ -336,11 +339,11 @@ public class TestGLSLShaderState02NEWT extends UITestCase {
         
         for(frames=0; frames<GLSLMiscHelper.frames_perftest; frames+=4) {
             // SP0
-            st.attachShaderProgram(gl, sp0);
+            st.attachShaderProgram(gl, sp0, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices0, colors0, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices1, colors1, true);
             // SP1
-            st.attachShaderProgram(gl, sp1);
+            st.attachShaderProgram(gl, sp1, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices0, colors0, true);
             GLSLMiscHelper.displayVCArraysNoChecks(drawable, gl, true, vertices1, colors1, true);
         }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLSimple01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLSimple01NEWT.java
index 6721939..ba43cc2 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLSimple01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestGLSLSimple01NEWT.java
@@ -33,13 +33,11 @@ import com.jogamp.opengl.test.junit.util.GLSLSimpleProgram;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 
 
-import javax.media.opengl.FPSCounter;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLContext;
 import javax.media.opengl.GLProfile;
 
 import org.junit.Assert;
-import org.junit.BeforeClass;
 import org.junit.Test;
 
 import com.jogamp.newt.opengl.GLWindow;
@@ -49,7 +47,6 @@ import com.jogamp.opengl.test.junit.util.MiscUtils;
 
 import java.io.IOException;
 import javax.media.opengl.GL2ES2;
-import org.junit.AfterClass;
 
 public class TestGLSLSimple01NEWT extends UITestCase {
     static long durationPerTest = 100; // ms
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java
index 13780a7..f6e46da 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestRulerNEWT01.java
@@ -72,10 +72,10 @@ public class TestRulerNEWT01 extends UITestCase {
         // test code ..        
         final ShaderState st = new ShaderState();
         
-        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "default");
-        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, 1, RedSquareES2.class,
-                "shader", "shader/bin", "ruler");
+        final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "default", false);
+        final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquareES2.class, "shader",
+                "shader/bin", "ruler", false);
 
         final ShaderProgram sp0 = new ShaderProgram();
         sp0.add(gl, vp0, System.err);
@@ -85,8 +85,7 @@ public class TestRulerNEWT01 extends UITestCase {
         Assert.assertTrue(!sp0.linked());
         Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
         
-        st.attachShaderProgram(gl, sp0);
-        st.useProgram(gl, true);
+        st.attachShaderProgram(gl, sp0, true);
         
         final PMVMatrix pmvMatrix = new PMVMatrix();
         final GLUniformData pmvMatrixUniform = new GLUniformData("gcu_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf());
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestTransformFeedbackVaryingsBug407NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestTransformFeedbackVaryingsBug407NEWT.java
index a3059ba..685ceeb 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestTransformFeedbackVaryingsBug407NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glsl/TestTransformFeedbackVaryingsBug407NEWT.java
@@ -1,25 +1,23 @@
 package com.jogamp.opengl.test.junit.jogl.glsl;
 
+import com.jogamp.opengl.test.junit.util.NEWTGLContext;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 
 import java.io.ByteArrayOutputStream;
 import java.io.PrintStream;
 
+import javax.media.opengl.GL;
+import javax.media.opengl.GL2ES2;
 import javax.media.opengl.GL3;
-import javax.media.opengl.GLCapabilities;
-import javax.media.opengl.GLContext;
+import javax.media.opengl.GLException;
 import javax.media.opengl.GLProfile;
 
 import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.BeforeClass;
 import org.junit.Test;
 
-import com.jogamp.newt.opengl.GLWindow;
 import com.jogamp.opengl.util.glsl.ShaderUtil;
 
 import java.io.IOException;
-import org.junit.AfterClass;
 
 /**
  * Bug 'Function glTransformFeedbackVaryings incorrectly passes argument'
@@ -27,7 +25,16 @@ import org.junit.AfterClass;
  */
 public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
 
-    private String VERTEX_SHADER_TEXT;
+    private static final boolean debugGL = true;
+    
+    private static final String VERTEX_SHADER_TEXT =
+                  "#version 150                           \n"
+                + "                                       \n"
+                + "out vec4 Position;                     \n"
+                + "                                       \n"
+                + "void main() {                          \n"
+                + "  Position = vec4(1.0, 1.0, 1.0, 1.0); \n"
+                + "}                                      \n";
 
     class MyShader {
         int shaderProgram;
@@ -39,7 +46,7 @@ public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
         }
     }
 
-    private MyShader getShader(GL3 gl, String text, int type) {
+    private MyShader attachShader(GL3 gl, String text, int type) {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         PrintStream pbaos = new PrintStream(baos);
 
@@ -52,13 +59,14 @@ public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
         gl.glShaderSource(vertShader, lines.length, lines, lengths, 0);
         gl.glCompileShader(vertShader);
 
-        if(!ShaderUtil.isShaderStatusValid(gl, vertShader, gl.GL_COMPILE_STATUS, pbaos)) {
+        if(!ShaderUtil.isShaderStatusValid(gl, vertShader, GL2ES2.GL_COMPILE_STATUS, pbaos)) {
             System.out.println("getShader:postCompile: "+baos.toString());
             Assert.assertTrue(false);
         }
         pbaos.flush(); baos.reset();
 
         gl.glAttachShader(shaderProgram, vertShader);
+        Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
 
         return new MyShader(shaderProgram, vertShader);
     }
@@ -69,119 +77,82 @@ public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
             gl.glDeleteShader(myShader.vertShader);
             gl.glDeleteProgram(myShader.shaderProgram);
         }
+        Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
     }
 
-
-    private GLWindow prepareTest() {
-        if(!GLProfile.isAvailable(GLProfile.GL3)) {
+    final static String glps = GLProfile.GL3;
+    
+    private NEWTGLContext.WindowContext prepareTest() throws GLException, InterruptedException {
+        final NEWTGLContext.WindowContext winctx = NEWTGLContext.createOnscreenWindow(GLProfile.getMaxProgrammable(true), 480, 480, debugGL);
+        if(!winctx.context.getGL().isGL3()) {
             System.err.println("GL3 not available");
-            System.err.println(GLProfile.glAvailabilityToString());
+            cleanupTest(winctx);
             return null;
         }
-        VERTEX_SHADER_TEXT =
-                  "#version 150                           \n"
-                + "                                       \n"
-                + "out vec4 Position;                     \n"
-                + "                                       \n"
-                + "void main() {                          \n"
-                + "  Position = vec4(1.0, 1.0, 1.0, 1.0); \n"
-                + "}                                      \n";
-
-        GLCapabilities caps;        
-
-        GLProfile glp = null;
-        try {
-            glp = GLProfile.get(GLProfile.GL3);
-        } catch (Throwable t) {
-            t.printStackTrace();
-            Assume.assumeNoException(t);
-        }
-        caps = new GLCapabilities(glp);
-
-        caps.setOnscreen(true);
-        caps.setDoubleBuffered(true);
-
-        GLWindow window = GLWindow.create(caps);
-        Assert.assertNotNull(window);
-        window.setUndecorated(true);
-        window.setSize(800, 600);
-        window.setVisible(true);
-        Assert.assertTrue(window.isNativeValid());
-
-        window.getContext().setSynchronized(true);
-
-        // trigger native creation of drawable/context
-        window.display();
-        Assert.assertTrue(window.isRealized());
-        Assert.assertTrue(window.getContext().isCreated());
-
-        return window;
+        Assert.assertEquals(GL.GL_NO_ERROR, winctx.context.getGL().glGetError());        
+        return winctx;
     }
 
-    private void cleanupTest(GLWindow window) {
-        if(null!=window) {
-            window.destroy();
+    private void cleanupTest(NEWTGLContext.WindowContext winctx) {
+        if(null!=winctx) {
+            NEWTGLContext.destroyWindow(winctx);
         }
     }
 
     @Test(timeout=60000)
-    public void testGlTransformFeedbackVaryings_WhenVarNameOK() {
-        if(!GLProfile.isAvailable(GLProfile.GL3)) {
+    public void testGlTransformFeedbackVaryings_WhenVarNameOK() throws GLException, InterruptedException {
+        NEWTGLContext.WindowContext winctx = prepareTest();
+        if(null == winctx) {
             return;
         }
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         PrintStream pbaos = new PrintStream(baos);
 
-        GLWindow window = prepareTest();
-        GLContext context = window.getContext();
-        context.makeCurrent();
-
         // given
 
-        GL3 gl = context.getGL().getGL3();
-        MyShader myShader = getShader(gl, VERTEX_SHADER_TEXT, GL3.GL_VERTEX_SHADER);
+        final GL3 gl = winctx.context.getGL().getGL3();
+        Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
+        
+        MyShader myShader = attachShader(gl, VERTEX_SHADER_TEXT, GL3.GL_VERTEX_SHADER);
         String[] vars = new String[]{"Position"};
 
         // when
 
         gl.glTransformFeedbackVaryings(myShader.shaderProgram, 1, vars, GL3.GL_SEPARATE_ATTRIBS);
         gl.glLinkProgram(myShader.shaderProgram);
-
+        Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
+        
         // then
 
         boolean error = false;
 
-        if(!ShaderUtil.isProgramValid(gl, myShader.shaderProgram, pbaos)) {
+        if(!ShaderUtil.isProgramLinkStatusValid(gl, myShader.shaderProgram, pbaos)) {
             System.out.println("Error (unexpected link error) - testGlTransformFeedbackVaryings_WhenVarNameOK:postLink: "+baos.toString());
             error = true;
         }
         pbaos.flush(); baos.reset();
-
         Assert.assertEquals(GL3.GL_NO_ERROR, gl.glGetError());
 
-        releaseShader(gl, myShader);
-        context.release();
-        cleanupTest(window);
-
+        releaseShader(gl, myShader);        
+        cleanupTest(winctx);
         Assert.assertFalse(error);
     }
 
     @Test(timeout=60000)
-    public void testGlTransformFeedbackVaryings_WhenVarNameWrong() {
-        if(!GLProfile.isAvailable(GLProfile.GL3)) {
+    public void testGlTransformFeedbackVaryings_WhenVarNameWrong() throws GLException, InterruptedException {
+        NEWTGLContext.WindowContext winctx = prepareTest();
+        if(null == winctx) {
             return;
         }
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         PrintStream pbaos = new PrintStream(baos);
 
-        GLWindow window = prepareTest();
-        GLContext context = window.getContext();
-        context.makeCurrent();
-
         // given
 
-        GL3 gl = context.getGL().getGL3();
-        MyShader myShader = getShader(gl, VERTEX_SHADER_TEXT, GL3.GL_VERTEX_SHADER);
+        final GL3 gl = winctx.context.getGL().getGL3();
+        Assert.assertEquals(GL.GL_NO_ERROR, gl.glGetError());
+
+        MyShader myShader = attachShader(gl, VERTEX_SHADER_TEXT, GL3.GL_VERTEX_SHADER);
         String[] vars = new String[]{"PPPosition"};
 
         // when
@@ -193,7 +164,7 @@ public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
 
         boolean error = false;
 
-        if(!ShaderUtil.isProgramValid(gl, myShader.shaderProgram, pbaos)) {
+        if(!ShaderUtil.isProgramLinkStatusValid(gl, myShader.shaderProgram, pbaos)) {
             System.out.println("GOOD (expected link error) - testGlTransformFeedbackVaryings_WhenVarNameWrong:postLink: "+baos.toString());
             // should be invalid, due to wrong var name
         } else {
@@ -202,13 +173,10 @@ public class TestTransformFeedbackVaryingsBug407NEWT extends UITestCase {
             error = true;
         }
         pbaos.flush(); baos.reset();
-
         Assert.assertEquals(GL3.GL_NO_ERROR, gl.glGetError());
-        // You cannot assume this error message - Assert.assertTrue(baos.toString().contains("(named PPPosition)"));
-
+        
         releaseShader(gl, myShader);
-        context.release();
-        cleanupTest(window);
+        cleanupTest(winctx);
 
         Assert.assertFalse(error);
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/glu/TestBug463ScaleImageMemoryAWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/glu/TestBug463ScaleImageMemoryAWT.java
index f23bca8..3f122ac 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/glu/TestBug463ScaleImageMemoryAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/glu/TestBug463ScaleImageMemoryAWT.java
@@ -92,7 +92,7 @@ public class TestBug463ScaleImageMemoryAWT extends UITestCase implements GLEvent
 
     @Test
     public void test01() throws InterruptedException {
-        GLProfile glprofile = GLProfile.getDefault();
+        GLProfile glprofile = GLProfile.getGL2ES1();
         GLCapabilities glCapabilities = new GLCapabilities(glprofile);
         final GLCanvas canvas = new GLCanvas(glCapabilities);
         canvas.addGLEventListener( this );
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/newt/TestSwingAWTRobotUsageBeforeJOGLInitBug411.java b/src/test/com/jogamp/opengl/test/junit/jogl/newt/TestSwingAWTRobotUsageBeforeJOGLInitBug411.java
index 213d3ad..b165a96 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/newt/TestSwingAWTRobotUsageBeforeJOGLInitBug411.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/newt/TestSwingAWTRobotUsageBeforeJOGLInitBug411.java
@@ -157,7 +157,9 @@ public class TestSwingAWTRobotUsageBeforeJOGLInitBug411 extends UITestCase {
         robot = new Robot();
         robot.setAutoWaitForIdle(true);
 
-        AWTRobotUtil.toFront(robot, frame);
+        Assert.assertEquals(true,  AWTRobotUtil.waitForVisible(frame, true));
+        AWTRobotUtil.clearAWTFocus(robot);        
+        AWTRobotUtil.toFrontAndRequestFocus(robot, frame);
         AWTRobotUtil.requestFocus(robot, button);
 
         System.err.println("TestSwingAWTRobotUsageBeforeJOGLInitBug411.setup(): Before JOGL init");
@@ -195,7 +197,7 @@ public class TestSwingAWTRobotUsageBeforeJOGLInitBug411 extends UITestCase {
             }
         });
 
-        AWTRobotUtil.toFront(robot, frame);
+        AWTRobotUtil.toFrontAndRequestFocus(robot, frame);
 
         drawable.addGLEventListener(new GearsES2());
 
@@ -214,6 +216,7 @@ public class TestSwingAWTRobotUsageBeforeJOGLInitBug411 extends UITestCase {
         drawable.addGLEventListener(new SwingGLAction());
 
         Point p0 = canvas.getLocationOnScreen();
+        p0.translate(10,10);
         robot.mouseMove( (int) ( p0.getX() + .5 ) ,
                          (int) ( p0.getY() + .5 ) );
         robot.mousePress(InputEvent.BUTTON1_MASK);
@@ -242,7 +245,7 @@ public class TestSwingAWTRobotUsageBeforeJOGLInitBug411 extends UITestCase {
     public void test01NewtCanvasAWT() throws AWTException, InterruptedException, InvocationTargetException {
         System.err.println("TestSwingAWTRobotUsageBeforeJOGLInitBug411.test01NewtCanvasAWT(): Start");
 
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
 
         GLWindow win0 = GLWindow.create(caps);
@@ -277,7 +280,7 @@ public class TestSwingAWTRobotUsageBeforeJOGLInitBug411 extends UITestCase {
     @Test
     public void test02GLCanvas() throws AWTException, InterruptedException, InvocationTargetException {
         System.err.println("TestSwingAWTRobotUsageBeforeJOGLInitBug411.test02GLCanvas(): Start");
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
 
         Animator anim = new Animator();
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/ReadBuffer2File.java b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/ReadBuffer2File.java
index b829c8d..9506d00 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/ReadBuffer2File.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/ReadBuffer2File.java
@@ -31,7 +31,6 @@ package com.jogamp.opengl.test.junit.jogl.offscreen;
 import java.io.IOException;
 import javax.media.opengl.*;
 
-import com.jogamp.opengl.util.texture.TextureIO;
 import java.io.File;
 
 public class ReadBuffer2File extends ReadBufferBase {
@@ -51,7 +50,7 @@ public class ReadBuffer2File extends ReadBufferBase {
             return;
         }
 
-        File file = File.createTempFile("shot" + shotNum + "-", ".ppm");
+        File file = File.createTempFile("shot" + shotNum + "-", ".png");
         readBufferUtil.write(file);
         System.out.println("Wrote: " + file.getAbsolutePath() + ", ...");
         shotNum++;
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/Surface2File.java b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/Surface2File.java
index 8ca1f3e..d1297e0 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/Surface2File.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/Surface2File.java
@@ -31,7 +31,6 @@ package com.jogamp.opengl.test.junit.jogl.offscreen;
 import javax.media.opengl.*;
 
 import com.jogamp.opengl.util.GLReadBufferUtil;
-import com.jogamp.opengl.util.texture.TextureIO;
 
 import java.io.File;
 import java.io.IOException;
@@ -55,12 +54,13 @@ public class Surface2File implements SurfaceUpdatedListener {
                 GL gl = ctx.getGL();
                 // FIXME glFinish() is an expensive paranoia sync, should not be necessary due to spec
                 gl.glFinish();
-                readBufferUtil.readPixels(gl, drawable, false);
-                gl.glFinish();
-                try {
-                    surface2File("shot");
-                } catch (IOException ex) {
-                    throw new RuntimeException("can not write survace to file", ex);
+                if(readBufferUtil.readPixels(gl, drawable, false)) {
+                    gl.glFinish();
+                    try {
+                        surface2File("shot");
+                    } catch (IOException ex) {
+                        throw new RuntimeException("can not write survace to file", ex);
+                    }
                 }
             }
         }
@@ -71,7 +71,7 @@ public class Surface2File implements SurfaceUpdatedListener {
             return;
         }
 
-        File file = File.createTempFile(basename + shotNum + "-", ".ppm");
+        File file = File.createTempFile(basename + shotNum + "-", ".tga");
         readBufferUtil.write(file);
         System.err.println("Wrote: " + file.getAbsolutePath() + ", ...");
         shotNum++;
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/TestOffscreen02BitmapNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/TestOffscreen02BitmapNEWT.java
index e2ce78b..7898dda 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/TestOffscreen02BitmapNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/offscreen/TestOffscreen02BitmapNEWT.java
@@ -36,10 +36,7 @@ import com.jogamp.newt.Window;
 import com.jogamp.newt.event.MouseListener;
 import com.jogamp.newt.event.WindowListener;
 import com.jogamp.newt.opengl.GLWindow;
-import org.junit.AfterClass;
 import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 
 import javax.media.opengl.*;
@@ -54,35 +51,13 @@ import java.io.IOException;
  * hence it is possible to not have GLSL. 
  */
 public class TestOffscreen02BitmapNEWT extends UITestCase {
-    static GLProfile glpDefault;
-    static GLDrawableFactory glDrawableFactory;
-    static int width, height;
-    GLCapabilities capsDefault;
-
-    @BeforeClass
-    public static void initClass() {
-        glpDefault = GLProfile.getDefault();
-        Assert.assertNotNull(glpDefault);
-        glDrawableFactory = GLDrawableFactory.getFactory(glpDefault);
-        System.out.println("INFO: PBuffer supported: "+ glDrawableFactory.canCreateGLPbuffer(null));
-        width  = 640;
-        height = 480;
-    }
-
-    @AfterClass
-    public static void releaseClass() {
-    }
-
-    @Before
-    public void init() {
-        capsDefault = new GLCapabilities(glpDefault);
-        Assert.assertNotNull(capsDefault);
-    }
+    static final int width = 640, height = 480;
 
     @Test
     public void test11OffscreenWindowPixmap() {
-        // Offscreen doesn't work on >= GL3 (ATI)
-        GLProfile glp = GLProfile.get(GLProfile.GL2);
+        // we need to stay w/ generic profile GL2ES1 
+        // since software rasterizer might be required (pixmap/bitmap) 
+        GLProfile glp = GLProfile.get(GLProfile.GL2ES1);
         Assert.assertNotNull(glp);
         GLCapabilities caps = new GLCapabilities(glp);
         Assert.assertNotNull(caps);
@@ -124,8 +99,9 @@ public class TestOffscreen02BitmapNEWT extends UITestCase {
 
     @Test
     public void test14OffscreenSnapshotWithDemoPixmap() {
-        // Offscreen doesn't work on >= GL3 (ATI)
-        GLProfile glp = GLProfile.get(GLProfile.GL2);
+        // we need to stay w/ generic profile GL2ES1 
+        // since software rasterizer might be required (pixmap/bitmap) 
+        GLProfile glp = GLProfile.get(GLProfile.GL2ES1);
         Assert.assertNotNull(glp);
         GLCapabilities caps = new GLCapabilities(glp);
         Assert.assertNotNull(caps);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAWT01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAWT01GLn.java
index 6139d81..03fed5e 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAWT01GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAWT01GLn.java
@@ -31,14 +31,13 @@ package com.jogamp.opengl.test.junit.jogl.swt;
 import java.awt.Frame;
 import java.lang.reflect.InvocationTargetException;
 
-import javax.media.opengl.GL2;
+import javax.media.opengl.GL2ES1;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLEventListener;
 import javax.media.opengl.GLProfile;
 import javax.media.opengl.awt.GLCanvas;
 
-import jogamp.nativewindow.swt.SWTAccessor;
 
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.awt.SWT_AWT;
@@ -55,7 +54,8 @@ import org.junit.BeforeClass;
 import org.junit.After;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.OneTriangle;
+import com.jogamp.nativewindow.swt.SWTAccessor;
+import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 
 /**
@@ -75,7 +75,10 @@ public class TestSWTAWT01GLn extends UITestCase {
 
     @BeforeClass
     public static void startup() {
-        System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() );
+        System.out.println( "GLProfile " + GLProfile.glAvailabilityToString() );        
+        if(!GLProfile.isAvailable(GLProfile.GL2)) {
+            setTestSupported(false);
+        }
     }
 
     @Before
@@ -140,14 +143,14 @@ public class TestSWTAWT01GLn extends UITestCase {
             /* @Override */
             public void display( GLAutoDrawable glautodrawable ) {
                 Rectangle rectangle = new Rectangle( 0, 0, glautodrawable.getWidth(), glautodrawable.getHeight() );
-                GL2 gl = glautodrawable.getGL().getGL2();
+                GL2ES1 gl = glautodrawable.getGL().getGL2ES1();
                 OneTriangle.render( gl, rectangle.width, rectangle.height );
             }
 
             /* @Override */
             public void reshape( GLAutoDrawable glautodrawable, int x, int y, int width, int height ) {
                 Rectangle rectangle = new Rectangle( 0, 0, glautodrawable.getWidth(), glautodrawable.getHeight() );
-                GL2 gl = glautodrawable.getGL().getGL2();
+                GL2ES1 gl = glautodrawable.getGL().getGL2ES1();
                 OneTriangle.setup( gl, rectangle.width, rectangle.height );
             }
         });
@@ -181,16 +184,8 @@ public class TestSWTAWT01GLn extends UITestCase {
     }
 
     @Test
-    public void test01GLDefault() throws InterruptedException {
-        GLProfile glprofile = GLProfile.getDefault();
-        System.out.println( "GLProfile Default: " + glprofile );
-        runTestGL( glprofile );
-    }
-
-    @Test
-    public void test02GL2() throws InterruptedException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
+    public void test() throws InterruptedException {
+        GLProfile glprofile = GLProfile.getGL2ES1();
         runTestGL( glprofile );
     }
 
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT02GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java
similarity index 91%
rename from src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT02GLn.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java
index b8e45df..0c35025 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT02GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTAccessor02GLn.java
@@ -28,7 +28,7 @@
  
 package com.jogamp.opengl.test.junit.jogl.swt;
 
-import javax.media.opengl.GL2;
+import javax.media.opengl.GL2ES1;
 import javax.media.opengl.GLContext;
 import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLProfile;
@@ -51,20 +51,23 @@ import org.junit.BeforeClass;
 import org.junit.After;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.OneTriangle;
+import com.jogamp.nativewindow.swt.SWTAccessor;
+import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import javax.media.nativewindow.AbstractGraphicsDevice;
 import javax.media.nativewindow.ProxySurface;
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLDrawable;
-import jogamp.nativewindow.swt.SWTAccessor;
 import org.eclipse.swt.widgets.Canvas;
 
 /**
- * Tests that a basic SWT app can open without crashing under different GL profiles. Uses the SWT GL canvas.
- * @author Wade Walker
+ * Tests that a basic SWT app can open without crashing under different GL profiles. 
+ * <p> 
+ * Uses JOGL's SWTAccessor only.
+ * </p>
+ * @author Wade Walker, et.al.
  */
-public class TestSWT02GLn extends UITestCase {
+public class TestSWTAccessor02GLn extends UITestCase {
 
     static int duration = 250;
 
@@ -176,7 +179,7 @@ public class TestSWT02GLn extends UITestCase {
                 boolean glok=false;
                 if( GLContext.CONTEXT_NOT_CURRENT < glcontext.makeCurrent() ) {
                     glok=true;
-                    GL2 gl = glcontext.getGL().getGL2();
+                    GL2ES1 gl = glcontext.getGL().getGL2ES1();
                     OneTriangle.setup( gl, rectangle.width, rectangle.height );
                     glcontext.release();
                 } else {
@@ -193,7 +196,7 @@ public class TestSWT02GLn extends UITestCase {
                 boolean glok=false;
                 if( GLContext.CONTEXT_NOT_CURRENT < glcontext.makeCurrent() ) {
                     glok=true;
-                    GL2 gl = glcontext.getGL().getGL2();
+                    GL2ES1 gl = glcontext.getGL().getGL2ES1();
                     if(sizeMissing[0]) {
                         OneTriangle.setup( gl, rectangle.width, rectangle.height);
                         sizeMissing[0] = false;
@@ -229,16 +232,8 @@ public class TestSWT02GLn extends UITestCase {
     }
 
     @Test
-    public void testA01GLDefault() throws InterruptedException {
-        GLProfile glprofile = GLProfile.getDefault();
-        System.out.println( "GLProfile Default: " + glprofile );
-        runTestAGL( glprofile );
-    }
-
-    @Test
-    public void test02GL2() throws InterruptedException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
+    public void test() throws InterruptedException {
+        GLProfile glprofile = GLProfile.getGL2ES1();
         runTestAGL( glprofile );
     }
 
@@ -257,6 +252,6 @@ public class TestSWT02GLn extends UITestCase {
             }
         }
         System.out.println("durationPerTest: "+duration);
-        org.junit.runner.JUnitCore.main(TestSWT02GLn.class.getName());
+        org.junit.runner.JUnitCore.main(TestSWTAccessor02GLn.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java
similarity index 86%
copy from src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java
copy to src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java
index d302c39..ce3100a 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTEclipseGLCanvas01GLn.java
@@ -28,7 +28,7 @@
  
 package com.jogamp.opengl.test.junit.jogl.swt;
 
-import javax.media.opengl.GL2;
+import javax.media.opengl.GL2ES1;
 import javax.media.opengl.GLContext;
 import javax.media.opengl.GLDrawableFactory;
 import javax.media.opengl.GLProfile;
@@ -53,14 +53,17 @@ import org.junit.BeforeClass;
 import org.junit.After;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.OneTriangle;
+import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 
 /**
- * Tests that a basic SWT app can open without crashing under different GL profiles. Uses the SWT GL canvas.
- * @author Wade Walker
+ * Tests that a basic SWT app can open without crashing under different GL profiles.
+ * <p> 
+ * Uses the SWT GLCanvas <code>org.eclipse.swt.opengl.GLCanvas</code>.
+ * </p>
+ * @author Wade Walker, et.al.
  */
-public class TestSWT01GLn extends UITestCase {
+public class TestSWTEclipseGLCanvas01GLn extends UITestCase {
 
     static int duration = 250;
 
@@ -124,7 +127,7 @@ public class TestSWT01GLn extends UITestCase {
                 Rectangle rectangle = glcanvas.getClientArea();
                 glcanvas.setCurrent();
                 glcontext.makeCurrent();
-                GL2 gl = glcontext.getGL().getGL2();
+                GL2ES1 gl = glcontext.getGL().getGL2ES1();
                 OneTriangle.setup( gl, rectangle.width, rectangle.height );
                 glcontext.release();
                 System.err.println("resize");
@@ -137,7 +140,7 @@ public class TestSWT01GLn extends UITestCase {
                 Rectangle rectangle = glcanvas.getClientArea();
                 glcanvas.setCurrent();
                 glcontext.makeCurrent();
-                GL2 gl = glcontext.getGL().getGL2();
+                GL2ES1 gl = glcontext.getGL().getGL2ES1();
                 OneTriangle.render( gl, rectangle.width, rectangle.height );
                 glcanvas.swapBuffers();
                 glcontext.release();
@@ -166,16 +169,8 @@ public class TestSWT01GLn extends UITestCase {
     }
 
     @Test
-    public void testA01GLDefault() throws InterruptedException {
-        GLProfile glprofile = GLProfile.getDefault();
-        System.out.println( "GLProfile Default: " + glprofile );
-        runTestAGL( glprofile );
-    }
-
-    @Test
-    public void test02GL2() throws InterruptedException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
+    public void test() throws InterruptedException {
+        GLProfile glprofile = GLProfile.getGL2ES1();
         runTestAGL( glprofile );
     }
 
@@ -194,6 +189,6 @@ public class TestSWT01GLn extends UITestCase {
             }
         }
         System.out.println("durationPerTest: "+duration);
-        org.junit.runner.JUnitCore.main(TestSWT01GLn.class.getName());
+        org.junit.runner.JUnitCore.main(TestSWTEclipseGLCanvas01GLn.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLnAWT.java
similarity index 61%
rename from src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java
rename to src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLnAWT.java
index d302c39..f7e839c 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWT01GLn.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/swt/TestSWTJOGLGLCanvas01GLnAWT.java
@@ -28,22 +28,16 @@
  
 package com.jogamp.opengl.test.junit.jogl.swt;
 
-import javax.media.opengl.GL2;
-import javax.media.opengl.GLContext;
-import javax.media.opengl.GLDrawableFactory;
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLCapabilitiesImmutable;
+import javax.media.opengl.GLEventListener;
 import javax.media.opengl.GLProfile;
 
 import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.Rectangle;
 import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.opengl.GLCanvas;
-import org.eclipse.swt.opengl.GLData;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
 import org.eclipse.swt.widgets.Shell;
 
 import org.junit.Assert;
@@ -53,14 +47,22 @@ import org.junit.BeforeClass;
 import org.junit.After;
 import org.junit.Test;
 
-import com.jogamp.opengl.test.junit.jogl.demos.gl2.OneTriangle;
+import com.jogamp.opengl.swt.GLCanvas;
+import com.jogamp.opengl.test.junit.jogl.demos.es1.OneTriangle;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 
 /**
- * Tests that a basic SWT app can open without crashing under different GL profiles. Uses the SWT GL canvas.
- * @author Wade Walker
+ * Tests that a basic SWT app can open without crashing under different GL profiles.
+ * <p> 
+ * Uses JOGL's new SWT GLCanvas.
+ * </p>
+ * <p>
+ * Holds AWT in it's test name, since our impl. still needs the AWT threading, 
+ * see {@link GLCanvas}.
+ * </p>
+ * @author Wade Walker, et.al.
  */
-public class TestSWT01GLn extends UITestCase {
+public class TestSWTJOGLGLCanvas01GLnAWT extends UITestCase {
 
     static int duration = 250;
 
@@ -108,43 +110,24 @@ public class TestSWT01GLn extends UITestCase {
     }
 
     protected void runTestAGL( GLProfile glprofile ) throws InterruptedException {
-        GLData gldata = new GLData();
-        gldata.doubleBuffer = true;
         // need SWT.NO_BACKGROUND to prevent SWT from clearing the window
         // at the wrong times (we use glClear for this instead)
-        final GLCanvas glcanvas = new GLCanvas( composite, SWT.NO_BACKGROUND, gldata );
-        Assert.assertNotNull( glcanvas );
-        glcanvas.setCurrent();
-        final GLContext glcontext = GLDrawableFactory.getFactory( glprofile ).createExternalGLContext();
-        Assert.assertNotNull( glcontext );
-
-        // fix the viewport when the user resizes the window
-        glcanvas.addListener( SWT.Resize, new Listener() {
-            public void handleEvent( Event event ) {
-                Rectangle rectangle = glcanvas.getClientArea();
-                glcanvas.setCurrent();
-                glcontext.makeCurrent();
-                GL2 gl = glcontext.getGL().getGL2();
-                OneTriangle.setup( gl, rectangle.width, rectangle.height );
-                glcontext.release();
-                System.err.println("resize");
-            }
-        });
-
-        // draw the triangle when the OS tells us that any part of the window needs drawing
-        glcanvas.addPaintListener( new PaintListener() {
-            public void paintControl( PaintEvent paintevent ) {
-                Rectangle rectangle = glcanvas.getClientArea();
-                glcanvas.setCurrent();
-                glcontext.makeCurrent();
-                GL2 gl = glcontext.getGL().getGL2();
-                OneTriangle.render( gl, rectangle.width, rectangle.height );
-                glcanvas.swapBuffers();
-                glcontext.release();
-                System.err.println("paint");
-            }
-        });
+        final GLCapabilitiesImmutable caps = new GLCapabilities( glprofile );
         
+        final GLCanvas canvas = new GLCanvas( composite, SWT.NO_BACKGROUND, caps, null, null);
+        Assert.assertNotNull( canvas );
+
+        canvas.addGLEventListener(new GLEventListener() {
+           public void init(final GLAutoDrawable drawable) { }
+           public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) {
+                OneTriangle.setup( drawable.getGL().getGL2(), width, height );
+           }                 
+           public void display(final GLAutoDrawable drawable) {
+                OneTriangle.render( drawable.getGL().getGL2(), drawable.getWidth(), drawable.getHeight());
+           }
+           public void dispose(final GLAutoDrawable drawable) {}         
+        });
+       
         shell.setText( getClass().getName() );
         shell.setSize( 640, 480 );
         shell.open();
@@ -152,7 +135,7 @@ public class TestSWT01GLn extends UITestCase {
         long lStartTime = System.currentTimeMillis();
         long lEndTime = lStartTime + duration;
         try {
-            while( (System.currentTimeMillis() < lEndTime) && !glcanvas.isDisposed() ) {
+            while( (System.currentTimeMillis() < lEndTime) && !canvas.isDisposed() ) {
                 if( !display.readAndDispatch() ) {
                     // blocks on linux .. display.sleep();
                     Thread.sleep(10);
@@ -162,20 +145,12 @@ public class TestSWT01GLn extends UITestCase {
             throwable.printStackTrace();
             Assume.assumeNoException( throwable );
         }
-        glcanvas.dispose();
-    }
-
-    @Test
-    public void testA01GLDefault() throws InterruptedException {
-        GLProfile glprofile = GLProfile.getDefault();
-        System.out.println( "GLProfile Default: " + glprofile );
-        runTestAGL( glprofile );
+        canvas.dispose();
     }
 
     @Test
-    public void test02GL2() throws InterruptedException {
-        GLProfile glprofile = GLProfile.get(GLProfile.GL2);
-        System.out.println( "GLProfile GL2: " + glprofile );
+    public void test() throws InterruptedException {
+        GLProfile glprofile = GLProfile.getGL2ES1();
         runTestAGL( glprofile );
     }
 
@@ -194,6 +169,6 @@ public class TestSWT01GLn extends UITestCase {
             }
         }
         System.out.println("durationPerTest: "+duration);
-        org.junit.runner.JUnitCore.main(TestSWT01GLn.class.getName());
+        org.junit.runner.JUnitCore.main(TestSWTJOGLGLCanvas01GLnAWT.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestGrayTextureFromFileAWTBug417.java b/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestGrayTextureFromFileAWTBug417.java
index 8f38ac6..d43a3a0 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestGrayTextureFromFileAWTBug417.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestGrayTextureFromFileAWTBug417.java
@@ -65,7 +65,11 @@ public class TestGrayTextureFromFileAWTBug417 extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.get(GLProfile.GL2GL3);
+        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+            UITestCase.setTestSupported(false);
+            return;
+        }
+        glp = GLProfile.getGL2GL3();
         Assert.assertNotNull(glp);
         caps = new GLCapabilities(glp);
         Assert.assertNotNull(caps);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestTexture01AWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestTexture01AWT.java
index 4905764..217b8ac 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestTexture01AWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/texture/TestTexture01AWT.java
@@ -61,7 +61,11 @@ public class TestTexture01AWT extends UITestCase {
 
     @BeforeClass
     public static void initClass() {
-        glp = GLProfile.get(GLProfile.GL2GL3);
+        if(!GLProfile.isAvailable(GLProfile.GL2GL3)) {
+            UITestCase.setTestSupported(false);
+            return;
+        }
+        glp = GLProfile.getGL2GL3();
         Assert.assertNotNull(glp);
         caps = new GLCapabilities(glp);
         Assert.assertNotNull(caps);
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite01NEWT.java
similarity index 50%
copy from src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java
copy to src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite01NEWT.java
index 05f122b..ab8e542 100644
--- a/src/test/com/jogamp/opengl/test/junit/jogl/acore/TestNVSwapGroupNEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite01NEWT.java
@@ -26,17 +26,17 @@
  * or implied, of JogAmp Community.
  */
  
-package com.jogamp.opengl.test.junit.jogl.acore;
+package com.jogamp.opengl.test.junit.jogl.util;
+
+import java.io.File;
 
 import com.jogamp.newt.opengl.GLWindow;
 
-import javax.media.nativewindow.util.InsetsImmutable;
 import javax.media.opengl.GLAutoDrawable;
 import javax.media.opengl.GLCapabilities;
-import javax.media.opengl.GLContext;
 import javax.media.opengl.GLEventListener;
 import javax.media.opengl.GLProfile;
-import com.jogamp.opengl.util.Animator;
+import com.jogamp.opengl.util.GLReadBufferUtil;
 
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
@@ -45,7 +45,7 @@ import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
 
-public class TestNVSwapGroupNEWT extends UITestCase {
+public class TestGLReadBufferUtilTextureIOWrite01NEWT extends UITestCase {
     static GLProfile glp;
     static GLCapabilities caps;
     static int width, height;
@@ -60,80 +60,41 @@ public class TestNVSwapGroupNEWT extends UITestCase {
         height = 256;
     }
 
-    protected GLWindow runTestGL(Animator animator, int x, int y, final int group, final int barrier) {
+    protected void snapshot(GLAutoDrawable drawable, boolean alpha, boolean flip, String filename) {
+        GLReadBufferUtil screenshot = new GLReadBufferUtil(alpha, false);
+        if(screenshot.readPixels(drawable.getGL(), drawable, flip)) {
+            screenshot.write(new File(filename));
+        }                
+    }
+    
+    @Test
+    public void testWritePNG_TGA_PAM() throws InterruptedException {
         GLWindow glWindow = GLWindow.create(caps);
         Assert.assertNotNull(glWindow);
-        glWindow.setTitle("Shared Gears NEWT Test: "+x+"/"+y);
-
+        glWindow.setTitle("Shared Gears NEWT Test");
         glWindow.setSize(width, height);
-
-        GearsES2 gears = new GearsES2(1);
+        glWindow.addGLEventListener(new GearsES2(1));
         glWindow.addGLEventListener(new GLEventListener() {
-            public void init(GLAutoDrawable drawable) {
-                int[] maxVals = new int[] { -1, -1 } ;
-                GLContext glc = drawable.getContext();
-                boolean r = glc.queryMaxSwapGroups(maxVals, 0, maxVals, 1);
-                System.err.println("swap group max groups "+maxVals[0]+", barriers "+maxVals[0]+", "+r);
-                if(maxVals[0]>=group) {
-                    System.err.println("swap group joing 1: "+glc.joinSwapGroup(group));
-                    if(maxVals[1]>=barrier) {
-                        System.err.println("swap group bind 1-1: "+glc.bindSwapBarrier(group, barrier));
-                    }
-                }                
-            }
+            public void init(GLAutoDrawable drawable) {}
             public void dispose(GLAutoDrawable drawable) {}
-            public void display(GLAutoDrawable drawable) {}
+            public void display(GLAutoDrawable drawable) {
+                // snapshot(drawable, false, true,  getSimpleTestName(".")+"-rgb_-"+drawable.getGLProfile().getName()+".ppm");
+                snapshot(drawable, true,  false, getSimpleTestName(".")+"-rgba-"+drawable.getGLProfile().getName()+".png");
+                snapshot(drawable, true,  false, getSimpleTestName(".")+"-rgba-"+drawable.getGLProfile().getName()+".tga");
+                snapshot(drawable, true,  true,  getSimpleTestName(".")+"-rgba-"+drawable.getGLProfile().getName()+".pam");
+                snapshot(drawable, false, false, getSimpleTestName(".")+"-rgb_-"+drawable.getGLProfile().getName()+".png");
+                snapshot(drawable, false, false, getSimpleTestName(".")+"-rgb_-"+drawable.getGLProfile().getName()+".tga");
+                snapshot(drawable, false, true,  getSimpleTestName(".")+"-rgb_-"+drawable.getGLProfile().getName()+".pam");
+            }
             public void reshape(GLAutoDrawable drawable, int x, int y,
-                    int width, int height) {}
+                    int width, int height) { }
         });
-        glWindow.addGLEventListener(gears);
-
-        animator.add(glWindow);
-
         glWindow.setVisible(true);
-
-        /** insets (if supported) are available only if window is set visible and hence is created */
-        glWindow.setTopLevelPosition(x, y);
-
-        return glWindow;
+        Thread.sleep(60);
+        glWindow.destroy();        
     }
 
-    /** NV swap group is currently disabled .. needs more testing */
-    @Test
-    public void test01() throws InterruptedException {
-        // make sure it won't be active for now !
-        int swap_group = 9999; 
-        int swap_barrier = 9999; 
-        
-        Animator animator = new Animator();
-        GLWindow f1 = runTestGL(animator, 0, 0, swap_group, swap_barrier);
-        InsetsImmutable insets = f1.getInsets();
-        GLWindow f2 = runTestGL(animator, width+insets.getTotalWidth(), 0, swap_group, swap_barrier);
-        animator.setUpdateFPSFrames(1, null);        
-        animator.start();
-        while(animator.isAnimating() && animator.getTotalFPSDuration()<duration) {
-            Thread.sleep(100);
-        }
-        animator.stop();
-
-        f1.destroy();
-        f2.destroy();
-
-        // see above ..
-        // releaseShared();
-    }
-
-    static long duration = 500; // ms
-
     public static void main(String args[]) {
-        for(int i=0; i<args.length; i++) {
-            if(args[i].equals("-time")) {
-                i++;
-                try {
-                    duration = Integer.parseInt(args[i]);
-                } catch (Exception ex) { ex.printStackTrace(); }
-            }
-        }
-        org.junit.runner.JUnitCore.main(TestNVSwapGroupNEWT.class.getName());
+        org.junit.runner.JUnitCore.main(TestGLReadBufferUtilTextureIOWrite01NEWT.class.getName());
     }
 }
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite02NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite02NEWT.java
new file mode 100644
index 0000000..79ae316
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestGLReadBufferUtilTextureIOWrite02NEWT.java
@@ -0,0 +1,146 @@
+/**
+ * Copyright 2011 JogAmp Community. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met:
+ * 
+ *    1. Redistributions of source code must retain the above copyright notice, this list of
+ *       conditions and the following disclaimer.
+ * 
+ *    2. Redistributions in binary form must reproduce the above copyright notice, this list
+ *       of conditions and the following disclaimer in the documentation and/or other materials
+ *       provided with the distribution.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * The views and conclusions contained in the software and documentation are those of the
+ * authors and should not be interpreted as representing official policies, either expressed
+ * or implied, of JogAmp Community.
+ */
+ 
+package com.jogamp.opengl.test.junit.jogl.util;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import com.jogamp.newt.opengl.GLWindow;
+
+import javax.media.opengl.GLAutoDrawable;
+import javax.media.opengl.GLCapabilities;
+import javax.media.opengl.GLEventListener;
+import javax.media.opengl.GLProfile;
+import com.jogamp.opengl.util.GLReadBufferUtil;
+
+import com.jogamp.opengl.test.junit.util.UITestCase;
+import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class TestGLReadBufferUtilTextureIOWrite02NEWT extends UITestCase {
+    static GLProfile glp;
+    static GLCapabilities caps;
+    static int width, height;
+
+    @BeforeClass
+    public static void initClass() {
+        glp = GLProfile.getDefault();
+        Assert.assertNotNull(glp);
+        caps = new GLCapabilities(glp);
+        Assert.assertNotNull(caps);
+        width  = 256;
+        height = 256;
+    }
+
+    protected void snapshot(GLAutoDrawable drawable, GLReadBufferUtil screenshot, String filename) {
+        if(screenshot.readPixels(drawable.getGL(), drawable, false)) {
+            screenshot.write(new File(filename));
+        }                
+    }
+    
+    @Test
+    public void testWriteTGAWithResize() throws InterruptedException {
+        final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false);
+        GLWindow glWindow = GLWindow.create(caps);
+        Assert.assertNotNull(glWindow);
+        glWindow.setTitle("Shared Gears NEWT Test");
+        glWindow.setSize(width, height);
+        glWindow.addGLEventListener(new GearsES2(1));
+        glWindow.addGLEventListener(new GLEventListener() {
+            int i=0;
+            public void init(GLAutoDrawable drawable) {}
+            public void dispose(GLAutoDrawable drawable) {}
+            public void display(GLAutoDrawable drawable) {
+                StringWriter filename = new StringWriter();
+                {
+                    PrintWriter pw = new PrintWriter(filename);
+                    pw.printf("%s-rgba-%s-%03dx%03d-n%03d.tga", 
+                            getSimpleTestName("."), drawable.getGLProfile().getName(), 
+                            drawable.getWidth(), drawable.getHeight(), i++);
+                }
+                if(screenshot.readPixels(drawable.getGL(), drawable, false)) {
+                    screenshot.write(new File(filename.toString()));
+                }                
+            }
+            public void reshape(GLAutoDrawable drawable, int x, int y,
+                    int width, int height) { }
+        });
+        glWindow.setVisible(true);
+        Thread.sleep(60);
+        glWindow.setSize(300, 300);
+        Thread.sleep(60);
+        glWindow.setSize(400, 400);
+        Thread.sleep(60);
+        glWindow.destroy();
+    }
+
+    @Test
+    public void testWritePNGWithResize() throws InterruptedException {
+        final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false);
+        GLWindow glWindow = GLWindow.create(caps);
+        Assert.assertNotNull(glWindow);
+        glWindow.setTitle("Shared Gears NEWT Test");
+        glWindow.setSize(width, height);
+        glWindow.addGLEventListener(new GearsES2(1));
+        glWindow.addGLEventListener(new GLEventListener() {
+            int i=0;
+            public void init(GLAutoDrawable drawable) {}
+            public void dispose(GLAutoDrawable drawable) {}
+            public void display(GLAutoDrawable drawable) {
+                StringWriter filename = new StringWriter();
+                {
+                    PrintWriter pw = new PrintWriter(filename);
+                    pw.printf("%s-rgba-%s-%03dx%03d-n%03d.png", 
+                            getSimpleTestName("."), drawable.getGLProfile().getName(), 
+                            drawable.getWidth(), drawable.getHeight(), i++);
+                }
+                if(screenshot.readPixels(drawable.getGL(), drawable, false)) {
+                    screenshot.write(new File(filename.toString()));
+                }                
+            }
+            public void reshape(GLAutoDrawable drawable, int x, int y,
+                    int width, int height) { }
+        });
+        glWindow.setVisible(true);
+        Thread.sleep(60);
+        glWindow.setSize(300, 300);
+        Thread.sleep(60);
+        glWindow.setSize(400, 400);
+        Thread.sleep(60);
+        glWindow.destroy();
+    }
+
+    public static void main(String args[]) {
+        org.junit.runner.JUnitCore.main(TestGLReadBufferUtilTextureIOWrite02NEWT.class.getName());
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/jogl/util/TestPNGImage01NEWT.java b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestPNGImage01NEWT.java
new file mode 100644
index 0000000..5a0c18d
--- /dev/null
+++ b/src/test/com/jogamp/opengl/test/junit/jogl/util/TestPNGImage01NEWT.java
@@ -0,0 +1,41 @@
+package com.jogamp.opengl.test.junit.jogl.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URLConnection;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.jogamp.common.util.IOUtil;
+import com.jogamp.opengl.test.junit.util.UITestCase;
+import com.jogamp.opengl.util.texture.spi.PNGImage;
+
+public class TestPNGImage01NEWT extends UITestCase {
+    @Test
+    public void testPNGReadWriteAndCompare() throws InterruptedException, IOException, MalformedURLException {
+        final File out1_f=new File(getSimpleTestName(".")+"-PNGImageTest1.png");
+        final File out2_f=new File(getSimpleTestName(".")+"-PNGImageTest2.png");
+        final String url_s="jogl/util/data/av/test-ntsc01-160x90.png";
+        URLConnection urlConn = IOUtil.getResource(url_s, PNGImage.class.getClassLoader());
+        PNGImage image0 = PNGImage.read(urlConn.getInputStream());
+        System.err.println("PNGImage - Orig: "+image0);        
+        image0.write(out1_f, true); 
+        {
+            Assert.assertEquals(image0.getData(), PNGImage.read(IOUtil.toURL(out1_f).openStream()).getData());
+        }
+        
+        final PNGImage image1 = PNGImage.createFromData(image0.getWidth(), image0.getHeight(), 
+                                                        image0.getDpi()[0], image0.getDpi()[1], 
+                                                        image0.getBytesPerPixel(), false, image0.getData());
+        image1.write(out2_f, true);
+        {
+            Assert.assertEquals(image0.getData(), PNGImage.read(IOUtil.toURL(out2_f).openStream()).getData());
+        }                
+    }
+    
+    public static void main(String args[]) {
+        org.junit.runner.JUnitCore.main(TestPNGImage01NEWT.class.getName());
+    }
+}
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestEventSourceNotAWTBug.java b/src/test/com/jogamp/opengl/test/junit/newt/TestEventSourceNotAWTBug.java
index 7956e22..ecf0ada 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestEventSourceNotAWTBug.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestEventSourceNotAWTBug.java
@@ -60,7 +60,7 @@ public class TestEventSourceNotAWTBug extends UITestCase {
 
         jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
-        final GLCapabilities caps = new GLCapabilities(GLProfile.getDefault());
+        final GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2());
         final GLWindow glWindow = GLWindow.create(caps);
         final NewtCanvasAWT canvas = new NewtCanvasAWT(glWindow);
         jf.getContentPane().add(canvas);
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus01SwingAWTRobot.java b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus01SwingAWTRobot.java
index fe7fef0..bb67e77 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus01SwingAWTRobot.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus01SwingAWTRobot.java
@@ -35,7 +35,6 @@ import org.junit.Assume;
 import java.awt.AWTException;
 import java.awt.BorderLayout;
 import java.awt.Button;
-import java.awt.Color;
 import java.awt.Robot;
 import java.lang.reflect.InvocationTargetException;
 
@@ -132,7 +131,10 @@ public class TestFocus01SwingAWTRobot extends UITestCase {
             public void run() {
                 frame1.setVisible(true);
             } } );
-        Assert.assertTrue(AWTRobotUtil.toFront(robot, frame1));
+        Assert.assertEquals(true,  AWTRobotUtil.waitForVisible(frame1, true));
+        Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glWindow1, true));        
+        AWTRobotUtil.clearAWTFocus(robot);
+        Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, frame1));
 
         Thread.sleep(durationPerTest); // manual testing
         
@@ -145,7 +147,6 @@ public class TestFocus01SwingAWTRobot extends UITestCase {
         // Continuous animation ..
         Animator animator = new Animator(glWindow1);
         animator.start();
-        AWTRobotUtil.assertRequestFocusAndWait(robot, frame1, frame1, frame1FA, null);
 
         // Button Focus
         Thread.sleep(100); // allow event sync
@@ -153,9 +154,6 @@ public class TestFocus01SwingAWTRobot extends UITestCase {
         System.err.println("FOCUS AWT  Button request");
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, button, button, buttonFA, frame1FA);
-        Assert.assertEquals(true,  buttonFA.focusGained());
-        Assert.assertEquals(false, frame1FA.focusGained());
-        Assert.assertEquals(true,  frame1FA.focusLost());
         Assert.assertEquals(false, glWindow1FA.focusGained());
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         System.err.println("FOCUS AWT  Button sync");
@@ -166,9 +164,6 @@ public class TestFocus01SwingAWTRobot extends UITestCase {
         System.err.println("FOCUS NEWT Canvas/GLWindow request");
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonFA);
-        Assert.assertEquals(true,  glWindow1FA.focusGained());
-        Assert.assertEquals(false, buttonFA.focusGained());
-        Assert.assertEquals(true,  buttonFA.focusLost());
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         System.err.println("FOCUS NEWT Canvas/GLWindow sync");
         AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
index b9eb748..a0efa53 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
@@ -156,7 +156,10 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
             public void run() {
                 jFrame1.setVisible(true);
             } } );
-        Assert.assertTrue(AWTRobotUtil.toFront(robot, jFrame1));
+        Assert.assertEquals(true,  AWTRobotUtil.waitForVisible(jFrame1, true));
+        Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glWindow1, true));                
+        AWTRobotUtil.clearAWTFocus(robot);
+        Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1));
 
         int wait=0;
         while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; }
@@ -167,7 +170,6 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
         // Continuous animation ..
         Animator animator1 = new Animator(glWindow1);
         animator1.start();
-        AWTRobotUtil.assertRequestFocusAndWait(robot, jFrame1, jFrame1, jFrame1FA, null);
 
         Thread.sleep(durationPerTest); // manual testing
         
@@ -176,13 +178,9 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
         System.err.println("FOCUS AWT  Button Outer request");
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, jFrame1FA);
-        Assert.assertEquals(true,  buttonNorthOuterFA.focusGained());
-        Assert.assertEquals(false, jFrame1FA.focusGained());
-        Assert.assertEquals(true,  jFrame1FA.focusLost());
         Assert.assertEquals(false, glWindow1FA.focusGained());
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
-        Assert.assertEquals(false, jFrame1FA.focusGained());
         System.err.println("FOCUS AWT  Button Outer sync");
         AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA);
         AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1, 
@@ -195,12 +193,8 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
         System.err.println("FOCUS NEWT Canvas/GLWindow request");
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA);
-        Assert.assertEquals(true,  glWindow1FA.focusGained());
-        Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
-        Assert.assertEquals(true,  buttonNorthOuterFA.focusLost());        
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
-        Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
         Assert.assertEquals(false, jFrame1FA.focusGained());
         System.err.println("FOCUS NEWT Canvas/GLWindow sync");
         AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
@@ -216,9 +210,6 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
         System.err.println("FOCUS AWT  Button request");
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA);
-        Assert.assertEquals(true,  buttonNorthInnerFA.focusGained());
-        Assert.assertEquals(false, glWindow1FA.focusGained());
-        Assert.assertEquals(true,  glWindow1FA.focusLost());        
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
         Assert.assertEquals(false, jFrame1FA.focusGained());
@@ -235,9 +226,6 @@ public class TestFocus02SwingAWTRobot extends UITestCase {
         EventCountAdapterUtil.reset(eventCountAdapters);
         AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA);
         Assert.assertTrue(AWTRobotUtil.waitForFocusCount(false, newtCanvasAWTFA));
-        Assert.assertEquals(true,  glWindow1FA.focusGained());
-        Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
-        Assert.assertEquals(true,  buttonNorthInnerFA.focusLost());
         Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
         Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
         Assert.assertEquals(false, jFrame1FA.focusGained());
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java
index 985affa..a5b7a76 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode00NEWT.java
@@ -35,21 +35,21 @@ import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
 
+import com.jogamp.newt.Display;
 import com.jogamp.newt.NewtFactory;
 import com.jogamp.newt.Screen;
-import com.jogamp.newt.Window;
 import com.jogamp.newt.ScreenMode;
 import com.jogamp.newt.util.MonitorMode;
 import com.jogamp.newt.util.ScreenModeUtil;
 import com.jogamp.opengl.test.junit.util.UITestCase;
 import java.util.Iterator;
 import java.util.List;
-import javax.media.nativewindow.Capabilities;
 import javax.media.nativewindow.util.Dimension;
 import javax.media.nativewindow.util.DimensionImmutable;
 import javax.media.nativewindow.util.SurfaceSize;
 
 public class TestScreenMode00NEWT extends UITestCase {
+    static int screenIdx = 0;
     static int width, height;
     
     static int waitTimeShort = 4; //1 sec
@@ -95,12 +95,12 @@ public class TestScreenMode00NEWT extends UITestCase {
 
     @Test
     public void testScreenModeInfo01() throws InterruptedException {
-        Capabilities caps = new Capabilities();
-        Window window = NewtFactory.createWindow(caps);
-        window.setSize(width, height);
-        window.setVisible(true);
-
-        Screen screen = window.getScreen();
+        Display dpy = NewtFactory.createDisplay(null);
+        Screen screen = NewtFactory.createScreen(dpy, screenIdx);
+        screen.addReference();
+        Assert.assertEquals(true,screen.isNativeValid());
+        Assert.assertEquals(true,screen.getDisplay().isNativeValid());
+        System.err.println("Screen: "+screen.toString());
 
         List<ScreenMode> screenModes = screen.getScreenModes();
         Assert.assertTrue(screenModes.size()>0);
@@ -116,18 +116,26 @@ public class TestScreenMode00NEWT extends UITestCase {
         System.err.println("curr SM: "+sm_c);
         System.err.println("curr sz: "+screen.getWidth()+"x"+screen.getHeight());
         Assert.assertEquals(sm_o, sm_c);
-        Assert.assertEquals(sm_c.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(sm_c.getRotatedHeight(), screen.getHeight());
 
-        window.destroy();
+        screen.removeReference();
 
-        Assert.assertEquals(false,window.isVisible());
-        Assert.assertEquals(false,window.isNativeValid());
         Assert.assertEquals(false,screen.isNativeValid());
         Assert.assertEquals(false,screen.getDisplay().isNativeValid());
     }
 
+    static int atoi(String a) {
+        try {
+            return Integer.parseInt(a);
+        } catch (Exception ex) { throw new RuntimeException(ex); }
+    }
+    
     public static void main(String args[]) throws IOException {
+        for(int i=0; i<args.length; i++) {
+            if(args[i].equals("-screen")) {
+                i++;
+                screenIdx = atoi(args[i]);
+            }
+        }
         String tstname = TestScreenMode00NEWT.class.getName();
         org.junit.runner.JUnitCore.main(tstname);
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java
index b05b5ad..c3c68e4 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestScreenMode01NEWT.java
@@ -200,8 +200,6 @@ public class TestScreenMode01NEWT extends UITestCase {
         Assert.assertNotNull(smOrig);
         Assert.assertEquals(smCurrent, smOrig);
         System.err.println("[0] current/orig: "+smCurrent);
-        Assert.assertEquals(smCurrent.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(smCurrent.getRotatedHeight(), screen.getHeight());
 
         screenModes = ScreenModeUtil.filterByRate(screenModes, smOrig.getMonitorMode().getRefreshRate());
         Assert.assertNotNull(screenModes);
@@ -222,8 +220,6 @@ public class TestScreenMode01NEWT extends UITestCase {
         screen.setCurrentScreenMode(sm);
         Assert.assertEquals(sm, screen.getCurrentScreenMode());
         Assert.assertNotSame(smOrig, screen.getCurrentScreenMode());
-        Assert.assertEquals(sm.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(sm.getRotatedHeight(), screen.getHeight());
 
         Thread.sleep(waitTimeLong);
 
@@ -253,8 +249,6 @@ public class TestScreenMode01NEWT extends UITestCase {
 
         Assert.assertNotNull(smCurrent);
         Assert.assertEquals(smCurrent, smOrig);
-        Assert.assertEquals(smCurrent.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(smCurrent.getRotatedHeight(), screen.getHeight());
 
         screen.destroy();
 
@@ -288,8 +282,6 @@ public class TestScreenMode01NEWT extends UITestCase {
         Assert.assertNotNull(smOrig);
         Assert.assertEquals(smCurrent, smOrig);
         System.err.println("[0] current/orig: "+smCurrent);
-        Assert.assertEquals(smCurrent.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(smCurrent.getRotatedHeight(), screen.getHeight());
         
         List<ScreenMode> screenModes = screen.getScreenModes();
         if(screenModes.size()==1) {
@@ -316,8 +308,6 @@ public class TestScreenMode01NEWT extends UITestCase {
 
         System.err.println("[0] set current: "+screenMode);
         screen.setCurrentScreenMode(screenMode);
-        Assert.assertEquals(screenMode.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(screenMode.getRotatedHeight(), screen.getHeight());
         
         if(!preFS) {
             System.err.println("[0] set FS post 0: "+window.isFullscreen());
@@ -354,8 +344,6 @@ public class TestScreenMode01NEWT extends UITestCase {
 
         Assert.assertNotNull(smCurrent);
         Assert.assertEquals(smCurrent, smOrig);
-        Assert.assertEquals(smCurrent.getRotatedWidth(), screen.getWidth());
-        Assert.assertEquals(smCurrent.getRotatedHeight(), screen.getHeight());
 
         screen.destroy();
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol01AWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol01AWT.java
index be824c2..d63f0d2 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol01AWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol01AWT.java
@@ -36,7 +36,7 @@ import java.awt.Frame;
 import javax.swing.JFrame;
 import javax.swing.SwingUtilities;
 
-import javax.media.nativewindow.WindowClosingProtocol;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLProfile;
@@ -53,7 +53,7 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
     public void testCloseFrameGLCanvas() throws InterruptedException, InvocationTargetException {
         final Frame frame = new Frame("testCloseFrameGLCanvas AWT");
 
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
         final GLCanvas glCanvas = new GLCanvas(caps);
         glCanvas.addGLEventListener(new GearsES2());
@@ -71,8 +71,8 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
         //
         // close with op: DO_NOTHING_ON_CLOSE -> NOP (default)
         //
-        int op = glCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DO_NOTHING_ON_CLOSE, op);
+        WindowClosingMode op = glCanvas.getDefaultCloseOperation();
+        Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op);
 
         Assert.assertEquals(true, AWTRobotUtil.closeWindow(frame, false)); // nop
         Thread.sleep(100);
@@ -84,9 +84,9 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
         //
         // close with op (GLCanvas): DISPOSE_ON_CLOSE -> dispose
         //
-        glCanvas.setDefaultCloseOperation(WindowClosingProtocol.DISPOSE_ON_CLOSE);
+        glCanvas.setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE);
         op = glCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DISPOSE_ON_CLOSE, op);
+        Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(frame, false)); // no frame close
         Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glCanvas, false));
@@ -104,7 +104,7 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
     public void testCloseJFrameGLCanvas() throws InterruptedException, InvocationTargetException {
         final JFrame frame = new JFrame("testCloseJFrameGLCanvas AWT");
 
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
         GLCanvas glCanvas = new GLCanvas(caps);
         glCanvas.addGLEventListener(new GearsES2());
@@ -123,8 +123,8 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
         // close with op: DO_NOTHING_ON_CLOSE -> NOP / HIDE (default)
         //
         Assert.assertEquals(JFrame.HIDE_ON_CLOSE, frame.getDefaultCloseOperation());
-        int op = glCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DO_NOTHING_ON_CLOSE, op);
+        WindowClosingMode op = glCanvas.getDefaultCloseOperation();
+        Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(frame, false)); // nop
         Thread.sleep(100);
@@ -145,7 +145,7 @@ public class TestWindowClosingProtocol01AWT extends UITestCase {
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         Assert.assertEquals(JFrame.DISPOSE_ON_CLOSE, frame.getDefaultCloseOperation());
         op = glCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DISPOSE_ON_CLOSE, op);
+        Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(frame, true));
         Assert.assertEquals(true,  AWTRobotUtil.waitForRealized(glCanvas, false));
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol02NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol02NEWT.java
index 8ad52ca..1657fcb 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol02NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol02NEWT.java
@@ -33,7 +33,7 @@ import java.lang.reflect.InvocationTargetException;
 import org.junit.Test;
 import org.junit.Assert;
 
-import javax.media.nativewindow.WindowClosingProtocol;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLProfile;
@@ -49,7 +49,7 @@ public class TestWindowClosingProtocol02NEWT extends UITestCase {
 
     @Test
     public void testCloseGLWindow() throws InterruptedException, InvocationTargetException {
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
         final GLWindow glWindow = GLWindow.create(caps);
         final AWTRobotUtil.WindowClosingListener windowClosingListener = AWTRobotUtil.addClosingListener(glWindow);
@@ -60,15 +60,15 @@ public class TestWindowClosingProtocol02NEWT extends UITestCase {
         Assert.assertEquals(true, glWindow.isVisible());
 
         // CHECK DEFAULT ..
-        int op = glWindow.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DISPOSE_ON_CLOSE, op);
+        WindowClosingMode op = glWindow.getDefaultCloseOperation();
+        Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op);
 
         //
         // close with op: DO_NOTHING_ON_CLOSE -> NOP
         //
-        glWindow.setDefaultCloseOperation(WindowClosingProtocol.DO_NOTHING_ON_CLOSE);
+        glWindow.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE);
         op = glWindow.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DO_NOTHING_ON_CLOSE, op);
+        Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op);
 
         Assert.assertEquals(true, AWTRobotUtil.closeWindow(glWindow, false)); // nop
         Assert.assertEquals(true, glWindow.isNativeValid());
@@ -78,9 +78,9 @@ public class TestWindowClosingProtocol02NEWT extends UITestCase {
         //
         // close with op (GLCanvas): DISPOSE_ON_CLOSE -> dispose
         //
-        glWindow.setDefaultCloseOperation(WindowClosingProtocol.DISPOSE_ON_CLOSE);
+        glWindow.setDefaultCloseOperation(WindowClosingMode.DISPOSE_ON_CLOSE);
         op = glWindow.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DISPOSE_ON_CLOSE, op);
+        Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(glWindow, true));
         Assert.assertEquals(false, glWindow.isNativeValid());
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java
index 19b2bbb..65068e9 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestWindowClosingProtocol03NewtAWT.java
@@ -37,7 +37,7 @@ import java.lang.reflect.InvocationTargetException;
 import javax.swing.JFrame;
 import javax.swing.SwingUtilities;
 
-import javax.media.nativewindow.WindowClosingProtocol;
+import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
 
 import javax.media.opengl.GLCapabilities;
 import javax.media.opengl.GLProfile;
@@ -53,7 +53,7 @@ public class TestWindowClosingProtocol03NewtAWT extends UITestCase {
     public void testCloseJFrameNewtCanvasAWT() throws InterruptedException, InvocationTargetException {
         final JFrame frame = new JFrame("testCloseJFrameNewtCanvasAWT");
 
-        GLProfile glp = GLProfile.getDefault();
+        GLProfile glp = GLProfile.getGL2ES2();
         GLCapabilities caps = new GLCapabilities(glp);
         final GLWindow glWindow = GLWindow.create(caps);
         final AWTRobotUtil.WindowClosingListener windowClosingListener = AWTRobotUtil.addClosingListener(glWindow);
@@ -82,8 +82,8 @@ public class TestWindowClosingProtocol03NewtAWT extends UITestCase {
         // close with op: DO_NOTHING_ON_CLOSE -> NOP / HIDE (default)
         //
         Assert.assertEquals(JFrame.HIDE_ON_CLOSE, frame.getDefaultCloseOperation());
-        int op = newtCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DO_NOTHING_ON_CLOSE, op);
+        WindowClosingMode op = newtCanvas.getDefaultCloseOperation();
+        Assert.assertEquals(WindowClosingMode.DO_NOTHING_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(frame, false));
         Assert.assertEquals(true,  frame.isDisplayable());
@@ -108,7 +108,7 @@ public class TestWindowClosingProtocol03NewtAWT extends UITestCase {
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         Assert.assertEquals(JFrame.DISPOSE_ON_CLOSE, frame.getDefaultCloseOperation());
         op = newtCanvas.getDefaultCloseOperation();
-        Assert.assertEquals(WindowClosingProtocol.DISPOSE_ON_CLOSE, op);
+        Assert.assertEquals(WindowClosingMode.DISPOSE_ON_CLOSE, op);
 
         Assert.assertEquals(true,  AWTRobotUtil.closeWindow(frame, true));
         Assert.assertEquals(false, frame.isDisplayable());
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01NEWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01NEWT.java
index 256868c..6b7b155 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01NEWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01NEWT.java
@@ -368,7 +368,7 @@ public class TestParenting01NEWT extends UITestCase {
         animator2.start();
 
         int state = 0;
-        int reparentAction;
+        Window.ReparentOperation reparentAction;
         while(animator1.isAnimating() && animator1.getTotalFPSDuration()<3*durationPerTest) {
             Thread.sleep(durationPerTest);
             switch(state) {
@@ -378,7 +378,7 @@ public class TestParenting01NEWT extends UITestCase {
                     System.err.println("Frames(1) "+glWindow2.getTotalFPSFrames());
                     reparentAction = glWindow2.reparentWindow(glWindow1, reparentRecreate);
                     System.err.println("Frames(2) "+glWindow2.getTotalFPSFrames());
-                    Assert.assertTrue(Window.ReparentAction.ACTION_INVALID < reparentAction);
+                    Assert.assertTrue(Window.ReparentOperation.ACTION_INVALID != reparentAction);
                     Assert.assertEquals(true, glWindow2.isVisible());
                     Assert.assertEquals(true, glWindow2.isNativeValid());
                     Assert.assertSame(glWindow1,glWindow2.getParent());
@@ -402,7 +402,7 @@ public class TestParenting01NEWT extends UITestCase {
                     Assert.assertEquals(true, glWindow2.isVisible());
 
                     reparentAction = glWindow2.reparentWindow(null, reparentRecreate);
-                    Assert.assertTrue(Window.ReparentAction.ACTION_INVALID < reparentAction);
+                    Assert.assertTrue(Window.ReparentOperation.ACTION_INVALID != reparentAction);
                     Assert.assertEquals(true, glWindow2.isVisible());
                     Assert.assertEquals(true, glWindow2.isNativeValid());
                     Assert.assertNull(glWindow2.getParent());
@@ -556,14 +556,14 @@ public class TestParenting01NEWT extends UITestCase {
         animator2.start();
 
         int state = 0;
-        int reparentAction;
+        Window.ReparentOperation reparentAction;
         while(animator1.isAnimating() && animator1.getTotalFPSDuration()<3*durationPerTest) {
             Thread.sleep(durationPerTest);
             switch(state) {
                 case 0:
                     Assert.assertEquals(true, glWindow2.isVisible());
                     reparentAction = glWindow2.reparentWindow(null, reparentRecreate);
-                    Assert.assertTrue(Window.ReparentAction.ACTION_INVALID < reparentAction);
+                    Assert.assertTrue(Window.ReparentOperation.ACTION_INVALID != reparentAction);
                     Assert.assertEquals(true, glWindow2.isVisible());
                     Assert.assertEquals(true, glWindow2.isNativeValid());
                     System.err.println("Frames for reparentWindow(parent, "+reparentRecreate+"): "+reparentAction+", B2: "+glWindow2.getTotalFPSFrames());
@@ -576,7 +576,7 @@ public class TestParenting01NEWT extends UITestCase {
                 case 1:
                     Assert.assertEquals(true, glWindow2.isVisible());
                     reparentAction = glWindow2.reparentWindow(glWindow1, reparentRecreate);
-                    Assert.assertTrue(Window.ReparentAction.ACTION_INVALID < reparentAction);
+                    Assert.assertTrue(Window.ReparentOperation.ACTION_INVALID != reparentAction);
                     Assert.assertEquals(true, glWindow2.isVisible());
                     Assert.assertEquals(true, glWindow2.isNativeValid());
                     System.err.println("Frames for reparentWindow(parent, "+reparentRecreate+"): "+reparentAction+", B3 "+glWindow2.getTotalFPSFrames());
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aAWT.java
index 2040fb9..de29db4 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParenting01aAWT.java
@@ -237,7 +237,7 @@ public class TestParenting01aAWT extends UITestCase {
             Thread.sleep(100);
         }
 
-        Assert.assertEquals(true, animator1.isAnimating()); // !!!
+        Assert.assertEquals(true, animator1.isAnimating());
 
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingFocusTraversal01AWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingFocusTraversal01AWT.java
index b23c170..f39b5df 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingFocusTraversal01AWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingFocusTraversal01AWT.java
@@ -65,7 +65,7 @@ import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
 public class TestParentingFocusTraversal01AWT extends UITestCase {
     static Dimension glSize, fSize;
     static int numFocus = 8;
-    static long durationPerTest = numFocus * 100;
+    static long durationPerTest = numFocus * 200;
     static GLCapabilities glCaps;
     static boolean manual = false;
 
@@ -191,9 +191,11 @@ public class TestParentingFocusTraversal01AWT extends UITestCase {
             }});
         Assert.assertEquals(true, AWTRobotUtil.waitForVisible(glWindow1, true));
         Assert.assertEquals(newtCanvasAWT1.getNativeWindow(),glWindow1.getParent());
-                        
+        AWTRobotUtil.clearAWTFocus(robot);
+        Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, frame1));
+        
         Assert.assertEquals(true, animator1.isAnimating());
-        Assert.assertEquals(false, animator1.isPaused());
+        // Assert.assertEquals(false, animator1.isPaused());
         Assert.assertNotNull(animator1.getThread());
           
         if(manual) {
@@ -203,7 +205,6 @@ public class TestParentingFocusTraversal01AWT extends UITestCase {
             // initial focus on bWest
             //        
             AWTRobotUtil.assertRequestFocusAndWait(robot, cWest, cWest, bWestFA, null);
-            Assert.assertEquals(true,  bWestFA.focusGained());
             Thread.sleep(durationPerTest/numFocus);
                     
             //
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java
index 1367a27..8ec65bf 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer01GLCanvasAWT.java
@@ -47,6 +47,7 @@ import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.newt.Window;
 import com.jogamp.newt.opengl.GLWindow;
 import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
@@ -103,10 +104,22 @@ public class TestParentingOffscreenLayer01GLCanvasAWT extends UITestCase {
             w.destroy();
         }
     }
+
+    @Test
+    public void testInfo00() throws InterruptedException, InvocationTargetException {
+        System.err.println("Java Version: "+Platform.getJavaVersionNumber());
+        System.err.println("OS Version: "+Platform.getOSVersionNumber());        
+        System.err.println("JAWTUtil.isOffscreenLayerRequired(): "+JAWTUtil.isOffscreenLayerRequired());
+        System.err.println("JAWTUtil.isOffscreenLayerSupported(): "+JAWTUtil.isOffscreenLayerSupported());
+    }
     
     @Test
     public void testOnscreenLayerGLCanvas_Onscreen() throws InterruptedException, InvocationTargetException {
-        testOffscreenLayerGLCanvas_Impl(false, false);
+        if(!JAWTUtil.isOffscreenLayerRequired()) {
+            testOffscreenLayerGLCanvas_Impl(false, false);
+        } else {
+            System.err.println("onscreen layer n/a");
+        }
     }
     
     /** We have no GLCanvas OffscreenWindow as we have for NEWT .. test disabled.
@@ -116,8 +129,12 @@ public class TestParentingOffscreenLayer01GLCanvasAWT extends UITestCase {
     } */
     
     @Test
-    public void testOffscreenLayerGLCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException {
-        testOffscreenLayerGLCanvas_Impl(true, false);
+    public void testOffscreenLayerGLCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException {        
+        if(JAWTUtil.isOffscreenLayerSupported()) {
+            testOffscreenLayerGLCanvas_Impl(true, false);
+        } else {
+            System.err.println("offscreen layer n/a");
+        }
     }
     
     private void testOffscreenLayerGLCanvas_Impl(boolean offscreenLayer, boolean offscreenClass) throws InterruptedException, InvocationTargetException {
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer02NewtCanvasAWT.java b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer02NewtCanvasAWT.java
index bc59c73..6a1980b 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer02NewtCanvasAWT.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/parenting/TestParentingOffscreenLayer02NewtCanvasAWT.java
@@ -106,17 +106,29 @@ public class TestParentingOffscreenLayer02NewtCanvasAWT extends UITestCase {
     
     @Test
     public void testOnscreenLayerNewtCanvas_Onscreen() throws InterruptedException, InvocationTargetException {
-        testOffscreenLayerNewtCanvas_Impl(false, false);
+        if(!JAWTUtil.isOffscreenLayerRequired()) {
+            testOffscreenLayerNewtCanvas_Impl(false, false);
+        } else {
+            System.err.println("onscreen layer n/a");
+        }
     }
     
-    @Test
-    public void testOffscreenLayerNewtCanvas_OffscreenLayerWithOffscreenClass() throws InterruptedException, InvocationTargetException {
-        testOffscreenLayerNewtCanvas_Impl(true, true);
+    // @Test
+    public void testOffscreenLayerNewtCanvas_OffscreenLayerWithOffscreenClass() throws InterruptedException, InvocationTargetException {                
+        if(JAWTUtil.isOffscreenLayerSupported()) {
+            testOffscreenLayerNewtCanvas_Impl(true, true);
+        } else {
+            System.err.println("offscreen layer n/a");
+        }        
     }
     
     @Test
-    public void testOffscreenLayerNewtCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException {
-        testOffscreenLayerNewtCanvas_Impl(true, false);
+    public void testOffscreenLayerNewtCanvas_OffscreenLayerWithOnscreenClass() throws InterruptedException, InvocationTargetException {        
+        if(JAWTUtil.isOffscreenLayerSupported()) {
+            testOffscreenLayerNewtCanvas_Impl(true, false);
+        } else {
+            System.err.println("offscreen layer n/a");
+        }        
     }
     
     private void testOffscreenLayerNewtCanvas_Impl(boolean offscreenLayer, boolean offscreenClass) throws InterruptedException, InvocationTargetException {
diff --git a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java
index a27bdd7..35a2d96 100644
--- a/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java
+++ b/src/test/com/jogamp/opengl/test/junit/util/AWTRobotUtil.java
@@ -37,6 +37,7 @@ import java.awt.KeyboardFocusManager;
 import java.awt.Robot;
 import java.awt.Toolkit;
 
+import javax.media.nativewindow.NativeWindow;
 import javax.media.opengl.awt.GLCanvas;
 
 import org.junit.Assert;
@@ -52,6 +53,20 @@ public class AWTRobotUtil {
     public static final int TIME_SLICE   = TIME_OUT / POLL_DIVIDER ;
     public static Integer AWT_CLICK_TO = null; 
     
+    public static void clearAWTFocus(Robot robot) throws InterruptedException, InvocationTargetException, AWTException {
+        if(null == robot) {
+            robot = new Robot();
+            robot.setAutoWaitForIdle(true);
+        }
+        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                System.err.println("******** clearAWTFocus.0");
+                KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
+            }});
+        robot.delay(ROBOT_DELAY);
+        System.err.println("******** clearAWTFocus.X");
+    }
+    
     public static java.awt.Point getCenterLocation(Object obj, boolean onTitleBarIfWindow) 
         throws InterruptedException, InvocationTargetException {
         Component comp = null;
@@ -99,9 +114,10 @@ public class AWTRobotUtil {
      *
      * @return True if the Window became the global focused Window within TIME_OUT
      */
-    public static boolean toFront(Robot robot, final java.awt.Window window)
+    public static boolean toFrontAndRequestFocus(Robot robot, final java.awt.Window window)
         throws AWTException, InterruptedException, InvocationTargetException {
 
+        // just for event tracing ..
         AWTWindowFocusAdapter winFA = new AWTWindowFocusAdapter("window");
         window.addWindowFocusListener(winFA);
         
@@ -110,24 +126,34 @@ public class AWTRobotUtil {
             robot.setAutoWaitForIdle(true);
         }
         java.awt.Point p0 = getCenterLocation(window, false);
-        System.err.println("robot pos: "+p0);
+        System.err.println("toFront: robot pos: "+p0);
         robot.mouseMove( (int) p0.getX(), (int) p0.getY() );
         robot.delay(ROBOT_DELAY);
 
-        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
-            public void run() {
-                window.setVisible(true);
-                window.toFront();
-                window.requestFocus();
-            }});
-        robot.delay(ROBOT_DELAY);
-
-        int wait;
-        for (wait=0; wait<POLL_DIVIDER && !winFA.focusGained(); wait++) {
+        int wait=0;
+        do {
+            final int _wait = wait;
+            javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
+                public void run() {
+                    if(0==_wait) {
+                        window.setVisible(true);
+                        window.toFront();
+                    }
+                    window.requestFocus();
+                }});
             Thread.sleep(TIME_SLICE);
-        }
+            wait++;
+        } while (wait<POLL_DIVIDER && !window.hasFocus());
+        final boolean success = wait<POLL_DIVIDER;
+        
         window.removeWindowFocusListener(winFA);
-        return wait<POLL_DIVIDER;
+        if(!success) {
+            System.err.println("*** AWTRobotUtil.toFrontAndRequestFocus() UI failure");
+            System.err.println("*** window: "+window);
+            System.err.println("*** window.hasFocus(): "+window.hasFocus());
+            Thread.dumpStack();
+        }
+        return success;
     }
 
     /**
@@ -143,7 +169,7 @@ public class AWTRobotUtil {
         }
 
         java.awt.Point p0 = getCenterLocation(obj, onTitleBarIfWindow);
-        System.err.println("robot pos: "+p0);
+        System.err.println("centerMouse: robot pos: "+p0+", onTitleBarIfWindow: "+onTitleBarIfWindow);
 
         robot.mouseMove( (int) p0.getX(), (int) p0.getY() );
         robot.delay(ROBOT_DELAY);
@@ -190,9 +216,11 @@ public class AWTRobotUtil {
                 javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
                     public void run() {
                         comp.requestFocus();
+                        System.err.println("requestFocus: AWT Component");
                     }});
             } else {
                 win.requestFocus();
+                System.err.println("requestFocus: NEWT Component");
             }
         } else {
             final int mouseButton = java.awt.event.InputEvent.BUTTON1_MASK;    
@@ -201,7 +229,9 @@ public class AWTRobotUtil {
             robot.waitForIdle();
             robot.mousePress(mouseButton);
             robot.mouseRelease(mouseButton);
-            robot.delay( getClickTimeout(obj) + 1 );                
+            final int d = getClickTimeout(obj) + 1;
+            robot.delay( d );                
+            System.err.println("requestFocus: click, d: "+d+" ms");
         }
     }
 
@@ -275,10 +305,27 @@ public class AWTRobotUtil {
             hasFocus = waitForFocus(waitForFocus, gain, lost);
         }
         if(!hasFocus) {
-            System.err.println("requestFocus: "+requestFocus);
-            System.err.println("waitForFocus: "+waitForFocus);
-            System.err.println("gain: "+gain);
-            System.err.println("lost: "+lost);
+            System.err.print("*** AWTRobotUtil.assertRequestFocusAndWait() ");
+            if(gain.focusGained() && !lost.focusLost()) {
+                // be error tolerant here, some impl. may lack focus-lost events (OS X) 
+                System.err.println("minor UI failure");
+                hasFocus = true;
+            } else {
+                System.err.println("major UI failure");
+            }
+            if(requestFocus instanceof Component) {
+                System.err.println("*** requestFocus.hasFocus() - AWT: "+((Component)requestFocus).hasFocus());
+            } else if(requestFocus instanceof NativeWindow) {
+                System.err.println("*** requestFocus.hasFocus() -  NW: "+((NativeWindow)requestFocus).hasFocus());
+            }
+            if(waitForFocus instanceof Component) {
+                System.err.println("*** waitForFocus.hasFocus() - AWT: "+((Component)waitForFocus).hasFocus());
+            } else if(waitForFocus instanceof NativeWindow) {
+                System.err.println("*** waitForFocus.hasFocus() -  NW: "+((NativeWindow)waitForFocus).hasFocus());
+            }
+            System.err.println("*** gain: "+gain);
+            System.err.println("*** lost: "+lost);
+            Thread.dumpStack();            
         }
         Assert.assertTrue("Did not gain focus", hasFocus);
     }
diff --git a/src/test/com/jogamp/opengl/test/junit/util/GLSLSimpleProgram.java b/src/test/com/jogamp/opengl/test/junit/util/GLSLSimpleProgram.java
index e23c31c..989de6c 100644
--- a/src/test/com/jogamp/opengl/test/junit/util/GLSLSimpleProgram.java
+++ b/src/test/com/jogamp/opengl/test/junit/util/GLSLSimpleProgram.java
@@ -62,7 +62,7 @@ public class GLSLSimpleProgram {
         int[] vlengths = new int[] { vlines[0].length() };
         gl.glShaderSource(vertShader, vlines.length, vlines, vlengths, 0);
         gl.glCompileShader(vertShader);
-        if(!ShaderUtil.isShaderStatusValid(gl, vertShader, gl.GL_COMPILE_STATUS, pbaos)) {
+        if(!ShaderUtil.isShaderStatusValid(gl, vertShader, GL2ES2.GL_COMPILE_STATUS, pbaos)) {
             System.out.println("getShader:postCompile vertShader: "+baos.toString());
             Assert.assertTrue(false);
         }
@@ -74,7 +74,7 @@ public class GLSLSimpleProgram {
         int[] flengths = new int[] { flines[0].length() };
         gl.glShaderSource(fragShader, flines.length, flines, flengths, 0);
         gl.glCompileShader(fragShader);
-        if(!ShaderUtil.isShaderStatusValid(gl, fragShader, gl.GL_COMPILE_STATUS, pbaos)) {
+        if(!ShaderUtil.isShaderStatusValid(gl, fragShader, GL2ES2.GL_COMPILE_STATUS, pbaos)) {
             System.out.println("getShader:postCompile fragShader: "+baos.toString());
             Assert.assertTrue(false);
         }
@@ -90,7 +90,7 @@ public class GLSLSimpleProgram {
 
         if(link) {
             gl.glLinkProgram(shaderProgram);
-            if(!ShaderUtil.isProgramValid(gl, shaderProgram, pbaos)) {
+            if(!ShaderUtil.isProgramLinkStatusValid(gl, shaderProgram, pbaos)) {
                 System.out.println("Error (GLSL link error):  "+baos.toString());
                 Assert.assertTrue(false);
             }
diff --git a/src/test/com/jogamp/opengl/test/junit/util/MiscUtils.java b/src/test/com/jogamp/opengl/test/junit/util/MiscUtils.java
index 506fe2d..9cbeabb 100644
--- a/src/test/com/jogamp/opengl/test/junit/util/MiscUtils.java
+++ b/src/test/com/jogamp/opengl/test/junit/util/MiscUtils.java
@@ -40,6 +40,15 @@ public class MiscUtils {
         }
         return def;
     }
+    
+    public static long atol(String str, long def) {
+        try {
+            return Long.parseLong(str);
+        } catch (Exception ex) {
+            ex.printStackTrace();
+        }
+        return def;
+    }
 
     public static boolean setFieldIfExists(Object instance, String fieldName, Object value) {
         try {
diff --git a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
index 1ff1428..368291a 100644
--- a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
+++ b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
@@ -28,14 +28,17 @@
  
 package com.jogamp.opengl.test.junit.util;
 
+import com.jogamp.common.os.Platform;
 import com.jogamp.common.util.locks.SingletonInstance;
 
+import org.junit.Assume;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Rule;
 import org.junit.rules.TestName;
+import org.junit.runner.manipulation.NoTestsRemainException;
 
 
 public abstract class UITestCase {
@@ -48,27 +51,34 @@ public abstract class UITestCase {
     public static final long SINGLE_INSTANCE_LOCK_POLL =      1000; // poll every 1s
 
     static volatile SingletonInstance singletonInstance;
+    
+    static volatile boolean testSupported = true;
 
     private static final synchronized void initSingletonInstance() {
         if( null == singletonInstance )  {
             // singletonInstance = SingletonInstance.createFileLock(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_FILE);
             singletonInstance = SingletonInstance.createServerSocket(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_PORT);
             if(!singletonInstance.tryLock(SINGLE_INSTANCE_LOCK_TO)) {
-                throw new RuntimeException("Fatal: Could lock single instance: "+singletonInstance.getName());
+                throw new RuntimeException("Fatal: Could not lock single instance: "+singletonInstance.getName());
             }
         }
     }
+    
+    public static void setTestSupported(boolean v) {
+        System.err.println("setTestSupported: "+v);
+        testSupported = v;
+    }
 
     public final String getTestMethodName() {
         return _unitTestName.getMethodName();
     }
     
-    public final String getSimpleTestName() {
-        return getClass().getSimpleName()+" - "+getTestMethodName();
+    public final String getSimpleTestName(String separator) {
+        return getClass().getSimpleName()+separator+getTestMethodName();
     }
 
-    public final String getFullTestName() {
-        return getClass().getName()+" - "+getTestMethodName();
+    public final String getFullTestName(String separator) {
+        return getClass().getName()+separator+getTestMethodName();
     }
     
     @BeforeClass
@@ -86,13 +96,20 @@ public abstract class UITestCase {
 
     @Before
     public void setUp() {
-        System.err.println("++++ UITestCase.setUp: "+getFullTestName());
+        System.err.print("++++ UITestCase.setUp: "+getFullTestName(" - "));
+        if(!testSupported) {
+            System.err.println(" - "+unsupportedTestMsg);
+            Assume.assumeTrue(testSupported);
+        }
+        System.err.println();      
     }
 
     @After
     public void tearDown() {
-        System.err.println("++++ UITestCase.tearDown: "+getFullTestName());
+        System.err.println("++++ UITestCase.tearDown: "+getFullTestName(" - "));
     }
+    
+    static final String unsupportedTestMsg = "Test not supported on this platform.";
 
 }
 
diff --git a/src/test/jogamp/newt/WindowImplAccess.java b/src/test/jogamp/newt/WindowImplAccess.java
index e8be5f6..3387a2a 100644
--- a/src/test/jogamp/newt/WindowImplAccess.java
+++ b/src/test/jogamp/newt/WindowImplAccess.java
@@ -38,7 +38,7 @@ public class WindowImplAccess {
         final WindowImpl winImpl = (WindowImpl) win.getDelegatedWindow();
         winImpl.runOnEDTIfAvail(true, new Runnable() {
             public void run() {
-                winImpl.windowDestroyNotify();
+                winImpl.windowDestroyNotify(false);
             }
         });        
     }
diff --git a/www/index.html b/www/index.html
index 202e4de..e48128b 100644
--- a/www/index.html
+++ b/www/index.html
@@ -36,12 +36,15 @@
                         <li><a href="../../wiki/index.php/Jogl_Tutorial">Tutorial</a></li>
                         <li><a href="../doc/userguide/">Userguide</a></li>
                         <li><a href="../../wiki/index.php/Jogl_FAQ">FAQ</a></li>
+                        <li><a href="../../git/?p=jogl.git">Code Repository</a></li>
+                        <li><a href="../../git/?p=jogl-demos.git">Demo Repository</a></li>
                         <li><a href="http://www.opengl.org">OpenGL.org</a></li>
                         <li><a href="http://www.opengl.org/registry/">OpenGL Registry</a></li>
-                        <li><a href="http://www.opengl.org/registry/doc/glspec41.core.20100725.withchanges.pdf">GL 4.1 Core Spec</a></li>
-                        <li><a href="http://www.opengl.org/registry/doc/glspec41.compatibility.20100725.withchanges.pdf">GL 4.1 Compat. Spec</a></li>
-                        <li><a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.10.6.pdf">GLSL 4.10 spec</a></li>
-                        <li><a href="http://www.khronos.org/files/opengl41-quick-reference-card.pdf">GL 4.1 / GLSL 4.10 Cards</a></li>
+                        <li><a href="http://www.khronos.org/registry/">Khronos Registry</a></li>
+                        <li><a href="http://www.opengl.org/registry/doc/glspec42.core.20120119.withchanges.pdf">GL 4.2 Core Spec</a></li>
+                        <li><a href="http://www.opengl.org/registry/doc/glspec42.compatibility.20120119.withchanges.pdf">GL 4.2 Compat. Spec</a></li>
+                        <li><a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.11.pdf">GLSL 4.20 spec</a></li>
+                        <li><a href="http://www.khronos.org/files/opengl42-quick-reference-card.pdf">GL 4.2 / GLSL 4.20 Cards</a></li>
                         <li><a href="http://www.khronos.org/opengles/sdk/docs/reference_cards/OpenGL-ES-2_0-Reference-card.pdf">ES 2.0 / ESSL 1.0 Cards</a></li>
                     </ul>
                     <h3>Presentations</h3>
@@ -49,6 +52,11 @@
                         <li><a href="../../doc/gpunurbs2011/graphicon2011-slides.pdf">NURBS @ GPU</a></li>
                         <li><a href="../../doc/siggraph2011/jogamp-siggraph2011.pdf">Siggraph 2011</a></li>
                         <li><a href="../../doc/siggraph2010/jogamp-siggraph2010.pdf">Siggraph 2010</a></li>
+                        <li><a href="BOF-3908-JOGL-slides.pdf"> JavaOne 2007 BOF Slides</a></li>
+                        <li><a href="bof0899.pdf">JavaOne 2006 BOF Slides</a></li>
+                        <li><a href="ts1361.pdf">JavaOne 2004 Slides</a></li>
+                        <li><a href="2125.pdf">JavaOne 2003 Slides</a></li>
+                        <li><a href="3167.pdf">JavaOne 2002 Slides</a></li>
                     </ul>
                     <h3>Papers</h3>
                     <ul>
@@ -56,11 +64,6 @@
                     </ul>
                     <h3>Archive</h3>
                     <ul>
-                        <li><a href="BOF-3908-JOGL-slides.pdf"> JavaOne 2007 BOF Slides</a></li>
-                        <li><a href="bof0899.pdf">JavaOne 2006 BOF Slides</a></li>
-                        <li><a href="ts1361.pdf">JavaOne 2004 Slides</a></li>
-                        <li><a href="2125.pdf">JavaOne 2003 Slides</a></li>
-                        <li><a href="3167.pdf">JavaOne 2002 Slides</a></li>
                         <li><a href="http://jausoft.com/gl4java/">GL4Java</a></li>
                     </ul>
                 </div>
@@ -79,7 +82,7 @@
                         its profiles and how we map them to JOGL.
                     </p>
                     <p>
-                        JOGL integrates with the AWT and Swing widget sets, as well with custom windowing toolkits using the NativeWindow API.
+                        JOGL integrates with the AWT, Swing and SWT widget sets, as well with custom windowing toolkits using the NativeWindow API.
                         <a href="../doc/NEWT-Overview.html">JOGL also provides its own native windowing toolkit, NEWT</a>.
                     </p>
                     <p>
@@ -114,95 +117,48 @@
                                                         <tbody>
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://worldwind.arc.nasa.gov/java/"><img src="worldwind.jpg"
-                                                                                                                       width="160" height="159" align="left" alt="World Wind"></img>NASA World Wind
-                                                                        Java</a> provides next-generation 3-D virtual globe technology for
-                                                                    applications written in the Java programming language. It supplies a
-                                                                    suite of open-source components that developers include in their own
-                                                                    applications, providing virtual globe functionality to any application
-                                                                    that can benefit from it. World Wind Java's components perform as well
-                                                                    as, or better than, any other known implementation and utilize the
-                                                                    OpenGL API for 3-D graphics via JOGL. See WWJ Technical Lead Tom
-                                                                    Gaskins' <a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-3489&yr=2007&track=2">JavaOne
-                                                                        2007</a> presentation on World Wind Java and the DiSTI Corporation's
-                                                                    <a href="http://www.disti.com/Products/demonstrations/java.html">F-16 flight simulator</a>
-                                                                    built using World Wind Java.
-                                                                </td>
-                                                                <td >
-                                                                    <a href="http://openendedgroup.com/field"><img src="field.png"
-                                                                                                                   width="160" height="159" align="left" alt="Field"></img>Field</a> is an
-                                                                    open-source development environment for digital art and experimental
-                                                                    code writing. Built around the needs of programmers that manipulate
-                                                                    images, make animations and compose music, Field seeks to tie
-                                                                    text-based programming with ad hoc visual metaphors. Field uses Python
-                                                                    and other programming languages and wants to be integrated into your
-                                                                    own personal code-base. And it comes with special support for the <a
-                                                                        href="http://processing.org/">Processing</a> environment. Field uses
-                                                                    JOGL for its UI and its built-in drawing system; it provides a
-                                                                    JOGL-based scene-graph library for 3D visualization.
+                                                                    <a href="http://processing.org/"><img src="media/processing.jpg" width="160" height="158" align="left" alt="Processing"></img>
+                                                                        Processing</a> is an open
+                                                                    source programming language and environment for people who want to
+                                                                    program images, animation, and sound. It is used by students, artists,
+                                                                    designers, architects, researchers, and hobbyists for learning,
+                                                                    prototyping, and production. Processing is developed by artists and
+                                                                    designers as an alternative to proprietary software tools in the same
+                                                                    domain. It uses JOGL for its hardware accelerated 3D rendering
+                                                                    support.
                                                                 </td>
-                                                            </tr>
-
-                                                            <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.madlix.com"><img src="madlix.png" width="160"
-                                                                                                         height="160" align="left" alt="Madlix"></img>MADLIX</a> lets users insert
-                                                                    3D-content in web pages, blogs, Google pages, community presentations
-                                                                    and more. MADLIX is JOGL-powered and runs smoothly inside all
-                                                                    Java-enabled browsers, with no need for custom plug-ins or application
-                                                                    installation. The <a href="http://www.madlix.com">on-line gallery</a>
-                                                                    features high-quality content ready for insertion. MADLIX is
-                                                                    accompanied by the MADLIX exporter tool enabling 3D artists to
-                                                                    directly export their 3D artwork from Autodesk Maya to the MADLIX
-                                                                    gallery. The exporter features pre-view functionality as well as a
-                                                                    standalone viewer, supporting the MADLIX file format and the open
-                                                                    standard file format COLLADA.
+                                                                    <a href="http://projects.hepforge.org/frog/ "><img src="media/Frog-Craft3_2.160w.png"
+                                                                                                                       width="160" height="120" align="left" alt="FROG"></img>FROG</a>
+                                                                    is a fast OpenGL event display tool mainly developed for visualization of data 
+                                                                    in the field of high energy physics. FROG is mostly used to visualized/animate data 
+                                                                    from proton/proton collision produced in the CMS experiment at the LHC, CERN, Switzerland.
+                                                                    Animations produced by this tools are frequently used to share the progress of the 
+                                                                    CMS experiment with the media of the world 
+                                                                    (animations are often visible on scientific website or even on TV).
 
-                                                                </td>
-                                                                <td >
-                                                                    <a href="http://bytonic.de/html/jake2.html">
-                                                                        <img src="jake2.jpg" width="160" height="128" align="left" alt="Jake2"></img>Jake2</a> is a port
-                                                                    of id Software's GPL'd Quake II engine from C to Java done by <a
-                                                                        href="http://bytonic.de/">bytonic software</a>. You can run the game
-                                                                    via <a href="http://bytonic.de/html/jake2_webstart.html">Java Web
-                                                                        Start</a> with <b>no manual installation</b> on all of JOGL's
-                                                                    supported platforms.
+                                                                    FROG has recently been ported to Java and is now using JOGL
+                                                                    and also offers an
+                                                                    <a href="http://projects.hepforge.org/frog/Downloads/jfrog/jfrog_web.jnlp ">online demonstration</a>.
                                                                 </td>
                                                             </tr>
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://volumeviewer.kenai.com/">
-                                                                        <img src="http://volumeviewer.kenai.com/thumbnail.png" width="160" height="120" align="left" alt="Volume Viewer"></img>Volume Viewer</a>
-                                                                    is an open source renderer for 3D volumetric data. It provides tools for coloring your model,
-                                                                    cutting away pieces, and viewing it from any angle. It can cast shadows within the model for extra realism.
-                                                                    You can even upload your own volumetric data and view it in real time.
+                                                                    <a href="http://c3d.com"><img src="media/c3d-studio.jpg"
+                                                                                                                       width="160" height="107" align="left" alt="C3D"></img>C3D</a>'s                                              <a href="http://c3d.com/index.php?option=com_content&view=section&layout=blog&id=5&Itemid=65">product palette</a> includes <i>C3D Studio</i> and <i>C3D Viewer</i>.<a href="http://c3d.com/index.php?option=com_content&view=article&id=46:c3dstudio&catid=34:generalpro [...]
                                                                 </td>
+
                                                                 <td >
-                                                                    <a href="http://netbeans-opengl-pack.dev.java.net/">
-                                                                        <img src="NetBeansOpenGLPackLogo160.png" width="160" height="159" align="left" alt="NOGL Pack logo"></img>
-                                                                        The NetBeans OpenGL Pack</a> provides an easy to use OpenGL development
-                                                                    environment integrated into NetBeans. It supplies modules like an GLSL
-                                                                    shader editor, hardware compiler/linker integration and tools for
-                                                                    displaying hardware information. The pack ships ready to run JOGL (JSR
-                                                                    231) demo projects and all OpenGL samples of the OpenGL Programming
-                                                                    Guide (also known as the Red Book).
+                                                                    <a href="http://www3.math.tu-berlin.de/jreality/index.php?article_id=1"><img src="media/jreality-logo-discreteksurfaces.png"
+                                                                                                                   width="160" height="105" align="left" alt="jReality"></img>jReality</a> 
+                                                                    is a Java based, open-source, full-featured 3D scene graph package designed for 3D visualization and specialized in mathematical visualization. It provides several backends, including a JOGL one for Java based OpenGL rendering. JReality is thread-safe, has a flexible shading model based on an attribute-inheritance mechanism in the scene graph, device-independent user interaction and support for 3D audio (JACK). It has a  [...]
                                                                 </td>
                                                             </tr>
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.insparia.com/"><img src="insparia.jpg" width="160" height="160" align="left" alt="insparia image"></img>
-                                                                        Insparia</a> was created to help people
-                                                                    easily visualize, construct and track information about a 3d
-                                                                    environment online. Shape and texture importing as well as a robust
-                                                                    renderer will be available in the final commercial version.  Insparia
-                                                                    uses JOGL to allow the user to construct and interact with their 3d
-                                                                    environment in real-time. Please note that Insparia is in alpha
-                                                                    testing. Feedback is appreciated.
-                                                                </td>
-                                                                <td >
-                                                                    <a href="http://www.scilab.org/"><img src="scilab.png" width="160"  height="159" align="left" alt="scilab image"></img>
+                                                                    <a href="http://www.scilab.org/"><img src="media/scilab.png" width="160"  height="159" align="left" alt="Scilab"></img>
                                                                         Scilab</a> is a free scientific software
                                                                     package for numerical computations providing a powerful open computing
                                                                     environment for engineering and scientific applications. It has
@@ -213,18 +169,13 @@
                                                                     on JOGL, allowing it to take advantage of the OpenGL accelerated
                                                                     graphics.
                                                                 </td>
-                                                            </tr>
 
-                                                            <tr>
                                                                 <td width="50%">
                                                                     <a href="http://www.brightideassoftware.com/Pebbles/PebblesHome.aspx">
-                                                                        <img src="pebbles.png" width="160" height="160" align="left" alt=""></img>
+                                                                        <img src="media/pebbles.png" width="200" align="left" alt="OneStone Pebbles"></img>
                                                                         OneStone® Pebbles</a> are a new series of calculus visualization tools developed
                                                                     by <a href="http://www.brightideassoftware.com/">Bright Ideas Software®</a>.
-                                                                    Designed from the ground up with input from
-                                                                    education professionals, these unique tools meld current educational
-                                                                    theory with state of the art graphics technology in consistent,
-                                                                    easy-to-use packages. Each 'Pebble' in the series is a stand-alone
+                                                                    Each 'Pebble' in the series is a stand-alone
                                                                     program designed to illustrate a specific topic in the calculus
                                                                     syllabus. While the topic of each Pebble is different, the experience
                                                                     of using each remains as constant as possible, and features several
@@ -234,40 +185,59 @@
                                                                     <a href="http://www.brightideassoftware.com/Pebbles/CurveFamilies.aspx"> Curve Families</a> and
                                                                     <a href="http://www.brightideassoftware.com/Pebbles/SurfacesOfRevolution.aspx">Surfaces of Revolution</a> examples!
                                                                 </td>
-                                                                <td >
-                                                                    <a href="http://www3.math.tu-berlin.de/jreality"><img src="viewerVR.png" width="160" height="160" align="left" alt="jreality"></img>
-                                                                        jReality</a> is an open-source,
-                                                                    full-featured 3D scene graph package designed for but not limited to
-                                                                    mathematical visualization.  It provides several backends, including a
-                                                                    JOGL one; it is thread-safe; it has a flexible shading model based on
-                                                                    an attribute-inheritance mechanism in the scene graph;
-                                                                    device-independent user interaction; support for true 3D audio; many
-                                                                    support classes for transformations and geometry; a plugin system for
-                                                                    assembling custom viewers; <a href="http://www3.math.tu-berlin.de/jreality/phpbb/">an active forum</a>
-                                                                    and a growing <a href="http://www3.math.tu-berlin.de/jreality/mediawiki/index.php/Developer_Tutorial">set
-                                                                        of tutorial examples</a> to help developers interested in using
-                                                                    jReality to solve their 3D problems.
 
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <a href="http://code.google.com/p/jzy3d/">
+                                                                        <img src="http://martin.pernollet.free.fr/cv/projects/jzy3d/demo_ring_surface.jpg" width="160" height="120" align="left" alt="Jzy3D"></img>
+                                                                        Jzy3d</a>
+                                                                    stands for Java Easy 3d, and allows a rapid display of 3d scientific 
+                                                                    data. User can define z=f(x,y) functions binded to (customizable) 
+                                                                    colormaps, as well as rendering predefined simple 3d shapes 
+                                                                    programmaticaly or from csv files.
+                                                                    One can moreover add pre/post renderers for adding java2d layers 
+                                                                    to the 3d scene.  Jzy3d provides a simple bridge to AWT, SWT, or 
+                                                                    Swing, and has already been integrated in Eclipse RCP 
+                                                                    and Swing applications. The API releases one of the burden
+                                                                    of working with OpenGL, 
+                                                                    3d polygon ordering and transparency management.
+                                                                </td>
+
+                                                                <td width="50%">
+                                                                    <a href="http://gephi.org/"><img src="media/gephi.jpg" width="160" height="102" align="left" alt="Gephi"></img>
+                                                                        Gephi</a> is a tool for people that have to explore and understand graphs. Like Photoshop but for data, the user interacts with the representation, manipulate the structures, shapes and colors to reveal hidden properties. The goal is to help data analysts to make hypothesis, intuitively discover patterns, isolate structure singularities or faults during data sourcing. It is a complementary tool to traditional statist [...]
                                                                 </td>
                                                             </tr>
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="https://zg3d.dev.java.net/"><img src="zg3d.png" width="160" height="160" align="left" alt=""></img>
-                                                                        ZG3D</a> is an open source project that uses
-                                                                    JOGL for visualizing 3D geometries with the emphasis of plotting
-                                                                    scientific data in a web application. Geometry objects in an XML file
-                                                                    or string can be dynamically loaded and removed. An HTML document may
-                                                                    call ZG3D functions through JavaScript and may define JavaScript
-                                                                    functions to receive messages from ZG3D, which makes it very easy and
-                                                                    flexible to embed interactive 3D web visualization. The software is
-                                                                    developed at the <a
-                                                                        href="http://www-cger.nies.go.jp/index.html">Center for Global
-                                                                        Environmental Research</a>, Japan, for the advanced data visualization
-                                                                    of the <a href="http://db.cger.nies.go.jp/g3db/ggtu/trajectory.html">Global Greenhouse Gases Database</a>.
+                                                                    <a href="http://jebgl.com/"><img src="media/JebGL_logo.160w.png"
+                                                                                                                   width="160" height="87" align="left" alt="JebGL"></img>JebGL</a> 
+                                                                    is a piece of Javascript which lets you run your WebGL apps in browsers lacking WebGL support without having to modify your existing code! Behind the scenes JebGL uses a fallback Java applet to emulate the WebGL canvas if needed, and the Java applet runs hardware accelerated on all platforms using JOGL. 
+                                                                    JebGL is open source, released under the MIT license.  
                                                                 </td>
+
+                                                                <td width="50%">
+                                                                    <a href="http://brandonborkholder.github.com/glg2d/"><img src="media/glg2d-demo.png" width="200" align="left" alt="GLG2D"></img>
+                                                                        GLG2D</a> is a Graphics2D implementation that uses OpenGL to implement basic Java2D drawing functionality. We currently use the fixed function pipeline, with the GL2 profile for most functionality. But a shader implementation is in the pipeline (so to speak). See <a href="http://brandonborkholder.github.com/glg2d/implementationstatus.html">implementation status</a> for which features are fully implemented.
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.codededge.com"><img src="elflightengine-160x122.png" width="160" height="122" align="left" alt="elflight engine"></img>
+                                                                    <a href="http://www.everplanes.com/"><img src="media/EverplanesLogo_160x160.png" width="122" height="122" align="left" alt="Everplanes"></img>
+                                                                        Everplanes</a> is a game of exploration, building, survival and strategy. 
+                                                                        It introduces new gameplay, resources and challenges in the updates. 
+                                                                        Each time the game is started, it automatically downloads the latest updates.
+                                                                        The game includes a built-in server for LAN or Internet play. 
+                                                                        You can run an open server, or configure various levels of access control. 
+                                                                        Everplanes features a built-in server browser and also includes global chat facility.
+                                                                        Everplanes is available for Mac OS X 10.4+, Windows XP/Vista/7 and Linux.
+                                                                </td>
+                                                                <td width="50%">
+                                                                    <a href="http://www.codefrontiers.com/page/elflight-engine/"><img src="media/elflightengine-160x122.png" width="160" height="122" align="left" alt="Elflight Engine"></img>
                                                                         The Elflight Engine</a> is a games engine designed for the web.
                                                                         It supports hardware accelerated 3D games and applications in a web browser,
                                                                         with the ability to import assets from major 3D packages such as Maya and 3D Studio.
@@ -278,9 +248,72 @@
                                                             </tr>
 
                                                             <tr>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <b>On the brink ...</b>
+                                                                </td>
+                                                                <td width="50%">
+                                                                    <b>.. to use JOGL Version 2.</b>
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <a href="http://worldwind.arc.nasa.gov/java/"><img src="media/worldwind.jpg"
+                                                                                                                       width="160" align="left" alt="World Wind"></img>NASA World Wind
+                                                                        Java</a> provides next-generation 3-D virtual globe technology for
+                                                                    applications written in the Java programming language. It supplies a
+                                                                    suite of open-source components that developers include in their own
+                                                                    applications, providing virtual globe functionality to any application
+                                                                    that can benefit from it. World Wind Java's components perform as well
+                                                                    as, or better than, any other known implementation and utilize the
+                                                                    OpenGL API for 3-D graphics via JOGL. See WWJ Technical Lead Tom
+                                                                    Gaskins' <a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-3489&yr=2007&track=2">JavaOne
+                                                                        2007</a> presentation on World Wind Java and the DiSTI Corporation's
+                                                                    <a href="http://www.disti.com/Products/demonstrations/java.html">F-16 flight simulator</a>
+                                                                    built using World Wind Java.
+                                                                </td>
+
+                                                                <td width="50%">
+                                                                    <a href="http://www.geogebra.org/"><img src="media/geogebra-screenshot-tangents.png" width="200" align="left" alt="GeoGebra"></img>GeoGebra</a> is free and multi-platform dynamic mathematics software for all levels of education that joins geometry, algebra, tables, graphing, statistics and calculus in one easy-to-use package. It has received several educational software awards in Europe and the USA. <a href="http://www.g [...]
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <b>Older projects ...</b>
+                                                                </td>
+                                                                <td width="50%">
+                                                                    <b>.. may use JOGL Version 1.</b>
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <a href="http://volumeviewer.kenai.com/">
+                                                                        <img src="http://volumeviewer.kenai.com/thumbnail.png" width="160" height="120" align="left" alt="Volume Viewer"></img>Volume Viewer</a>
+                                                                    is an open source renderer for 3D volumetric data. It provides tools for coloring your model,
+                                                                    cutting away pieces, and viewing it from any angle. It can cast shadows within the model for extra realism.
+                                                                    You can even upload your own volumetric data and view it in real time.
+                                                                </td>
+                                                                <td >
+                                                                    <a href="http://bytonic.de/html/jake2.html">
+                                                                        <img src="media/jake2.jpg" width="160" height="128" align="left" alt="Jake2"></img>Jake2</a> is a port
+                                                                    of id Software's GPL'd Quake II engine from C to Java done by <a
+                                                                        href="http://bytonic.de/">bytonic software</a>. You can run the game
+                                                                    via <a href="http://bytonic.de/html/jake2_webstart.html">Java Web
+                                                                        Start</a> with <b>no manual installation</b> on all of JOGL's
+                                                                    supported platforms.
+                                                                </td>
+
+                                                            </tr>
+
+                                                            <tr>
                                                                 <td width="50%">
                                                                     <a href="http://www.fusion-laboratory.de/"><img
-                                                                            src="fusion-laboratory.jpg" width="160" height="160" align="left"
+                                                                            src="media/fusion-laboratory.jpg" width="160" height="160" align="left"
                                                                             alt="Fusion Laboratory"></img>The Fusion Framework</a> enables Swing
                                                                     components to be extended with 3D content via JOGL. In general the 3D
                                                                     content will show up in layers on top of the corresponding Swing
@@ -293,8 +326,19 @@
                                                                     demonstrate the abilities of the framework; please fill out the web
                                                                     form to help evaluate the components' usefulness.
                                                                 </td>
+
                                                                 <td width="50%">
-                                                                    <a href="http://www.artofillusion.org/"><img src="artofillusion.jpg" width="160" height="117" align="left" alt="Art Of Illusion"></img>
+                                                                    <a href="http://3d-alignment.eu"><img src="media/strap.jpg" width="160" height="118" align="left" alt="STRAP"></img></a>
+                                                                    With <a href="http://3d-alignment.eu">STRAP</a> you can align your proteins by
+                                                                    sequence and 3D-structure.  STRAP simultaneously displays
+                                                                    3d-structures, amino acid sequence alignment and nucleotide sequences.
+                                                                    It has powerful annotation features.
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <a href="http://www.artofillusion.org/"><img src="media/artofillusion.jpg" width="160" height="117" align="left" alt="Art Of Illusion"></img>
                                                                         Art of Illusion</a> is a free, open source 3D modelling and rendering
                                                                     studio. Many of its capabilities rival those found in commercial
                                                                     programs. Some of the highlights include subdivision surface based
@@ -302,40 +346,26 @@
                                                                     for designing procedural textures and materials. It uses JOGL for
                                                                     real-time OpenGL rendering in its modeling views.
                                                                 </td>
-                                                            </tr>
 
-                                                            <tr>
-                                                                <td width="50%">
-                                                                    <a href="http://www.avengina.org/"><img src="avengina.jpg" alt="Avengina" align="left" height="99" width="160"></img>Avengina</a> is a
-                                                                    realtime 3D graphics engine which is designed for the execution as a
-                                                                    Java applet. Alternatively it can be launched as a Java Webstart
-                                                                    application outside the browserwindow. The software provides the
-                                                                    possibility to exhibit texts and images in virtual
-                                                                    galleries. Regarding the control and behaviour of the avatar it's
-                                                                    redolent of a game engine. The graphics rendering system bases on
-                                                                    per-pixel lighting and supports normal mapping, specular lighting and
-                                                                    stencil volume shadows. Avengina uses JOGL for realtime rendering.
-                                                                </td>
                                                                 <td width="50%">
-
-                                                                    <a href="http://chronotext.org/"><img src="chronotext.jpg" width="160" height="120" align="left" alt="chronotext"></img>
-                                                                        chronotext</a> is a series
-                                                                    of visual design experiments involving animated text and 3D objects
-                                                                    and surfaces. Several examples can be run on-line via <a
-                                                                        href="http://chronotext.org/scriptorium/behind/index.htm">Java Web
-                                                                        Start</a>. See the <a href="http://www.chronotext.org/mapping/">latest
-                                                                        experiments</a> of mapping text on to real 3D surfaces.
+                                                                    <a href="http://impact.sourceforge.net/"><img src="media/impact.jpg" width="160" height="129" align="left" alt="Impact"></img>
+                                                                        Impact</a> is a
+                                                                    complete finite element suite including preprocessor, solver and
+                                                                    postprocessor which is useable for simulating dynamic events such as
+                                                                    car crashes or stamping of metal sheets. The suite allows 3D
+                                                                    modelling, solving and viewing of simulation results, all in OpenGL
+                                                                    accelerated graphics through the use of JOGL.
                                                                 </td>
                                                             </tr>
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.sculpteo.com"><img src="sculpteo_3_robot_72dpi_sm.jpg" width="160" height="120" align="left" alt="sculpteo"></img>
+                                                                    <a href="http://www.sculpteo.com"><img src="media/sculpteo_3_robot_72dpi_sm.jpg" width="160" height="120" align="left" alt="Sculpteo"></img>
                                                                         Sculpteo</a> offers a 3D printing service, fast and available for everyone.
                                                                     Starting from a 3D design, Sculpteo makes a specific object : interior decoration, characters, robots, miniatures, models, mechanic objects...
                                                                 </td>
                                                                 <td width="50%">
-                                                                    <a href="http://www.fenggui.org/"><img src="fenggui.jpg" width="160" height="127" align="left" alt="FengGUI"></img>
+                                                                    <a href="http://www.fenggui.org/"><img src="media/fenggui.jpg" width="160" height="127" align="left" alt="FengGUI"></img>
                                                                         FengGUI</a> is a graphical
                                                                     user interface (GUI) application programming interface (API) based on
                                                                     OpenGL. FengGUI provides all typical GUI components like buttons,
@@ -346,46 +376,8 @@
                                                             </tr>
 
                                                             <tr>
-                                                                <td  width="50%">
-                                                                    <a href="http://www.simulation.com/products/glstudio/glstudio.html"><img
-                                                                            src="glstudio.jpg" width="160" height="135" align="left" alt="GL Studio"></img>
-                                                                        GL Studio</a> is an object oriented rapid application
-                                                                    development tool that allows a user to graphically combine
-                                                                    photographs, 3D models and behavior logic to create advanced 2D and 3D
-                                                                    human machine interfaces.  GL Studio generates Java or C++ source code
-                                                                    which can then be integrated into the user’s application as a user
-                                                                    interface. <a
-                                                                        href="http://www.simulation.com/products/glstudio/java/java.html">Java
-                                                                        code</a> generated with GL Studio can be deployed using
-                                                                    javax.swing.JPanel, java.awt.Canvas and JavaBeans. GL Studio uses
-                                                                    OpenGL for rendering and GL Studio for Java uses the JOGL API.
-
-                                                                </td>
-                                                                <td width="50%">
-                                                                    <a href="http://impact.sourceforge.net/"><img src="impact.jpg" width="160" height="129" align="left" alt="Impact"></img>
-                                                                        Impact</a> is a
-                                                                    complete finite element suite including preprocessor, solver and
-                                                                    postprocessor which is useable for simulating dynamic events such as
-                                                                    car crashes or stamping of metal sheets. The suite allows 3D
-                                                                    modelling, solving and viewing of simulation results, all in OpenGL
-                                                                    accelerated graphics through the use of JOGL.
-                                                                </td>
-                                                            </tr>
-
-                                                            <tr>
-                                                                <td width="50%">
-                                                                    <a href="http://code.google.com/p/jzy3d/">
-                                                                        <img src="http://martin.pernollet.free.fr/cv/projects/jzy3d/demo_ring_surface.jpg" width="160" height="120" align="left" alt="Jack Flowers"></img>
-                                                                        Jzy3d</a>
-                                                                    stands for Java Easy 3d, and allows a rapid display of 3d scientific data. User can define z=f(x,y) functions
-                                                                    binded to (customizable) colormaps, as well as rendering predefined simple 3d shapes programmaticaly or from csv files.
-                                                                    One can moreover add pre/post renderers for adding java2d layers to the 3d scene.
-                                                                    Jzy3d provides a simple bridge to AWT, SWT, or Swing, and has already been integrated with success in Eclipse RCP and Swing
-                                                                    professionnal applications by the company MASA Group. The API has been written with the goal to hide the burden of working with
-                                                                    OpenGL, 3d polygon ordering and transparency management.
-                                                                </td>
                                                                 <td width="50%">
-                                                                    <a href="http://mbt.sdsc.edu/"><img src="mbt.jpg" width="160" height="122" align="left" alt="Molecular Biology Toolkit"></img></a>The
+                                                                    <a href="http://mbt.sdsc.edu/"><img src="media/mbt.jpg" width="160" height="122" align="left" alt="Molecular Biology Toolkit"></img></a>The
                                                                     <a href="http://mbt.sdsc.edu/">Molecular Biology Toolkit</a> is a
                                                                     Java-based protein visualization and analysis toolkit. The toolkit
                                                                     provides classes for efficiently loading, managing and manipulating
@@ -398,22 +390,9 @@
                                                                         demo</a>), <a href="http://www.immuneepitope.org/">EpitopeViewer</a>
                                                                     (<a href="http://spdc.sdsc.edu/iedb/epitopeViewer/viewer_jogl333.php">webstart demo</a>), and <a href="http://sirius.sdsc.edu/">Sirius</a>.
                                                                 </td>
-                                                            </tr>
 
-                                                            <tr>
-                                                                <td width="50%">
-                                                                    <a href="http://processing.org/"><img src="processing.jpg" width="160" height="158" align="left" alt="processing"></img>
-                                                                        Processing</a> is an open
-                                                                    source programming language and environment for people who want to
-                                                                    program images, animation, and sound. It is used by students, artists,
-                                                                    designers, architects, researchers, and hobbyists for learning,
-                                                                    prototyping, and production. Processing is developed by artists and
-                                                                    designers as an alternative to proprietary software tools in the same
-                                                                    domain. It uses JOGL for its hardware accelerated 3D rendering
-                                                                    support.
-                                                                </td>
                                                                 <td width="50%">
-                                                                    <a href="http://www.specknet.org/dev/specksim"><img src="specksim.jpg" width="160" height="117" align="left" alt="SpeckSim"></img>
+                                                                    <a href="http://www.specknet.org/dev/specksim"><img src="media/specksim.jpg" width="160" height="117" align="left" alt="SpeckSim"></img>
                                                                         SpeckSim</a> is a
                                                                     behaviour-level simulator for networks of small, resource-constrained
                                                                     devices with sensing, computation and communication
@@ -427,44 +406,159 @@
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://3d-alignment.eu"><img src="strap.jpg" width="160" height="118" align="left" alt="STRAP"></img></a>
-                                                                    With <a href="http://3d-alignment.eu">STRAP</a> you can align your proteins by
-                                                                    sequence and 3D-structure.  STRAP simultaneously displays
-                                                                    3d-structures, amino acid sequence alignment and nucleotide sequences.
-                                                                    It has powerful annotation features.
-                                                                </td>
-                                                                <td width="50%">
                                                                     <a href="http://www.insightmachines.com/en/vehicleDynamicsEngine.shtml">
-                                                                        <img src="vehicle.jpg" width="160" height="160" align="left" alt=""></img>Vehicle Dynamics Engine Demo</a>
+                                                                        <img src="media/vehicle.jpg" width="160" height="160" align="left" alt="Vehicle Dynamics Engine Demo"></img>Vehicle Dynamics Engine Demo</a>
                                                                     is a Java Web Start demonstration of a 3D physics engine developed by
                                                                     <a href="http://www.insightmachines.com/">Insight Machines</a>. The
                                                                     engine is designed especially for car games. The demo uses JOGL and
                                                                     employs such techniques like shadow casting using the stencil buffer.
                                                                 </td>
+
+                                                                <td width="50%">
+
+                                                                    <a href="http://chronotext.org/"><img src="media/chronotext.jpg" width="160" height="120" align="left" alt="chronotext"></img>
+                                                                        chronotext</a> is a series
+                                                                    of visual design experiments involving animated text and 3D objects
+                                                                    and surfaces. Several examples can be run on-line via <a
+                                                                        href="http://chronotext.org/scriptorium/behind/index.htm">Java Web
+                                                                        Start</a>. See the <a href="http://www.chronotext.org/mapping/">latest
+                                                                        experiments</a> of mapping text on to real 3D surfaces.
+                                                                </td>
                                                             </tr>
 
                                                             <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.vlsolutions.com/">
-                                                                        <img src="vldocking.jpg" width="160" height="113" align="left" alt="VLDocking"></img>VLDocking</a> is
-                                                                    a set of Java components that helps the Swing developer to build
-                                                                    applications with Docking capabilities, and even raise existing
-                                                                    applications to higher standards. It supports docking via drag and
-                                                                    drop, enhanced toolbars, closable tabs, and more. It fully supports
-                                                                    heavyweight components such as JOGL's GLCanvas in a docking
-                                                                    environment.
+                                                                    <a href="http://www.avengina.org/"><img src="media/avengina.jpg" alt="Avengina" align="left" height="99" width="160"></img>Avengina</a> is a
+                                                                    realtime 3D graphics engine which is designed for the execution as a
+                                                                    Java applet. Alternatively it can be launched as a Java Webstart
+                                                                    application outside the browserwindow. The software provides the
+                                                                    possibility to exhibit texts and images in virtual
+                                                                    galleries. Regarding the control and behaviour of the avatar it's
+                                                                    redolent of a game engine. The graphics rendering system bases on
+                                                                    per-pixel lighting and supports normal mapping, specular lighting and
+                                                                    stencil volume shadows. Avengina uses JOGL for realtime rendering.
                                                                 </td>
+
+                                                                <td >
+                                                                    <a href="http://netbeans-opengl-pack.dev.java.net/">
+                                                                        <img src="media/NetBeansOpenGLPackLogo160.png" width="160" height="159" align="left" alt="NOGL Pack logo"></img>
+                                                                        The NetBeans OpenGL Pack</a> provides an easy to use OpenGL development
+                                                                    environment integrated into NetBeans. It supplies modules like an GLSL
+                                                                    shader editor, hardware compiler/linker integration and tools for
+                                                                    displaying hardware information. The pack ships ready to run JOGL (JSR
+                                                                    231) demo projects and all OpenGL samples of the OpenGL Programming
+                                                                    Guide (also known as the Red Book).
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
                                                                 <td width="50%">
-                                                                    <a href="http://www.nascar.com/trackpass/about/raceview/"><img src="raceview.jpg" width="160" height="92" align="left" alt=""></img>
+                                                                    <a href="http://www.nascar.com/trackpass/about/raceview/"><img src="media/raceview.jpg" width="160" height="92" align="left" alt="RaceView"></img>
                                                                         RaceView</a> from NASCAR / NEXTEL, part of the <a
                                                                         href="http://www.nascar.com/trackpass/">TrackPass</a> package, puts
                                                                     you in the race. Control the virtual camera angle, listen to the
                                                                     driver and team, and see crucial statistics and times, all in real
                                                                     time as the race goes on. RaceView uses JOGL for its 3D rendering.
                                                                 </td>
+
+                                                                <td width="50%">
+                                                                    <a href="http://www.insparia.com/"><img src="media/insparia.jpg" width="160" height="160" align="left" alt="Insparia"></img>
+                                                                        Insparia</a> was created to help people
+                                                                    easily visualize, construct and track information about a 3d
+                                                                    environment online. Shape and texture importing as well as a robust
+                                                                    renderer will be available in the final commercial version.  Insparia
+                                                                    uses JOGL to allow the user to construct and interact with their 3d
+                                                                    environment in real-time. Please note that Insparia is in alpha
+                                                                    testing. Feedback is appreciated.
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td width="50%">
+                                                                    <b>Discontinued ..</b>
+                                                                </td>
+                                                                <td width="50%">
+                                                                    <b>.. projects</b>
+                                                                </td>
                                                             </tr>
                                                             <tr>
                                                                 <td width="50%">
+                                                                    <a href="http://www.madlix.com"><img src="media/madlix.png" width="160"
+                                                                                                         height="160" align="left" alt="Madlix"></img>MADLIX</a> lets users insert
+                                                                    3D-content in web pages, blogs, Google pages, community presentations
+                                                                    and more. MADLIX is JOGL-powered and runs smoothly inside all
+                                                                    Java-enabled browsers, with no need for custom plug-ins or application
+                                                                    installation. The <a href="http://www.madlix.com">on-line gallery</a>
+                                                                    features high-quality content ready for insertion. MADLIX is
+                                                                    accompanied by the MADLIX exporter tool enabling 3D artists to
+                                                                    directly export their 3D artwork from Autodesk Maya to the MADLIX
+                                                                    gallery. The exporter features pre-view functionality as well as a
+                                                                    standalone viewer, supporting the MADLIX file format and the open
+                                                                    standard file format COLLADA.
+
+                                                                </td>
+                                                                <td width="50%">
+                                                                    <a href="https://zg3d.dev.java.net/"><img src="media/zg3d.png" width="160" height="160" align="left" alt="ZG3D"></img>
+                                                                        ZG3D</a> is an open source project that uses
+                                                                    JOGL for visualizing 3D geometries with the emphasis of plotting
+                                                                    scientific data in a web application. Geometry objects in an XML file
+                                                                    or string can be dynamically loaded and removed. An HTML document may
+                                                                    call ZG3D functions through JavaScript and may define JavaScript
+                                                                    functions to receive messages from ZG3D, which makes it very easy and
+                                                                    flexible to embed interactive 3D web visualization. The software is
+                                                                    developed at the <a
+                                                                        href="http://www-cger.nies.go.jp/index.html">Center for Global
+                                                                        Environmental Research</a>, Japan, for the advanced data visualization
+                                                                    of the <a href="http://db.cger.nies.go.jp/g3db/ggtu/trajectory.html">Global Greenhouse Gases Database</a>.
+                                                                </td>
+                                                            </tr>
+
+                                                            <tr>
+                                                                <td  width="50%">
+                                                                    <a href="http://www.simulation.com/products/glstudio/glstudio.html"><img
+                                                                            src="media/glstudio.jpg" width="160" height="135" align="left" alt="GL Studio"></img>
+                                                                        GL Studio</a> is an object oriented rapid application
+                                                                    development tool that allows a user to graphically combine
+                                                                    photographs, 3D models and behavior logic to create advanced 2D and 3D
+                                                                    human machine interfaces.  GL Studio generates Java or C++ source code
+                                                                    which can then be integrated into the user’s application as a user
+                                                                    interface. <a
+                                                                        href="http://www.simulation.com/products/glstudio/java/java.html">Java
+                                                                        code</a> generated with GL Studio can be deployed using
+                                                                    javax.swing.JPanel, java.awt.Canvas and JavaBeans. GL Studio uses
+                                                                    OpenGL for rendering and GL Studio for Java uses the JOGL API.
+
+                                                                </td>
+
+                                                                <td width="50%">
+                                                                    <a href="http://www.vlsolutions.com/">
+                                                                        <img src="media/vldocking.jpg" width="160" height="113" align="left" alt="VLDocking"></img>VLDocking</a> is
+                                                                    a set of Java components that helps the Swing developer to build
+                                                                    applications with Docking capabilities, and even raise existing
+                                                                    applications to higher standards. It supports docking via drag and
+                                                                    drop, enhanced toolbars, closable tabs, and more. It fully supports
+                                                                    heavyweight components such as JOGL's GLCanvas in a docking
+                                                                    environment.
+                                                                </td>
+                                                            </tr>
+
+                                                            <!--- abandoned JOGL ..
+                                                            <tr>
+                                                                <td >
+                                                                    <a href="http://openendedgroup.com/field"><img src="media/field.png"
+                                                                                                                   width="160" height="159" align="left" alt="Field"></img>Field</a> is an
+                                                                    open-source development environment for digital art and experimental
+                                                                    code writing. Built around the needs of programmers that manipulate
+                                                                    images, make animations and compose music, Field seeks to tie
+                                                                    text-based programming with ad hoc visual metaphors. Field uses Python
+                                                                    and other programming languages and wants to be integrated into your
+                                                                    own personal code-base. And it comes with special support for the <a
+                                                                        href="http://processing.org/">Processing</a> environment. Field uses
+                                                                    JOGL for its UI and its built-in drawing system; it provides a
+                                                                    JOGL-based scene-graph library for 3D visualization.
+                                                                </td>
+                                                            </tr>
+                                                                <td width="50%">
                                                                     <a href="http://www.eclipse.org/gef3d/"><img src="http://wiki.eclipse.org/images/thumb/b/be/Gef3d_sample_ecore3D.png/800px-Gef3d_sample_ecore3D.png" width="160" height="94" align="left" alt="GEF3d"></img>
                                                                         GEF3D</a> is an Eclipse GEF extension bringing 3D to diagram editing.
                                                                     That is with GEF3D you can create 3D diagrams, 2D diagrams and combine
@@ -472,13 +566,8 @@
                                                                     controller classes. Instead of drawing 2D figures, you can now draw 3D figures.
                                                                     Existing GEF-based 2D editors can be embedded into 3D editors with minimal effort.
                                                                 </td>
-                                                                <td width="50%">
-                                                                    <a href="http://gephi.org/"><img src="gephi.jpg" width="160" height="102" align="left" alt="Gephi"></img>
-                                                                        Gephi</a>  is a visualization and exploration
-                                                                    platform for all kinds of networks and complex systems,
-                                                                    dynamic and hierarchical graphs.
-                                                                </td>
-                                                            </tr>
+                                                            --->
+
                                                         </tbody>
                                                     </table>
                                                 </td>
diff --git a/www/media/EverplanesLogo_160x160.png b/www/media/EverplanesLogo_160x160.png
new file mode 100644
index 0000000..4513118
Binary files /dev/null and b/www/media/EverplanesLogo_160x160.png differ
diff --git a/www/media/Frog-Craft3_2.160w.png b/www/media/Frog-Craft3_2.160w.png
new file mode 100644
index 0000000..64fefd0
Binary files /dev/null and b/www/media/Frog-Craft3_2.160w.png differ
diff --git a/www/media/Frog-Craft3_2.png b/www/media/Frog-Craft3_2.png
new file mode 100644
index 0000000..4da8907
Binary files /dev/null and b/www/media/Frog-Craft3_2.png differ
diff --git a/www/media/JebGL_logo.160w.png b/www/media/JebGL_logo.160w.png
new file mode 100644
index 0000000..416ec9f
Binary files /dev/null and b/www/media/JebGL_logo.160w.png differ
diff --git a/www/media/JebGL_logo.png b/www/media/JebGL_logo.png
new file mode 100644
index 0000000..8891216
Binary files /dev/null and b/www/media/JebGL_logo.png differ
diff --git a/www/NetBeansOpenGLPackLogo160.png b/www/media/NetBeansOpenGLPackLogo160.png
similarity index 100%
rename from www/NetBeansOpenGLPackLogo160.png
rename to www/media/NetBeansOpenGLPackLogo160.png
diff --git a/www/artofillusion.jpg b/www/media/artofillusion.jpg
similarity index 100%
rename from www/artofillusion.jpg
rename to www/media/artofillusion.jpg
diff --git a/www/avengina.jpg b/www/media/avengina.jpg
similarity index 100%
rename from www/avengina.jpg
rename to www/media/avengina.jpg
diff --git a/www/media/c3d-studio.jpg b/www/media/c3d-studio.jpg
new file mode 100644
index 0000000..a3be188
Binary files /dev/null and b/www/media/c3d-studio.jpg differ
diff --git a/www/chronotext.jpg b/www/media/chronotext.jpg
similarity index 100%
rename from www/chronotext.jpg
rename to www/media/chronotext.jpg
diff --git a/www/elflightengine-160x122.png b/www/media/elflightengine-160x122.png
similarity index 100%
rename from www/elflightengine-160x122.png
rename to www/media/elflightengine-160x122.png
diff --git a/www/fenggui.jpg b/www/media/fenggui.jpg
similarity index 100%
rename from www/fenggui.jpg
rename to www/media/fenggui.jpg
diff --git a/www/field.png b/www/media/field.png
similarity index 100%
rename from www/field.png
rename to www/media/field.png
diff --git a/www/fusion-laboratory.jpg b/www/media/fusion-laboratory.jpg
similarity index 100%
rename from www/fusion-laboratory.jpg
rename to www/media/fusion-laboratory.jpg
diff --git a/www/media/geogebra-screenshot-tangents.png b/www/media/geogebra-screenshot-tangents.png
new file mode 100644
index 0000000..8607abe
Binary files /dev/null and b/www/media/geogebra-screenshot-tangents.png differ
diff --git a/www/gephi.jpg b/www/media/gephi.jpg
similarity index 100%
rename from www/gephi.jpg
rename to www/media/gephi.jpg
diff --git a/www/media/glg2d-demo.png b/www/media/glg2d-demo.png
new file mode 100644
index 0000000..662c6e3
Binary files /dev/null and b/www/media/glg2d-demo.png differ
diff --git a/www/glstudio.jpg b/www/media/glstudio.jpg
similarity index 100%
rename from www/glstudio.jpg
rename to www/media/glstudio.jpg
diff --git a/www/impact.jpg b/www/media/impact.jpg
similarity index 100%
rename from www/impact.jpg
rename to www/media/impact.jpg
diff --git a/www/insparia.jpg b/www/media/insparia.jpg
similarity index 100%
rename from www/insparia.jpg
rename to www/media/insparia.jpg
diff --git a/www/jackflowers.jpg b/www/media/jackflowers.jpg
similarity index 100%
rename from www/jackflowers.jpg
rename to www/media/jackflowers.jpg
diff --git a/www/jake2.jpg b/www/media/jake2.jpg
similarity index 100%
rename from www/jake2.jpg
rename to www/media/jake2.jpg
diff --git a/www/media/jogl-applet-moviecube01-small.png b/www/media/jogl-applet-moviecube01-small.png
new file mode 100644
index 0000000..124c88c
Binary files /dev/null and b/www/media/jogl-applet-moviecube01-small.png differ
diff --git a/www/media/jogl-applet-moviecube01.png b/www/media/jogl-applet-moviecube01.png
new file mode 100644
index 0000000..a22c560
Binary files /dev/null and b/www/media/jogl-applet-moviecube01.png differ
diff --git a/www/media/jreality-logo-discreteksurfaces.png b/www/media/jreality-logo-discreteksurfaces.png
new file mode 100644
index 0000000..1499545
Binary files /dev/null and b/www/media/jreality-logo-discreteksurfaces.png differ
diff --git a/www/madlix.png b/www/media/madlix.png
similarity index 100%
rename from www/madlix.png
rename to www/media/madlix.png
diff --git a/www/media/map_of_illarion.png b/www/media/map_of_illarion.png
new file mode 100644
index 0000000..c8bb0c1
Binary files /dev/null and b/www/media/map_of_illarion.png differ
diff --git a/www/mbt.jpg b/www/media/mbt.jpg
similarity index 100%
rename from www/mbt.jpg
rename to www/media/mbt.jpg
diff --git a/www/media/pebbles.png b/www/media/pebbles.png
new file mode 100644
index 0000000..5f4c1de
Binary files /dev/null and b/www/media/pebbles.png differ
diff --git a/www/processing.jpg b/www/media/processing.jpg
similarity index 100%
rename from www/processing.jpg
rename to www/media/processing.jpg
diff --git a/www/raceview.jpg b/www/media/raceview.jpg
similarity index 100%
rename from www/raceview.jpg
rename to www/media/raceview.jpg
diff --git a/www/scilab.png b/www/media/scilab.png
similarity index 100%
rename from www/scilab.png
rename to www/media/scilab.png
diff --git a/www/sculpteo_3_robot_72dpi_sm.jpg b/www/media/sculpteo_3_robot_72dpi_sm.jpg
similarity index 100%
rename from www/sculpteo_3_robot_72dpi_sm.jpg
rename to www/media/sculpteo_3_robot_72dpi_sm.jpg
diff --git a/www/specksim.jpg b/www/media/specksim.jpg
similarity index 100%
rename from www/specksim.jpg
rename to www/media/specksim.jpg
diff --git a/www/strap.jpg b/www/media/strap.jpg
similarity index 100%
rename from www/strap.jpg
rename to www/media/strap.jpg
diff --git a/www/vehicle.jpg b/www/media/vehicle.jpg
similarity index 100%
rename from www/vehicle.jpg
rename to www/media/vehicle.jpg
diff --git a/www/vldocking.jpg b/www/media/vldocking.jpg
similarity index 100%
rename from www/vldocking.jpg
rename to www/media/vldocking.jpg
diff --git a/www/worldwind.jpg b/www/media/worldwind.jpg
similarity index 100%
rename from www/worldwind.jpg
rename to www/media/worldwind.jpg
diff --git a/www/zg3d.png b/www/media/zg3d.png
similarity index 100%
rename from www/zg3d.png
rename to www/media/zg3d.png
diff --git a/www/pebbles.png b/www/pebbles.png
deleted file mode 100644
index 1ccefc9..0000000
Binary files a/www/pebbles.png and /dev/null differ
diff --git a/www/sun-contributor-agreement.pdf b/www/sun-contributor-agreement.pdf
deleted file mode 100644
index f2860ea..0000000
Binary files a/www/sun-contributor-agreement.pdf and /dev/null differ
diff --git a/www/tck-license.html b/www/tck-license.html
deleted file mode 100644
index d4c69e5..0000000
--- a/www/tck-license.html
+++ /dev/null
@@ -1,39 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML>
-<HEAD>
-</HEAD>
-<BODY>
-<P>
-<B>Java<SUP>TM</SUP> Binding for the OpenGL<SUP>®</SUP> API Technology Compatibility Kit</B>
-</P>
-
-<P>
-If you would like to build and distribute your own release of the Java
-Binding for the OpenGL API, you will need to first certify that it is
-compatible with the specification by running the TCK on your release.
-</P>
-
-<P>
-To execute the <A HREF="License_TCK_JSR231.pdf">Java Binding for the
-OpenGL API TCK agreement</A>, sign it and send it to:
-</P>
-
-<DL>
-<DD>
-JOGL <BR>
-Sun Microsystems, Inc. <BR>
-Attn: Travis Bryson <BR>
-4220 Network Circle <BR>
-MS: USCA22-212 <BR>
-Santa Clara, CA 95054, USA <BR>
-</DL>
-
-<P>
-Once we receive and record your signed TCK agreement, we will provide
-you with a copy of the TCK.  For any questions and support you can
-send email to jsr231support at sun.com (add a "-" in between "jsr231" and
-"support").
-</P>
-
-</BODY>
-</HTML>
diff --git a/www/viewerVR.png b/www/viewerVR.png
deleted file mode 100644
index 8571777..0000000
Binary files a/www/viewerVR.png and /dev/null differ

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-java/libjogl2-java.git



More information about the pkg-java-commits mailing list