diff --git a/.gitignore b/.gitignore
index 77952237828937714acb1a05f283a7a85d6de800..5fdf1359ad6f4999cec1738cd2a9fe2667773e11 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,6 @@ CTestTestfile.cmake
 CMakeFiles
 cmake_install.cmake
 stage
-dng
 gipltng
 ost
 *_tests
@@ -27,12 +26,25 @@ CMakeLists.txt.user
 OpenStructure.cbp
 DartConfiguration.tcl
 Testing
+*~
 README.html
 CPackConfig.cmake
 CPackSourceConfig.cmake
-deployment/macos/DNG.app
-deployment/macos/standalone
+/deployment/macos/DNG.app
+/deployment/macos/standalone
 ChemLib
 components.cif
 compounds.chemlib
-deployment/macos/openstructure.dmg
+/deployment/macos/openstructure.dmg
+/scripts/dng
+*.vcproj
+*.user
+*.dir
+*.sln
+*.ncb
+*suo
+Release
+RelWithDebInfo
+Debug
+*.cxx_parameters
+/deployment/win/create_archive.bat
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 08575372b9f41c3d2b6091bad61327232eb529c2..82b1b67d718e2b0e6f3b8ff1a7e1485772f9995a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,272 +1,292 @@
-#-------------------------------------------------------------------------------
-# Author: Marco Biasini
-#-------------------------------------------------------------------------------
-
-cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake_support)
-include(OST)
-
-project(OpenStructure CXX C)
-
-option(USE_SHADER "whether to compile with shader support"
-       OFF)
-option(SET_RPATH "embed rpath upon make install"
-       OFF)
-option(COMPILE_TMTOOLS "whether to compile the tmalign and tmscore programs"
-       OFF)
-option(PROFILE "whether to compile with profiling support"
-       OFF)       
-option(ENABLE_GUI "whether the graphical user interface should be enabled"
-       ON)
-option(ENABLE_GFX "whether graphics support should be enabled"
-      ON)
-option(ENABLE_IMG "whether the image processing module should be compiled"
-       ON)
-option(USE_DOUBLE_PRECISION "whether to compile in double precision" 
-       OFF)
-option(ENABLE_SPNAV "whether 3DConnexion devices should be supported"
-      OFF)
-option(STATIC_PROPERTY_WORKAROUND "workaround for static property bug with some boost/boost_python combinations" OFF)
-option(DEPLOYMENT "switch on deployment settings" OFF)
-option(COMPILE_TESTS "wheter unit tests should be compiled by default" OFF)
-
-if (PREFIX)
-  set(CMAKE_INSTALL_PREFIX ${PREFIX})
-endif()
-
-if (SYS_ROOT)
-  set(CMAKE_PREFIX_PATH ${SYS_ROOT})
-endif()
-
-if (OPTIMIZE)
-  set(CMAKE_BUILD_TYPE Release)
-  set(_OPT ON)
-else()
-   set(CMAKE_BUILD_TYPE Debug)
-    set(_OPT OFF)
-endif()
-
-if (USE_DOUBLE_PRECISION)
-  set(_DOUBLE_PREC ON)
-else()
-  set(_DOUBLE_PREC OFF)
-  set(_DOUBLE_PREC OFF)
-endif()
-
-if (NOT ENABLE_GFX)
-  set(ENABLE_GUI OFF)
-endif()
-
-if (ENABLE_GUI)
-  set(_UI ON)
-else()
-  set(_UI OFF)
-endif()
-
-if (ENABLE_GFX)
-  set(_OPENGL ON)
-else()
-  set(_OPENGL OFF)
-endif()
-
-if (USE_SHADER)
-  set(_SHADER ON)
-else()
-  set(_SHADER OFF)
-endif()
-if (COMPILE_TMTOOLS)
-  set(_TM_TOOLS ON)
-else()
-  set(_TM_TOOLS OFF)
-endif()
-if (ENABLE_IMG)
-  set(_IMG ON)
-else()
-  set(_IMG OFF)
-endif()
-if (PROFILE)
-  set(_PROFILE ON)
-else()
-  set(_PROFILE OFF)
-endif()
-
-if (COMPOUND_LIB)
-  set(_COMP_LIB "${COMPOUND_LIB}")
-  if (NOT IS_ABSOLUTE "${COMPOUND_LIB}")
-    set(COMPOUND_LIB "${CMAKE_CURRENT_SOURCE_DIR}/${COMPOUND_LIB}")
-  endif()
-else()
-  set(_COMP_LIB "NONE")
-endif()
-
-if (STATIC_PROPERTY_WORKAROUND)
-  set(_STATICPROPS ON)
-else()
-  set(_STATICPROPS OFF)
-endif()
-
-if (NOT CMAKE_BUILD_TYPE)
-  set(CMAKE_BUILD_TYPE Debug)
-endif()
-
-set(STAGE_DIR "${CMAKE_BINARY_DIR}/stage")
-set(EXECUTABLE_OUTPUT_PATH ${STAGE_DIR}/bin)
-set(HEADER_STAGE_PATH ${STAGE_DIR}/include)
-set(SHARED_DATA_PATH ${STAGE_DIR}/share/openstructure)
-include_directories("${HEADER_STAGE_PATH}")
-link_directories(${LIB_STAGE_PATH})
-
-
-
-if (UNIX AND NOT APPLE)
-  check_architecture()
-endif()
-set (ARCH ${CMAKE_NATIVE_ARCH})
-if ("${ARCH}" MATCHES "64")
-  set(LIB_DIR lib64)
-  set(LIB_STAGE_PATH "${STAGE_DIR}/lib64")
-else()
-  set(LIB_DIR lib)
-  set(LIB_STAGE_PATH "${STAGE_DIR}/lib")
-endif()
-
-file(MAKE_DIRECTORY ${STAGE_DIR} 
-     ${EXECUTABLE_OUTPUT_PATH} 
-     ${HEADER_STAGE_PATH}
-     ${LIB_STAGE_PATH})
-
-if (WIN32)
-   # add_definitions(-DBOOST_TEST_INCLUDED)
-   
-   add_definitions(-D_USE_MATH_DEFINES -D_CRT_SECURE_NO_DEPRECATE 
-                   -D_SCL_SECURE_NO_DEPRECATE -DNOMINMAX)
-   add_definitions(-Zc:wchar_t-)   #  
-  # add_definitions(-MDd -vmg -EHsc -GR)
-  #GR:Uses the __fastcall calling convention (x86 only).
-  #-EHsc to specify the synchronous exception handling mode/
-  #-vmg Uses full generality for pointers to members.
-  add_definitions(-DBOOST_ZLIB_BINARY=zdll)
-  #add_definitions(-NODEFAULTLIB:LIBCMTD.lib)
-endif()
-
-function(get_compiler_version _OUTPUT_VERSION)
-  exec_program(${CMAKE_CXX_COMPILER} 
-               ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion
-               OUTPUT_VARIABLE _COMPILER_VERSION
-  )
-  string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2"
-    _COMPILER_VERSION ${_COMPILER_VERSION})
-
-  set(${_OUTPUT_VERSION} ${_COMPILER_VERSION} PARENT_SCOPE)
-endfunction()
-
-if (CMAKE_COMPILER_IS_GNUCXX)
-  get_compiler_version(_GCC_VERSION)
-  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
-  if (_GCC_VERSION MATCHES "44")
-    # gcc 4.4. is very strict about aliasing rules. the shared_count
-    # implementation that is used boost's shared_ptr violates these rules. To
-    # silence the warnings and prevent miscompiles, enable
-    #  -fno-strict-aliasing
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-strict-aliasing")
-  endif()
-  if (APPLE AND NOT _GCC_VERSION MATCHES "42")
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
-  endif()
-endif()
-
-set(CMAKE_LIBRARY_OUTPUT_DIRECTORY)
-set(_BOOST_MIN_VERSION 1.37)
-find_package(Boost ${_BOOST_MIN_VERSION} 
-             COMPONENTS filesystem system REQUIRED)
-set(BOOST_LIBRARIES ${Boost_LIBRARIES})
-set(Boost_LIBRARIES)
-find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS iostreams REQUIRED)
-set(BOOST_IOSTREAM_LIBRARIES ${Boost_LIBRARIES})
-set(Boost_LIBRARIES)
-find_package(Boost ${_BOOST_MIN_VERSION} 
-             COMPONENTS unit_test_framework REQUIRED)
-set(BOOST_UNIT_TEST_LIBRARIES ${Boost_LIBRARIES})
-set(Boost_LIBRARIES)
-find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS python REQUIRED)
-set(BOOST_PYTHON_LIBRARIES ${Boost_LIBRARIES})
-set(Boost_LIBRARIES)
-find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS program_options REQUIRED)
-set(BOOST_PROGRAM_OPTIONS_LIBRARIES ${Boost_LIBRARIES})
-set(Boost_LIBRARIES)
-find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS regex REQUIRED)
-set(BOOST_REGEX_LIBRARIES ${Boost_LIBRARIES})
-#find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS math REQUIRED)
-#set(BOOST_MATH_LIBRARIES ${Boost_LIBRARIES})
-
-find_package(Qt4 4.5.0 REQUIRED)
-find_package(OpenGL REQUIRED)
-find_package(PNG REQUIRED)
-find_package(Eigen 2.0.0 REQUIRED)
-find_package(Python 2.4 REQUIRED)
-
-if (ENABLE_IMG)
-  find_package(FFTW REQUIRED)
-  find_package(TIFF REQUIRED)
-endif()
-
-if (ENABLE_GUI)
-  ost_find_python_module(sip)
-  ost_find_python_module(PyQt4)
-endif()
-
-if (ENABLE_SPNAV)
-  find_package(SpNav REQUIRED)
-endif()
-
-# basic environment
-include_directories(${Boost_INCLUDE_DIRS} 
-                    ${FFTW_INCLUDE_PATH} 
-                    ${EIGEN2_INCLUDE_DIR}
-                    ${TIFF_INCLUDE_DIR}
-                    ${SPNAV_INCLUDE_DIR}
-                    )
-if (UNIX)
-  SET(CMAKE_SKIP_BUILD_RPATH  FALSE)
-  SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
-  if(USE_RPATH)
-    set(_USE_RPATH ON)
-    SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}")
-    SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
-  else()
-    set(_USE_RPATH OFF)
-   SET(CMAKE_INSTALL_RPATH "")
-   SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
-  endif() 
-endif()
-
-
-add_subdirectory(modules)
-add_subdirectory(scripts)
-add_subdirectory(deployment)
-set(FILES_TO_BE_REMOVED CMakeFiles stage tests)
-set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES
-                         "${FILES_TO_BE_REMOVED}")
-
-#ost_match_boost_python_version(${PYTHON_LIBRARIES})
-
-message(STATUS 
-        "OpenStructure will be built with the following options:\n"
-        "   Install Prefix                  (-PREFIX) : ${CMAKE_INSTALL_PREFIX}\n"
-        "   RPath in install            (-DUSE_RPATH) : ${_USE_RPATH}\n"
-        "   Graphical interface        (-DENABLE_GUI) : ${_UI}\n"
-        "   OpenGL support             (-DENABLE_GFX) : ${_OPENGL}\n"
-        "   Image Processing support   (-DENABLE_IMG) : ${_IMG}\n"
-        "   Shader support             (-DUSE_SHADER) : ${_SHADER}\n"
-        "   Optimize                     (-DOPTIMIZE) : ${_OPT}\n"
-        "   Profiling support             (-DPROFILE) : ${_PROFILE}\n"
-        "   Double Precision (-DUSE_DOUBLE_PRECISION) : ${_DOUBLE_PREC}\n"
-        "   Compound Lib             (-DCOMPOUND_LIB) : ${_COMP_LIB}\n"
-        "   TMAlign and TMScore   (-DCOMPILE_TMTOOLS) : ${_TM_TOOLS}")
-        
-# doc target to create HTML documentation
-#set(SPHINX sphinx-build)
-#set(SPHINX_OPTIONS -c doc/conf -b html -d doc/html/doctrees)
-#add_custom_target(doc COMMAND 
-#                  ${SPHINX} ${SPHINX_OPTIONS} modules doc/html
-#                  VERBATIM)
+#-------------------------------------------------------------------------------
+# Author: Marco Biasini
+#-------------------------------------------------------------------------------
+
+cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake_support)
+include(OST)
+
+project(OpenStructure CXX C)
+
+option(USE_SHADER "whether to compile with shader support"
+       OFF)
+option(SET_RPATH "embed rpath upon make install"
+       OFF)
+option(COMPILE_TMTOOLS "whether to compile the tmalign and tmscore programs"
+       OFF)
+option(PROFILE "whether to compile with profiling support"
+       OFF)       
+option(ENABLE_GUI "whether the graphical user interface should be enabled"
+       ON)
+option(ENABLE_GFX "whether graphics support should be enabled"
+      ON)
+option(ENABLE_IMG "whether the image processing module should be compiled"
+       ON)
+option(USE_DOUBLE_PRECISION "whether to compile in double precision" 
+       OFF)
+option(ENABLE_SPNAV "whether 3DConnexion devices should be supported"
+      OFF)
+option(STATIC_PROPERTY_WORKAROUND "workaround for static property bug with some boost/boost_python combinations" OFF)
+option(DEPLOYMENT "switch on deployment settings" OFF)
+option(COMPILE_TESTS "wheter unit tests should be compiled by default" OFF)
+option(ENABLE_STATIC "whether static libraries should be compiled" OFF)
+if (CXX)
+  set(CMAKE_CXX_COMPILER ${CXX})
+endif()
+
+if (CC)
+  set(CMAKE_C_COMPILER ${CC})
+endif()
+
+if (FORTRAN_COMPILER)
+  set(CMAKE_FORTRAN_COMPILER ${FORTRAN_COMPILER})
+endif()
+
+
+if (PREFIX)
+  set(CMAKE_INSTALL_PREFIX ${PREFIX})
+endif()
+
+if (SYS_ROOT)
+  set(CMAKE_PREFIX_PATH ${SYS_ROOT})
+endif()
+
+if (OPTIMIZE)
+  set(CMAKE_BUILD_TYPE Release)
+  set(_OPT ON)
+else()
+   set(CMAKE_BUILD_TYPE Debug)
+    set(_OPT OFF)
+endif()
+
+if (USE_DOUBLE_PRECISION)
+  set(_DOUBLE_PREC ON)
+else()
+  set(_DOUBLE_PREC OFF)
+  set(_DOUBLE_PREC OFF)
+endif()
+
+if (NOT ENABLE_GFX)
+  set(ENABLE_GUI OFF)
+endif()
+
+if (ENABLE_GUI)
+  set(_UI ON)
+else()
+  set(_UI OFF)
+endif()
+
+if (ENABLE_GFX)
+  set(_OPENGL ON)
+else()
+  set(_OPENGL OFF)
+endif()
+
+if (USE_SHADER)
+  set(_SHADER ON)
+else()
+  set(_SHADER OFF)
+endif()
+if (COMPILE_TMTOOLS)
+  set(_TM_TOOLS ON)
+else()
+  set(_TM_TOOLS OFF)
+endif()
+if (ENABLE_IMG)
+  set(_IMG ON)
+else()
+  set(_IMG OFF)
+endif()
+if (PROFILE)
+  set(_PROFILE ON)
+else()
+  set(_PROFILE OFF)
+endif()
+
+if (COMPOUND_LIB)
+  set(_COMP_LIB "${COMPOUND_LIB}")
+  if (NOT IS_ABSOLUTE "${COMPOUND_LIB}")
+    set(COMPOUND_LIB "${CMAKE_CURRENT_SOURCE_DIR}/${COMPOUND_LIB}")
+  endif()
+else()
+  set(_COMP_LIB "NONE")
+endif()
+
+if (STATIC_PROPERTY_WORKAROUND)
+  set(_STATICPROPS ON)
+else()
+  set(_STATICPROPS OFF)
+endif()
+
+if (NOT CMAKE_BUILD_TYPE)
+  set(CMAKE_BUILD_TYPE Debug)
+endif()
+
+set(STAGE_DIR "${CMAKE_BINARY_DIR}/stage")
+set(EXECUTABLE_OUTPUT_PATH ${STAGE_DIR}/bin)
+set(HEADER_STAGE_PATH ${STAGE_DIR}/include)
+set(SHARED_DATA_PATH ${STAGE_DIR}/share/openstructure)
+include_directories("${HEADER_STAGE_PATH}")
+link_directories(${LIB_STAGE_PATH})
+
+
+
+if (UNIX AND NOT APPLE)
+  check_architecture()
+endif()
+set (ARCH ${CMAKE_NATIVE_ARCH})
+if ("${ARCH}" MATCHES "64")
+  set(LIB_DIR lib64)
+  set(LIB_STAGE_PATH "${STAGE_DIR}/lib64")
+else()
+  set(LIB_DIR lib)
+  set(LIB_STAGE_PATH "${STAGE_DIR}/lib")
+endif()
+
+file(MAKE_DIRECTORY ${STAGE_DIR} 
+     ${EXECUTABLE_OUTPUT_PATH} 
+     ${HEADER_STAGE_PATH}
+     ${LIB_STAGE_PATH})
+
+if (WIN32)
+   # add_definitions(-DBOOST_TEST_INCLUDED)
+   
+   add_definitions(-D_USE_MATH_DEFINES -D_CRT_SECURE_NO_DEPRECATE 
+                   -D_SCL_SECURE_NO_DEPRECATE -DNOMINMAX)
+   add_definitions(-Zc:wchar_t-)   #  
+  # add_definitions(-MDd -vmg -EHsc -GR)
+  #GR:Uses the __fastcall calling convention (x86 only).
+  #-EHsc to specify the synchronous exception handling mode/
+  #-vmg Uses full generality for pointers to members.
+  add_definitions(-DBOOST_ZLIB_BINARY=zdll)
+  #add_definitions(-NODEFAULTLIB:LIBCMTD.lib)
+endif()
+
+function(get_compiler_version _OUTPUT_VERSION)
+  exec_program(${CMAKE_CXX_COMPILER} 
+               ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion
+               OUTPUT_VARIABLE _COMPILER_VERSION
+  )
+  string(REGEX REPLACE "([0-9])\\.([0-9])(\\.[0-9])?" "\\1\\2"
+    _COMPILER_VERSION ${_COMPILER_VERSION})
+
+  set(${_OUTPUT_VERSION} ${_COMPILER_VERSION} PARENT_SCOPE)
+endfunction()
+
+if (CMAKE_COMPILER_IS_GNUCXX)
+  get_compiler_version(_GCC_VERSION)
+  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
+  if (_GCC_VERSION MATCHES "44")
+    # gcc 4.4. is very strict about aliasing rules. the shared_count
+    # implementation that is used boost's shared_ptr violates these rules. To
+    # silence the warnings and prevent miscompiles, enable
+    #  -fno-strict-aliasing
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-strict-aliasing")
+  endif()
+endif()
+
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY)
+set(_BOOST_MIN_VERSION 1.37)
+
+find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS python REQUIRED)
+set(BOOST_PYTHON_LIBRARIES ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+find_package(Boost ${_BOOST_MIN_VERSION} 
+             COMPONENTS unit_test_framework REQUIRED)
+set(BOOST_UNIT_TEST_LIBRARIES ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+if (ENABLE_STATIC)
+  set(Boost_USE_STATIC_LIBS ON)
+endif()
+find_package(Boost ${_BOOST_MIN_VERSION} 
+             COMPONENTS filesystem system REQUIRED)
+set(BOOST_LIBRARIES ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS iostreams REQUIRED)
+set(BOOST_IOSTREAM_LIBRARIES ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS program_options REQUIRED)
+set(BOOST_PROGRAM_OPTIONS ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+find_package(Boost ${_BOOST_MIN_VERSION} COMPONENTS regex REQUIRED)
+set(BOOST_REGEX_LIBRARIES ${Boost_LIBRARIES})
+set(Boost_LIBRARIES)
+
+        
+find_package(Qt4 4.5.0 REQUIRED)
+find_package(OpenGL REQUIRED)
+find_package(PNG REQUIRED)
+find_package(Eigen 2.0.0 REQUIRED)
+find_package(Python 2.4 REQUIRED)
+
+if (ENABLE_IMG)
+  find_package(FFTW REQUIRED)
+  find_package(TIFF REQUIRED)
+endif()
+
+
+if (ENABLE_STATIC)
+  set(Boost_LIBRARIES)
+  set(Boost_USE_STATIC_LIBS ON)
+  find_package(Boost ${_BOOST_MIN_VERSION} 
+               COMPONENTS filesystem system iostreams regex REQUIRED)
+  message(${Boost_LIBRARIES})
+  find_package(ZLIB REQUIRED)
+  set(STATIC_LIBRARIES ${Boost_LIBRARIES} ${FFTW_LIBRARIES} ${TIFF_LIBRARIES} 
+      ${PNG_LIBRARIES} ${ZLIB_LIBRARIES})
+endif()
+
+if (ENABLE_GUI)
+  ost_find_python_module(sip)
+  ost_find_python_module(PyQt4)
+endif()
+
+if (ENABLE_SPNAV)
+  find_package(SpNav REQUIRED)
+endif()
+
+# basic environment
+include_directories(${Boost_INCLUDE_DIRS} 
+                    ${FFTW_INCLUDE_PATH} 
+                    ${EIGEN2_INCLUDE_DIR}
+                    ${TIFF_INCLUDE_DIR}
+                    ${SPNAV_INCLUDE_DIR}
+                    )
+if (UNIX)
+  SET(CMAKE_SKIP_BUILD_RPATH  FALSE)
+  SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
+  if(USE_RPATH)
+    set(_USE_RPATH ON)
+    SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}")
+    SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
+  else()
+    set(_USE_RPATH OFF)
+   SET(CMAKE_INSTALL_RPATH "")
+   SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
+  endif() 
+endif()
+
+
+add_subdirectory(modules)
+add_subdirectory(scripts)
+add_subdirectory(deployment)
+set(FILES_TO_BE_REMOVED CMakeFiles stage tests)
+set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES
+                         "${FILES_TO_BE_REMOVED}")
+
+#ost_match_boost_python_version(${PYTHON_LIBRARIES})
+
+message(STATUS 
+        "OpenStructure will be built with the following options:\n"
+        "   Install Prefix                  (-PREFIX) : ${CMAKE_INSTALL_PREFIX}\n"
+        "   RPath in install            (-DUSE_RPATH) : ${_USE_RPATH}\n"
+        "   Graphical interface        (-DENABLE_GUI) : ${_UI}\n"
+        "   OpenGL support             (-DENABLE_GFX) : ${_OPENGL}\n"
+        "   Image Processing support   (-DENABLE_IMG) : ${_IMG}\n"
+        "   Shader support             (-DUSE_SHADER) : ${_SHADER}\n"
+        "   Optimize                     (-DOPTIMIZE) : ${_OPT}\n"
+        "   Profiling support             (-DPROFILE) : ${_PROFILE}\n"
+        "   Double Precision (-DUSE_DOUBLE_PRECISION) : ${_DOUBLE_PREC}\n"
+        "   Compound Lib             (-DCOMPOUND_LIB) : ${_COMP_LIB}\n"
+        "   TMAlign and TMScore   (-DCOMPILE_TMTOOLS) : ${_TM_TOOLS}\n"
+        "   Static Libraries       (-DENABLE_STATIC)  : ${ENABLE_STATIC}")
diff --git a/cmake_support/OST.cmake b/cmake_support/OST.cmake
index 9d928f6c946de5ce7a3c3f1d64991a98b2392d02..10ec36703b5dd3d278461f4e35ea9aeb01f5c218 100644
--- a/cmake_support/OST.cmake
+++ b/cmake_support/OST.cmake
@@ -136,7 +136,7 @@ macro(module)
   #-----------------------------------------------------------------------------
   set(_ARGS "NAME;SOURCES;HEADERS;DEPENDS_ON;LINK;HEADER_OUTPUT_DIR;PREFIX")
   set(_ARG_PREFIX ost)  
-  parse_argument_list(_ARG "${_ARGS}" "" ${ARGN})  
+  parse_argument_list(_ARG "${_ARGS}" "NO_STATIC" ${ARGN})  
   if (NOT _ARG_NAME)
     message(FATAL_ERROR 
             "invalid use of module(): a module name must be provided")
@@ -178,7 +178,7 @@ macro(module)
       endif()
     endforeach()
     add_library(${_LIB_NAME} SHARED ${_ABS_SOURCE_NAMES})
-    
+
     set_target_properties(${_LIB_NAME} 
                           PROPERTIES OUTPUT_NAME ${_LIB_NAME}
                                      PROJECT_LABEL ${_ARG_NAME}
@@ -191,6 +191,25 @@ macro(module)
                           LIBRARY_OUTPUT_DIRECTORY ${LIB_STAGE_PATH}
                           ARCHIVE_OUTPUT_DIRECTORY ${LIB_STAGE_PATH}
                           RUNTIME_OUTPUT_DIRECTORY ${LIB_STAGE_PATH})
+    if (ENABLE_STATIC AND NOT _ARG_NO_STATIC)
+      add_library(${_LIB_NAME}_static STATIC ${_ABS_SOURCE_NAMES})
+      set_target_properties(${_LIB_NAME}_static
+                            PROPERTIES OUTPUT_NAME ${_LIB_NAME}
+                                       PROJECT_LABEL ${_ARG_NAME}
+                                       EchoString   ${_ARG_NAME}
+                                       MODULE_DEPS "${_ARG_DEPENDS_ON}")
+      get_target_property(_DEFS ${_LIB_NAME}_static COMPILE_DEFINITIONS)
+      set_target_properties(${_LIB_NAME}_static PROPERTIES
+                            COMPILE_DEFINITIONS OST_MODULE_${_UPPER_LIB_NAME})
+      set_target_properties(${_LIB_NAME}_static PROPERTIES
+                            LIBRARY_OUTPUT_DIRECTORY ${LIB_STAGE_PATH}
+                            ARCHIVE_OUTPUT_DIRECTORY ${LIB_STAGE_PATH}
+                            RUNTIME_OUTPUT_DIRECTORY ${LIB_STAGE_PATH})
+      foreach(_DEPENDENCY ${_ARG_DEPENDS_ON})
+        target_link_libraries(${_LIB_NAME}_static ost_${_DEPENDENCY}_static)
+      endforeach()
+      target_link_libraries(${_LIB_NAME} ${ZLIB_LIBRARIES})
+    endif()
     if (APPLE)
       set_target_properties(${_LIB_NAME} PROPERTIES
                             LINK_FLAGS "-Wl,-rpath,."
@@ -268,20 +287,24 @@ endmacro()
 #-------------------------------------------------------------------------------
 macro(executable)
   parse_argument_list(_ARG 
-                      "NAME;SOURCES;LINK;DEPENDS_ON" "NO_RPATH" ${ARGN})
+                      "NAME;SOURCES;LINK;DEPENDS_ON" "NO_RPATH;STATIC" ${ARGN})
   if (NOT _ARG_NAME)
     message(FATAL_ERROR "invalid use of executable(): a name must be provided")
   endif()
   add_executable(${_ARG_NAME} ${_ARG_SOURCES})
-  if (APPLE AND NOT _ARG_NO_RPATH)
+  if (APPLE AND NOT _ARG_NO_RPATH AND NOT _ARG_STATIC)
     set_target_properties(${_ARG_NAME} PROPERTIES
                           LINK_FLAGS "-Wl,-rpath,@loader_path/../lib")
   endif()
   if (_ARG_LINK)
     target_link_libraries(${_ARG_NAME} ${_ARG_LINK})
   endif()
+  if (ENABLE_STATIC AND _ARG_STATIC)
+    set(TARGET_SUFFIX _static)
+    target_link_libraries(${_ARG_NAME} ${STATIC_LIBRARIES})
+  endif()
   foreach(_DEP ${_ARG_DEPENDS_ON})
-    target_link_libraries(${_ARG_NAME} ost_${_DEP})
+    target_link_libraries(${_ARG_NAME} ost_${_DEP}${TARGET_SUFFIX})
   endforeach()
   install(TARGETS ${_ARG_NAME} DESTINATION bin)
 endmacro()
@@ -508,7 +531,7 @@ macro(ost_unittest MODULE SOURCE_FILES)
         target_link_libraries(${_test_name} ${BOOST_UNIT_TEST_LIBRARIES}
                             "ost_${MODULE}")
         add_custom_target("${_test_name}_run"
-                        COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${_test_name} || echo 
+                        COMMAND OST_ROOT=${STAGE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/${_test_name} || echo 
                         WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
                         COMMENT "running checks for module ${MODULE}"
                         DEPENDS ${_test_name})
diff --git a/deployment/linux/create_bundle.py b/deployment/linux/create_bundle.py
index b5a6f281f602def83c1318c93112e4ffdb186555..43e980f9dbfed5f355ead57d1501823d5b15e5cd 100644
--- a/deployment/linux/create_bundle.py
+++ b/deployment/linux/create_bundle.py
@@ -3,6 +3,7 @@ import shutil
 import subprocess
 import string
 import sys
+import datetime
 
 
 # custom parameters
@@ -39,13 +40,10 @@ if uname_line[0].find('x86_64') !=-1:
 else: 
   libdir='lib'
   archstring='32bit'
-svninfo_output=subprocess.Popen('svn info', shell=True, cwd='../../',stdout=subprocess.PIPE).stdout
-svninfo_lines=svninfo_output.readlines()
-svninfo_split=string.split(svninfo_lines[4])
-revstring=svninfo_split[1]
-directory_name='openstructure-linux-'+archstring+'-'+additional_label+'-rev'+revstring
-print 'Stripping subversion information to avoid accidental commit'
-subprocess.call('rm -rf $(find . -name .svn)',shell=True,cwd='../../')
+date_pattern='%Y-%b-%d'
+build=str(datetime.datetime.now())
+stamp=datetime.datetime.strptime(build, date_pattern)
+directory_name='openstructure-linux-'+archstring+'-'+additional_label+stamp
 print 'Hardcoding package python binary path in openstructure executables'
 subprocess.call('mv scripts/ost.in scripts/ost.in.backup',shell=True,cwd='../../')
 subprocess.call('sed "s/@PYTHON_BINARY@/\$DNG_ROOT\/bin\/'+python_bin_in_bundle+'/g" scripts/ost.in.backup > scripts/ost.in.prepreprepre',shell=True,cwd='../../')
diff --git a/deployment/macos/deploy.py b/deployment/macos/deploy.py
index 60d45e647da40c0b94d806b6a8107cdc6569049e..dea9207ab211bf8b210ff1cf0b62748140a04def 100644
--- a/deployment/macos/deploy.py
+++ b/deployment/macos/deploy.py
@@ -9,6 +9,7 @@ p.add_option('--bundle', action='store_true', default=False)
 p.add_option('--no_rpath', action='store_true',
              default=False)
 p.add_option('--macports_workaround', action='store_true', default=False)
+p.add_option('--dmg', action='store_true', default=False)
 opts, args=p.parse_args()
 deps.make_standalone('../../stage', 'standalone', True, 
                      opts.no_rpath, 
@@ -18,6 +19,9 @@ if os.path.exists('DNG.app'):
 bundle.create_bundle('DNG', opts.bundle)
 if opts.bundle:
   shutil.copytree('../../examples', 'DNG.app/Contents/examples')
-  os.system('rm `find DNG.app/Contents/examples/ -name "*.pyc"`')
-  os.system('rm -rf DNG.app/Contents/examples/harmony')
-  os.system('rm -rf DNG.app/Contents/examples/dokk')  
\ No newline at end of file
+  os.system('rm `find DNG.app/Contents/examples/ -name "*.pyc"` 2> /dev/null')
+  os.system('rm -rf DNG.app/Contents/examples/demos/harmony')
+  os.system('rm -rf DNG.app/Contents/examples/demos/dokk')
+  if opts.dmg:
+    os.system('rm -rf openstructure.dmg')
+    os.system('hdiutil create -srcFolder DNG.app openstructure.dmg')
\ No newline at end of file
diff --git a/deployment/macos/deps.py b/deployment/macos/deps.py
index 460071d1b7effb0eb7477549f9495699891729da..b74fd30ef929f8ca4c371aca8504cf09c0465a68 100644
--- a/deployment/macos/deps.py
+++ b/deployment/macos/deps.py
@@ -50,9 +50,10 @@ def collect_deps(stage_dir, components, binaries, site_packages,
     if bin_name not in pool:
       _deps_for_lib(bin_name, pool)
   for site_package in site_packages:
-    full_path=os.path.join(site_packages_dir, site_package)
+    full_path=get_python_module_path(site_package)
+    print full_path
     if not os.path.exists(full_path):
-      print 'WARNING', site_package, 'does not exists'
+      print 'WARNING:', site_package, 'does not exists'
       continue
     if os.path.isdir(full_path):
       for so_file in glob.glob(os.path.join(full_path, '*.so')):
@@ -202,6 +203,14 @@ def get_site_package_dir():
       return p[:index+len(pattern)]
   raise RuntimeError("Couldn't determine site-packages location")
 
+def get_python_module_path(module):
+  for path in sys.path:
+    full_path=os.path.join(path, module)
+    if os.path.exists(full_path):
+      return full_path
+  return None
+  
+  
 def get_python_home():
   """
   Derive Python home by looking at the location of the os module
@@ -300,7 +309,7 @@ def make_standalone(stage_dir, outdir, no_includes, force_no_rpath=False,
     open(ost_script, 'w').write(script)
     os.chmod(ost_script, 0555)
   elif use_rpath==False:
-    print 'BIG FAT WARNING: Creation bundle with @executable_path and default'
+    print 'BIG FAT WARNING: Creating bundle with @executable_path and default'
     print 'Python might not work. Test carefully before deploying.'
 
   if no_includes:
@@ -308,7 +317,7 @@ def make_standalone(stage_dir, outdir, no_includes, force_no_rpath=False,
     os.system(REMOVE_CURRENT % outdir)  
   print 'copying site-packages'
   for sp in SITE_PACKAGES:
-    src=os.path.join(site_packages, sp)  
+    src=get_python_module_path(sp)
     if os.path.isdir(src):
       shutil.copytree(src, os.path.join(outdir, 'lib/openstructure', sp))
     else:
diff --git a/doc/conf/conf.py b/doc/conf/conf.py
index e37ac88a4dba6c8b16869ba1964cb688104aa527..c99ef1783eb0c53305d4dc96d925f1a93314d499 100644
--- a/doc/conf/conf.py
+++ b/doc/conf/conf.py
@@ -49,9 +49,9 @@ copyright = u'2010, OpenStructure authors'
 # built documents.
 #
 # The short X.Y version.
-version = '1.0'
+version = '1.1'
 # The full version, including alpha/beta/rc tags.
-release = '1.0'
+release = '1.1'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
diff --git a/doc/make.py b/doc/make.py
index 1653dc73eb1ba177b05530200027f5e3bf90dd61..8fb157390b4e6635dde1d68e890b2fe2d8be868b 100644
--- a/doc/make.py
+++ b/doc/make.py
@@ -67,7 +67,9 @@ def _CollectRstDocs(outdir, dirname, fnames):
 def ParseArgs():
   parser = OptionParser("usage: ost make.py [options] ")
   parser.add_option("-l","--linkcheck", action="store_true", default=False, dest="linkcheck", help="validate all external links")
-  parser.add_option("-b", "--build-html", action="store_true", default=False, dest="html", help="build html documentation")
+  parser.add_option("-b", "--build-html", action="store_true",
+                    default=False, dest="html", help="build html documentation")
+  parser.add_option('-j', '--build-json', action='store_true', default=False)
   parser.add_option("-d", "--doctest", action="store_true", default=False, dest="doctest", help="run all test")
   parser.add_option("-q", "--quiet", action="store_true", default=False, dest="quiet", help="run all test")
   return parser.parse_args()
@@ -88,10 +90,13 @@ sphinx_bin=settings.Locate(['sphinx-build', 'sphinx-build-2.6'])
 
 if opts.html:
   os.system('%s %s -b html -c %s %s %s' % (sphinx_bin, opt_str, 'doc/conf', 'doc/source', 
-                                      'doc/build'))
+                                      'doc/build/html'))
 if opts.doctest:
   os.system('%s %s -b doctest -c %s %s %s' % (sphinx_bin, opt_str, 'doc/conf', 'doc/source', 
-                                      'doc/build'))
+                                      'doc/build/doctest'))
+if opts.build_json:
+  os.system('%s %s -b json -c %s %s %s' % (sphinx_bin, opt_str, 'doc/conf', 'doc/source',
+                                      'doc/build/json'))
 if opts.linkcheck:
   os.system('%s %s -b linkcheck -c %s %s %s' % (sphinx_bin, opt_str, 'doc/conf', 'doc/source', 
-                                      'doc/build'))
+                                      'doc/build/check'))
diff --git a/examples/code_fragments/dokk/datafiles/hud.ini b/examples/code_fragments/dokk/datafiles/hud.ini
index c53f99455b46c22d94147ce10bee3141032b408f..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644
--- a/examples/code_fragments/dokk/datafiles/hud.ini
+++ b/examples/code_fragments/dokk/datafiles/hud.ini
@@ -1,3 +0,0 @@
-[TEXT]
-RMSD: Sie sind %.1f von der L�sung entfernt
-SECONDS: noch %i Sekunden
diff --git a/examples/demos/gfx_mapslab.py b/examples/demos/gfx_mapslab.py
index de59b2e5d1df8ee8386ae75921543139bddefde6..8cc8ca334d2abf5f4dd7911bcb0b77f422da70b1 100644
--- a/examples/demos/gfx_mapslab.py
+++ b/examples/demos/gfx_mapslab.py
@@ -52,6 +52,7 @@ scene.SetCenter(go1.GetCenter())
 
 go2 = gfx.MapSlab("slab",mh,geom.Plane(go1.GetCenter(),geom.Vec3(0.0,0.0,1.0)))
 scene.Add(go2)
-go2.ColorBy(gfx.YELLOW,gfx.GREEN,0.2,0.8)
+
+go2.ColorBy('HEAT_MAP',0.2,0.8)
 
 print 'Demo 4: Projecting the density of a map onto a plane...' 
diff --git a/examples/demos/the_hammer.py b/examples/demos/the_hammer.py
index f6c77ebca38b663fd03b5e922604ccb3a3ef73e8..48970cefb16a8b9bee9a70395b2d5555f86e82cb 100644
--- a/examples/demos/the_hammer.py
+++ b/examples/demos/the_hammer.py
@@ -12,7 +12,7 @@ class Anim(QtCore.QTimer):
         self.b=b
         self.angle=0.0
         self.dir=0.01
-        self.edi=self.a.view.handle.RequestXCSEditor(mol.EditMode.UNBUFFERED_EDIT)
+        self.edi=self.a.view.handle.EditXCS(mol.UNBUFFERED_EDIT)
         QtCore.QObject.connect(self, QtCore.SIGNAL("timeout()"), self.OnTimer)
 
         
@@ -34,17 +34,15 @@ class Anim(QtCore.QTimer):
 
 def Hammer(off=geom.Vec3()):
   ent=mol.CreateEntity()
-  edi=ent.RequestXCSEditor(mol.EditMode.BUFFERED_EDIT)
+  edi=ent.EditXCS(mol.BUFFERED_EDIT)
   chain=edi.InsertChain("A")
   res=edi.AppendResidue(chain, "QUAD")
-  prop=mol.AtomProp()
-  prop.radius=1.0
-  a=edi.InsertAtom(res, "A", off+geom.Vec3(0.0, 0.0, 0.0), prop)
-  b=edi.InsertAtom(res, "B", off+geom.Vec3(0.0, 4.0, 0.0), prop)  
-  c=edi.InsertAtom(res, "C", off+geom.Vec3(2.0, 4.0, 0.0), prop)  
-  d=edi.InsertAtom(res, "D", off+geom.Vec3(2.0, 5.0, 0.0), prop)    
-  e=edi.InsertAtom(res, "E", off+geom.Vec3(-2.0, 5.0, 0.0), prop)      
-  f=edi.InsertAtom(res, "F", off+geom.Vec3(-2.0, 4.0, 0.0), prop)        
+  a=edi.InsertAtom(res, "A", off+geom.Vec3(0.0, 0.0, 0.0), "H")
+  b=edi.InsertAtom(res, "B", off+geom.Vec3(0.0, 4.0, 0.0), "H")
+  c=edi.InsertAtom(res, "C", off+geom.Vec3(2.0, 4.0, 0.0), "H")
+  d=edi.InsertAtom(res, "D", off+geom.Vec3(2.0, 5.0, 0.0), "H")
+  e=edi.InsertAtom(res, "E", off+geom.Vec3(-2.0, 5.0, 0.0), "H")
+  f=edi.InsertAtom(res, "F", off+geom.Vec3(-2.0, 4.0, 0.0), "H")
   edi.Connect(a, b)
   edi.Connect(b, c)
   edi.Connect(c, d)
@@ -55,17 +53,17 @@ def Hammer(off=geom.Vec3()):
 
 def TheWall():
   ent=mol.CreateEntity()
-  edi=ent.RequestXCSEditor(mol.EditMode.BUFFERED_EDIT)
+  edi=ent.EditXCS(mol.BUFFERED_EDIT)
   chain=edi.InsertChain("A")
   res=edi.AppendResidue(chain, "QUAD")
-  prop=mol.AtomProp()
-  prop.radius=0.25
   index=0
   for i in range(-10, 10):
     for j in range(-10, 10):
       index+=1
-      edi.InsertAtom(res, "A%d" % index, geom.Vec3(4.0, -2.0, 0.0)+
-                     geom.Vec3(i, 0, j)*0.25, prop)
+      atom=edi.InsertAtom(res, "A%d" % index, geom.Vec3(4.0, -2.0, 0.0)+
+                          geom.Vec3(i, 0, j)*0.25)
+      atom.radius=0.25
+                     
   return ent
 
 a=Hammer()
diff --git a/examples/gfx/ambient_occlusion1.py b/examples/gfx/ambient_occlusion1.py
new file mode 100644
index 0000000000000000000000000000000000000000..df0d8a7fe2597bc70e1bb35e18b7094385372d9f
--- /dev/null
+++ b/examples/gfx/ambient_occlusion1.py
@@ -0,0 +1,19 @@
+s=io.LoadSurface("../demos/data/sh2","msms")
+scene.Add(gfx.Surface("s",s))
+
+# alternative shading mode
+scene.SetShadingMode("hf")
+
+# add outlines to surface
+scene["s"].SetOutline(True)
+scene["s"].SetOutlineMode(3)
+
+# turn on realtime ambient occlusion
+scene.SetAmbientOcclusion(True)
+
+# strength of the AO effect, default is 1.0
+scene.SetAmbientOcclusionWeight(1.0)
+
+# AO algorithms 0-3, default is 1
+scene.SetAmbientOcclusionMode(1)
+
diff --git a/examples/gfx/ambient_occlusion2.py b/examples/gfx/ambient_occlusion2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce9bc0a403b26a1a5289948a9f08f6acd7788d98
--- /dev/null
+++ b/examples/gfx/ambient_occlusion2.py
@@ -0,0 +1,21 @@
+
+e=io.LoadPDB("../demos/data/sdh.pdb")
+scene.Add(gfx.Entity("x",gfx.CPK,e.Select("chain=A")))
+
+# fast spheres with 3D sprites, default
+scene["x"].GetOptions(gfx.CPK).SetSphereMode(1)
+
+# turn on realtime ambient occlusion
+scene.SetAmbientOcclusion(True)
+
+# strength of the AO effect, default is 1.0
+scene.SetAmbientOcclusionWeight(1.0)
+
+# AO algorithms 0-3, default is 1
+scene.SetAmbientOcclusionMode(1)
+
+# orientation
+scene.SetRTC(geom.Mat4(0.827929,-0.460893,-0.319547,29.688,
+                       0.174973,0.753608,-0.633609,19.9405,
+                       0.532839,0.468671,0.704578,73.0075,
+                       -5.4704,1.54823,-116,1))
diff --git a/examples/gfx/hsc_hemilight.py b/examples/gfx/hsc_hemilight.py
new file mode 100644
index 0000000000000000000000000000000000000000..91a4b8c4fd186a2303989e166cc196c07d4bd220
--- /dev/null
+++ b/examples/gfx/hsc_hemilight.py
@@ -0,0 +1,30 @@
+e=io.LoadPDB("../demos/data/sdh.pdb")
+scene.Add(gfx.Entity("x",gfx.HSC,e.Select("chain=A")))
+scene["x"].GetOptions(gfx.HSC).SetTubeRadius(0.6)
+# spiral helices (default)
+scene["x"].GetOptions(gfx.HSC).SetHelixMode(0)
+# straight strands
+scene["x"].GetOptions(gfx.HSC).SetStrandMode(1)
+# colors
+scene["x"].SetColor(gfx.Color(0.9,0.95,1.0))
+scene["x"].SetColor(gfx.Color(1.0,0.9,0.7),"rtype=helix")
+scene["x"].SetDetailColor(gfx.Color(1.0,0.95,0.78),"rtype=helix")
+scene["x"].SetColor(gfx.Color(0.5,1.0,0.7),"rtype=strand")
+scene["x"].SetDetailColor(gfx.Color(0.7,1.0,0.79),"rtype=strand")
+
+# switch to hemilighting mode
+scene.SetShadingMode("hf")
+# add outline to improved visibility
+scene["x"].Outline(True)
+scene["x"].SetOutlineMode(1)
+scene["x"].SetOutlineWidth(4.5)
+
+# looks best on white bg
+scene.bg=gfx.WHITE
+
+scene.SetRTC(geom.Mat4(-0.589889,-0.594876,0.546034,28.2245,
+                        0.806165,-0.472502,0.356147,20.1685,
+                        0.0461388,0.65028,0.758291,73.5665,
+                        -3.52709,1.72253,-120,1))
+
+
diff --git a/examples/gfx/shadow_mapping.py b/examples/gfx/shadow_mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4260ca317670b039f6eb310224edb3da5429174
--- /dev/null
+++ b/examples/gfx/shadow_mapping.py
@@ -0,0 +1,15 @@
+s=io.LoadSurface("../demos/data/sh2","msms")
+scene.Add(gfx.Surface("s",s))
+
+# alternative shading mode
+scene.SetShadingMode("hf")
+
+# add outlines to surface
+scene["s"].Outline(True)
+scene["s"].SetOutlineMode(3)
+
+# turn on realtime shadow mapping
+scene.SetShadow(True)
+
+scene.SetShadowQuality(3) # default
+
diff --git a/examples/gfx/transp.py b/examples/gfx/transp.py
new file mode 100644
index 0000000000000000000000000000000000000000..76468f0ca0dc2bfc3d695b0810744489cbfa1db1
--- /dev/null
+++ b/examples/gfx/transp.py
@@ -0,0 +1,13 @@
+e=io.LoadPDB("../demos/data/sh2.pdb")
+s=io.LoadSurface("../demos/data/sh2","msms")
+
+scene.Add(gfx.Entity("x",gfx.HSC,e.Select("chain=A")))
+scene["x"].SetColor(gfx.Color(0.9,0.95,1.0))
+scene["x"].SetColor(gfx.Color(1.0,0.9,0.7),"rtype=helix")
+scene["x"].SetColor(gfx.Color(0.5,1.0,0.7),"rtype=strand")
+
+scene.Add(gfx.Surface("s",s))
+scene["s"].SetOpacity(0.4)
+scene["s"].SetMat(0,1,0,0)
+
+scene.bg=gfx.WHITE
diff --git a/modules/base/pymod/__init__.py b/modules/base/pymod/__init__.py
index c6d7a8ec17b8085fb4412236f0bfbbf5f6cc648f..286bedced409ad9f66317d0ee7a71afde1c53082 100644
--- a/modules/base/pymod/__init__.py
+++ b/modules/base/pymod/__init__.py
@@ -27,6 +27,7 @@ from ost import seq
 try:
   from ost import gfx
   scene = gfx.Scene()
+  scene.Stereo=gfx.Stereo
 except ImportError:
   pass
   
diff --git a/modules/base/pymod/stutil.py b/modules/base/pymod/stutil.py
index 75bb922485ac2239d0158b3ba80a33cc05976990..e61a1687c24e4be08ccf40320c4bf49a94603b37 100644
--- a/modules/base/pymod/stutil.py
+++ b/modules/base/pymod/stutil.py
@@ -45,7 +45,20 @@ def Mean(xs):
   """
   if len(xs)==0:
     raise RuntimeError("Can't calculate mean of empty sequence")
-  return sum(xs)/len(xs)
+  return float(sum(xs))/len(xs)
+
+@FloatValueExtract
+def Median(xs):
+  """
+  Calculate median of dataset
+  """
+  if len(xs)==0:
+    raise RuntimeError("Can't calculate median of empty sequence")
+  sorted_xs=sorted(xs)
+  if (len(xs) % 2)==0:
+    return (sorted_xs[(len(xs)-1)/2]+sorted_xs[(len(xs)-1)/2+1])/2.0
+  else:
+    return sorted_xs[(len(xs)-1)/2]
 
 @FloatValueExtract
 def StdDev(xs):
@@ -73,7 +86,7 @@ def Correl(xs, ys):
   
     sum[(xi-<x>)*(yi-<y>)]
   r=----------------------
-          (n-1)*sx*sy
+          sx*sy
           
   where <x>, <y> are the mean of dataset xs and ys, and, sx and sy are the 
   standard deviations.
@@ -90,9 +103,9 @@ def Correl(xs, ys):
     cross_term+=(x-mean_x)*(y-mean_y)
     sigma_x+=(x-mean_x)**2
     sigma_y+=(y-mean_y)**2
-  sigma_x=math.sqrt(sigma_x/len(xs))
-  sigma_y=math.sqrt(sigma_y/len(ys))  
-  return cross_term/((len(xs)-1)*sigma_x*sigma_y)
+  sigma_x=math.sqrt(sigma_x)
+  sigma_y=math.sqrt(sigma_y)
+  return cross_term/(sigma_x*sigma_y)
 
 def Histogram(xs, bounds, num_bins):
   bins=[0 for i in range(num_bins)]
diff --git a/modules/base/pymod/wrap_base.cc b/modules/base/pymod/wrap_base.cc
index 20a6668cbedd99e9137d31c51ccf6de0ac2c515e..790c322018a6150b197bd2f31522225416489a3f 100644
--- a/modules/base/pymod/wrap_base.cc
+++ b/modules/base/pymod/wrap_base.cc
@@ -23,6 +23,7 @@
 #include <ost/base.hh>
 #include <ost/platform.hh>
 #include <ost/message.hh>
+#include <ost/version.hh>
 
 using namespace boost::python;
 
@@ -44,6 +45,11 @@ BOOST_PYTHON_MODULE(_base)
   def("SetPrefixPath", &ost::SetPrefixPath);
   def("GetPrefixPath", &ost::GetPrefixPath);
   def("GetSharedDataPath", &ost::GetSharedDataPath);  
+  
+  scope().attr("VERSION")=OST_VERSION_STRING;
+  scope().attr("VERSION_MAJOR")=OST_VERSION_MAJOR;
+  scope().attr("VERSION_MINOR")=OST_VERSION_MINOR;  
+  scope().attr("VERSION_PATCH")=OST_VERSION_PATCH;
   export_Logger();
   export_Range();
   export_Units();
diff --git a/modules/base/src/export_helper/generic_property_def.hh b/modules/base/src/export_helper/generic_property_def.hh
index 785bcce900b6ab8ee2f5eca3aeb68d5c87923695..84a486bc371c0694002a917d08a988299b59e2fe 100644
--- a/modules/base/src/export_helper/generic_property_def.hh
+++ b/modules/base/src/export_helper/generic_property_def.hh
@@ -156,6 +156,7 @@ void const_generic_prop_def(O& bp_class)
     .def("GetIntProp", get_int2)    
     .def("GetStringProp", get_str1)
     .def("GetStringProp", get_str2)    
+    .def("GetPropList",&C::GetPropList)
     .def("GetGenericBoolProperty", &depr_get_bool_a<C>)
     .def("GetGenericBoolProperty", &depr_get_bool_b<C>)
     .def("GetGenericFloatProperty", &depr_get_float_a<C>)
@@ -180,6 +181,7 @@ void generic_prop_def(O& bp_class)
     .def("SetFloatProp", &C::SetFloatProp)
     .def("SetIntProp", &C::SetIntProp)
     .def("SetStringProp", &C::SetStringProp)
+    .def("GetPropList",&C::GetPropList)
     .def("ClearGenericProperties", &depr_clear_props<C>)
     .def("SetGenericIntProperty", &depr_set_int<C>)
     .def("SetGenericFloatProperty", &depr_set_float<C>)
@@ -189,4 +191,4 @@ void generic_prop_def(O& bp_class)
   ;
 }
 
-#endif
\ No newline at end of file
+#endif
diff --git a/modules/base/src/export_helper/vector.hh b/modules/base/src/export_helper/vector.hh
index 0b262bf5561aac5523112c0ad34cd2c4b4e0e776..68409cc2be62c1b4ad99d0eddd032d2bf1cb55eb 100644
--- a/modules/base/src/export_helper/vector.hh
+++ b/modules/base/src/export_helper/vector.hh
@@ -1,27 +1,37 @@
 #ifndef OST_EXPORT_HELPER_VECTOR_HH
 #define OST_EXPORT_HELPER_VECTOR_HH
 
-# include <boost/python/def_visitor.hpp>
-
+#include <boost/python/def_visitor.hpp>
+#include <boost/python/suite/indexing/container_utils.hpp>
 /*
   Author: Marco Biasini
  */
 
 namespace ost {
 
-
+namespace bp=boost::python;
 template <typename Container>
 class VectorAdditions : 
-  public boost::python::def_visitor<VectorAdditions<Container> > {
+  public bp::def_visitor<VectorAdditions<Container> > {
 public:
+ typedef typename Container::value_type value_type;
+ typedef Container container_type;
  template <class Class>
  void visit(Class& cl) const
  {
    cl
      .def("__str__", &to_string)
+     .def("__init__", make_constructor(&from_iter))
    ;
  }
 private:
+  static boost::shared_ptr<Container> from_iter(const bp::object& obj)
+  {
+    boost::shared_ptr<Container> c(new Container);
+    bp::container_utils::extend_container(*c.get(), obj);
+    return c;
+  }
+  
   static std::string to_string(Container& cl)
   {
     std::stringstream ss;
diff --git a/modules/base/src/fixed_string.hh b/modules/base/src/fixed_string.hh
index a7858cf06185d8f716157228c18fb91feb005d56..fac1ba6cdc744cebc597808a158759f7f17e503b 100644
--- a/modules/base/src/fixed_string.hh
+++ b/modules/base/src/fixed_string.hh
@@ -55,7 +55,9 @@ public:
   bool operator!=(const FixedString<LENGTH>& rhs) const {
     return !this->operator==(rhs);
   }
-
+  size_t capacity() const {
+    return LENGTH;
+  }
   FixedString<LENGTH>& operator=(const String& rhs) {
     this->assign(rhs);
     return *this;
@@ -68,6 +70,8 @@ public:
   const char* c_str() const {
     return bytes_;
   }
+  char* data() { return bytes_; }
+  const char* data() const { return bytes_; }
 private:
   void assign(const String& str) {
     assert(str.length()<=LENGTH);
diff --git a/modules/base/src/generic_property.hh b/modules/base/src/generic_property.hh
index 12e53932e1ad7217bb50d7eefdded0733cc7e5c3..8787d95bd0632507630fd01cd874a991a410945e 100644
--- a/modules/base/src/generic_property.hh
+++ b/modules/base/src/generic_property.hh
@@ -31,6 +31,7 @@
 #include <exception>
 #include <sstream>
 #include <map>
+#include <vector>
 #include <boost/variant.hpp>
 
 #include <ost/module_config.hh>
@@ -109,6 +110,7 @@ public:
       map_->erase(key);
     }
   }
+
   void Assign(const GenericPropContainerImpl& impl)
   {
     if (impl.map_) {
@@ -130,6 +132,17 @@ public:
     return *map_;
   }
       
+  std::vector<String> GetPropList() const
+  {
+    std::vector<String> prop_list;
+    if (map_) {
+      PropertyMap::const_iterator i;
+      for (i=map_->begin(); i!=map_->end(); ++i) {
+        prop_list.push_back(i->first);
+      }
+    }
+    return prop_list;
+  }
   
 private:
   mutable PropertyMap* map_;
@@ -189,12 +202,13 @@ public:
     rep << this->GetImpl()->GenericProp(key);
     return rep.str();
   }  
-    /// \brief returns String property, raises an exception if it does not exist
-    String GetStringProp(const String& key) const
-    {
-      CheckHandleValidity(*static_cast<const H*>(this));      
-      return this->gp_get<String>(key);
-    }
+
+  /// \brief returns String property, raises an exception if it does not exist
+  String GetStringProp(const String& key) const
+  {
+    CheckHandleValidity(*static_cast<const H*>(this));
+    return this->gp_get<String>(key);
+  }
 
   /// \brief returns floating point property, raises an exception if it does 
   ///     not exist
@@ -279,6 +293,12 @@ public:
     CheckHandleValidity(*static_cast<const H*>(this));    
     return this->GetImpl()->GetPropMap();
   }  
+
+  std::vector<String> GetPropList() const
+  {
+    CheckHandleValidity(*static_cast<const H*>(this));
+    return this->GetImpl()->GetPropList();
+  }
 };
 
 /// \brief base class for the handler classes
diff --git a/modules/base/tests/CMakeLists.txt b/modules/base/tests/CMakeLists.txt
index be13a37fffbbb6a8a52fd62c535ff856266c5726..d18e16f0765d8c2cd562338655b90f6ed9e97750 100644
--- a/modules/base/tests/CMakeLists.txt
+++ b/modules/base/tests/CMakeLists.txt
@@ -2,6 +2,7 @@ set(OST_BASE_UNIT_TESTS
   test_generic_property.cc
   test_string_ref.cc
   test_pod_vector.cc
+  test_stutil.py
   tests.cc
 )
 
diff --git a/modules/base/tests/test_generic_property.cc b/modules/base/tests/test_generic_property.cc
index 9fad50c49e5e876868e995518cf8419975987120..8b946685cbb0da482e024adf87c0901a09217119 100644
--- a/modules/base/tests/test_generic_property.cc
+++ b/modules/base/tests/test_generic_property.cc
@@ -29,7 +29,7 @@ BOOST_AUTO_TEST_SUITE( base )
 BOOST_AUTO_TEST_CASE( test_generic_property )
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor editor=eh.RequestXCSEditor();  
+  XCSEditor editor=eh.EditXCS();  
   ChainHandle ch=editor.InsertChain("A");
   ResidueHandle res = editor.AppendResidue(ch, "X");
   AtomHandle atom = editor.InsertAtom(res, "Y",geom::Vec3());
diff --git a/modules/base/tests/test_stutil.py b/modules/base/tests/test_stutil.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cc4570b5605b5eb47c7507e0d0aa7f942f66496
--- /dev/null
+++ b/modules/base/tests/test_stutil.py
@@ -0,0 +1,92 @@
+import unittest
+from ost import stutil
+
+class TestStUtils(unittest.TestCase):
+
+  def setUp(self):
+    self.data1 = [0,1,2,3,4,5,6,-5,-4,-3,-2,-1,1]
+    self.data2 = [1,2,3,4,5,6,7,8,9,10,11,12,13]
+    self.data3 = [0.1,0.5,0.7,2.4,0.5,4.1,0.9,-1.1,-0.5,0.7,-1.4,-7.5,8.5]
+    self.data_short = [0,1]
+    self.data_short2 = [0,1,2]
+
+    self.mean = 0.5384615385
+    self.mean2 = 0.6076923077
+    self.median = 1
+    self.median2 = 0.5
+    self.median_short = 0.5
+    self.median_short2 = 1.0
+    self.stddev = 3.3192998478
+    self.stddev2 = 3.4192805223
+    self.minimum = -5
+    self.minimum2 = -7.5
+    self.maximum = 6
+    self.maximum2 = 8.5
+    self.correl = -0.39639313
+    self.correl2 = -0.0619291504
+
+
+  def isSimilar(self, value, reference, accuracy):
+    if abs(value - reference) <= accuracy:
+      return True
+    return False
+
+  def testMean(self):
+    assert self.isSimilar(stutil.Mean(self.data1), self.mean, 0.001), \
+           "Mean (%f) does not correspond to precalculated mean (%f)" % \
+           (stutil.Mean(self.data1), self.mean)
+    assert self.isSimilar(stutil.Mean(self.data3), self.mean2, 0.001), \
+           "Mean (%f) does not correspond to precalculated mean (%f)" % \
+           (stutil.Mean(self.data3), self.mean2)
+
+  def testMedian(self):
+    assert self.isSimilar(stutil.Median(self.data1), self.median, 0.001), \
+           "Median (%f) does not correspond to precalculated median (%f)" % \
+           (stutil.Median(self.data1), self.median)
+    assert self.isSimilar(stutil.Median(self.data3), self.median2, 0.001), \
+           "Median (%f) does not correspond to precalculated median (%f)" % \
+           (stutil.Median(self.data3), self.median2)
+    assert self.isSimilar(stutil.Median(self.data_short), self.median_short, 0.001), \
+           "Median (%f) does not correspond to precalculated median (%f)" % \
+           (stutil.Median(self.data_short), self.median_short)
+    assert self.isSimilar(stutil.Median(self.data_short2), self.median_short2, 0.001), \
+           "Median (%f) does not correspond to precalculated median (%f)" % \
+           (stutil.Median(self.data_short2), self.median_short2)
+
+  def testStddev(self):
+    assert self.isSimilar(stutil.StdDev(self.data1), self.stddev, 0.001), \
+           "StdDev (%f) does not correspond to precalculated StdDev (%f)" % \
+           (stutil.StdDev(self.data1), self.stddev)
+    assert self.isSimilar(stutil.StdDev(self.data3), self.stddev2, 0.001), \
+           "StdDev (%f) does not correspond to precalculated StdDev (%f)" % \
+           (stutil.StdDev(self.data3), self.stddev2)
+
+  def testMinimum(self):
+    assert self.isSimilar(stutil.Min(self.data1), self.minimum, 0.001), \
+           "Minimum (%f) does not correspond to precalculated minimum (%f)" % \
+           (stutil.Min(self.data1), self.minimum)
+    assert self.isSimilar(stutil.Min(self.data3), self.minimum2, 0.001), \
+           "Minimum (%f) does not correspond to precalculated minimum (%f)" % \
+           (stutil.Min(self.data3), self.minimum2)
+
+  def testMaximum(self):
+    assert self.isSimilar(stutil.Max(self.data1), self.maximum, 0.001), \
+           "Maximum (%f) does not correspond to precalculated maximum (%f)" % \
+           (stutil.Max(self.data1), self.maximum)
+    assert self.isSimilar(stutil.Max(self.data3), self.maximum2, 0.001), \
+           "Maximum (%f) does not correspond to precalculated maximum (%f)" % \
+           (stutil.Max(self.data3), self.maximum2)
+
+  def testCorrel(self):
+    assert self.isSimilar(stutil.Correl(self.data1, self.data2), self.correl, 0.001), \
+           "Correl (%f) does not correspond to precalculated correl (%f)" % \
+           (stutil.Correl(self.data1, self.data2), self.correl)
+    assert self.isSimilar(stutil.Correl(self.data3, self.data2), self.correl2, 0.001), \
+           "Correl (%f) does not correspond to precalculated correl (%f)" % \
+           (stutil.Correl(self.data3, self.data2), self.correl2)
+
+if __name__ == "__main__":
+  try:
+    unittest.main()
+  except Exception, e:
+    print e
\ No newline at end of file
diff --git a/modules/bindings/pymod/CMakeLists.txt b/modules/bindings/pymod/CMakeLists.txt
index f91dc53d8e46178f80f41f6140a3fdcc8424ee01..89244b23f96c53c63e8b44385d3c64a1c07e197e 100644
--- a/modules/bindings/pymod/CMakeLists.txt
+++ b/modules/bindings/pymod/CMakeLists.txt
@@ -1,2 +1,13 @@
-pymod(NAME bindings PY __init__.py lga.py hbplus.py msms.py tmtools.py 
-                       dssp.py clustalw.py utils.py naccess.py)
+set(OST_BINDINGS
+__init__.py
+lga.py
+hbplus.py
+msms.py
+tmtools.py 
+dssp.py
+clustalw.py
+utils.py
+naccess.py
+blast.py
+)
+pymod(NAME bindings PY ${OST_BINDINGS})
diff --git a/modules/bindings/pymod/blast.py b/modules/bindings/pymod/blast.py
new file mode 100644
index 0000000000000000000000000000000000000000..32e36e3bf37fd4860111b76425efea56c8547659
--- /dev/null
+++ b/modules/bindings/pymod/blast.py
@@ -0,0 +1,122 @@
+from ost import settings
+import subprocess
+from xml.dom import minidom
+from ost import io, seq
+import ost
+import re
+import os
+class AlignedPatch:
+  def __init__(self, aln, bit_score, score, evalue):
+    self.aln=aln
+    self.bit_score=bit_score
+    self.score=score
+    self.evalue=evalue
+
+class BlastHit:
+  """
+  A positive match found by BLAST.
+  
+  Each blast hit consists of one or more aligned patches. 
+  
+  """
+  def __init__(self, identifier, aligned_patches):
+    self.identifier=identifier
+    self.aligned_patches=aligned_patches
+
+def ParseBlastOutput(string):
+  """
+  Parses the blast output and returns a list of BlastHits
+  """
+  def _GetText(node):
+    rc=''
+    for child in node.childNodes:
+        if child.nodeType==child.TEXT_NODE:
+            rc+=child.data
+    return rc
+      
+  def _GetValue(node, tag_name):
+    tag=node.getElementsByTagName(tag_name)
+    assert len(tag)==1
+    return _GetText(tag[0])
+    
+  def _GetInt(node, tag_name):
+    return int(_GetValue(node, tag_name))
+
+  def _ParseHsp(query_id, hit_id, hsp):
+    bit_score=float(_GetValue(hsp, 'Hsp_bit-score'))
+    score=float(_GetValue(hsp, 'Hsp_score'))
+    evalue=float(_GetValue(hsp, 'Hsp_evalue'))
+    query_offset=_GetInt(hsp, 'Hsp_query-from')-1
+    hit_offset=_GetInt(hsp, 'Hsp_hit-from')-1
+    query_seq=seq.CreateSequence(str(query_id), str(_GetValue(hsp, 'Hsp_qseq')))
+    query_seq.offset=query_offset
+    hit_seq=seq.CreateSequence(str(hit_id), str(_GetValue(hsp, 'Hsp_hseq')))
+    hit_seq.offset=hit_offset
+    aln=seq.CreateAlignment(query_seq, hit_seq)
+    return AlignedPatch(aln, bit_score, score, evalue)
+  try:
+    doc=minidom.parseString(string)
+  except Exception, e:
+    ost.LogError('Error while parsing BLAST output: %s' % str(e))
+    return None
+  hits=[]
+  query_id=_GetValue(doc, 'BlastOutput_query-def')
+  for hit in doc.getElementsByTagName('Hit'):
+    hit_id=_GetValue(hit, 'Hit_def')
+    hsps=hit.getElementsByTagName('Hsp')
+    aligned_patches=[_ParseHsp(query_id, hit_id, hsp) for hsp in hsps]
+    hits.append(BlastHit(hit_id, aligned_patches))
+  return hits
+
+
+
+class BlastError(RuntimeError):
+  def __init__(self, brief, details):
+    self.brief=brief
+    self.details=details
+
+  def __str__(self):
+    if self.details:
+      return '%s\n%s' % (self.brief, self.details)
+    else:
+      return self.brief
+
+def Blast(query, database, gap_open=11, gap_ext=1, matrix='BLOSUM62',
+         blast_location=None):
+  """
+  Runs a protein vs. protein blast search. The results are returned as a 
+  list of :class:`BlastHit` instances.
+  
+  :param query: the query sequence
+  :type query: :class:`seq.ConstSequenceHandle`
+  
+  :param database: The filename of the sequence database. Make sure that 
+      formatdb has been run on the database and the <database>.pin file exists.
+  :param matrix: The substitution matrix to be used. Must be one of 'BLOSUM45',
+     'BLOSUM62', 'BLOSUM80', 'PAM30', 'PAM70'.
+  :param gap_open: Gap opening penalty. Note that only a subset of gap opening 
+     penalties is supported for each substitutition matrix. Consult the blast 
+     docs for more information.
+  :param gap_ext: Gap extension penalty. Only a subset of gap extension 
+     penalties are supported for each of the substitution matrices. Consult the 
+     blast docs for more information.
+  """
+  subst_mats=('BLOSUM45', 'BLOSUM62', 'BLOSUM80', 'PAM30', 'PAM70',)
+  if matrix not in subst_mats:
+    raise ValueError('matrix must be one of %s' % ', '.join(subst_mats))
+  if not os.path.exists('%s.pin' % database):
+    raise IOError("Database %s does not exist" % database)
+  blastall_exe=settings.Locate('blastall', explicit_file_name=blast_location)
+  args=[blastall_exe, '-d', database, '-p', 'blastp', 
+        '-m', '7', '-M', matrix, '-G', str(gap_open), '-E', str(gap_ext)]
+  ost.LogInfo('running BLAST (%s)' % ' '.join(args))
+  blast_pipe=subprocess.Popen(args, stderr=subprocess.PIPE, 
+                              stdout=subprocess.PIPE, stdin=subprocess.PIPE)
+  stdout, stderr=blast_pipe.communicate(io.SequenceToString(query, 'fasta'))
+  if len(stderr)>0:
+     pattern=re.compile(r'^\[.*\]\s+ERROR:\s+(.*)')
+     lines=stderr.split('\n')
+     error_message=pattern.match(lines[0])
+     if error_message:
+       raise BlastError(error_message.group(1), '\n'.join(lines[1:]))
+  return ParseBlastOutput(stdout)
diff --git a/modules/bindings/pymod/clustalw.py b/modules/bindings/pymod/clustalw.py
index f61d4f24f3f074badf749ae01f29b6893364dd87..2c2fd6ebac5cf580dd1a259cb087a0ada9a127c4 100644
--- a/modules/bindings/pymod/clustalw.py
+++ b/modules/bindings/pymod/clustalw.py
@@ -3,7 +3,8 @@ from ost import settings, io, seq, LogError
 import os
 import subprocess
 
-def ClustalW(seq1, seq2=None, clustalw=None, keep_files=False):
+def ClustalW(seq1, seq2=None, clustalw=None, keep_files=False, nopgap=False, 
+             clustalw_option_string=False):
   clustalw_path=settings.Locate(('clustalw', 'clustalw2'), 
                                 explicit_file_name=clustalw)
   
@@ -13,8 +14,8 @@ def ClustalW(seq1, seq2=None, clustalw=None, keep_files=False):
       seq_list.AddSequence(seq1)
       seq_list.AddSequence(seq2)
     elif isinstance(seq1, str) and isinstance(seq2, str):
-      seqh1=CreateSequence("seq1", seq1)
-      seqh2=CreateSequence("seq2", seq2)
+      seqh1=seq.CreateSequence("seq1", seq1)
+      seqh2=seq.CreateSequence("seq2", seq2)
       seq_list=seq.CreateSequenceList()
       seq_list.AddSequence(seqh1)
       seq_list.AddSequence(seqh2)
@@ -32,6 +33,11 @@ def ClustalW(seq1, seq2=None, clustalw=None, keep_files=False):
   command='%s -infile="%s" -output=fasta -outfile="%s"' % (clustalw_path,
                                                            temp_dir.files[0],
                                                            out)
+  if nopgap:
+    command+=" -nopgap"
+  if clustalw_option_string!=False:
+    command=command+" "+clustalw_option_string  #see useful flags: http://toolkit.tuebingen.mpg.de/clustalw/help_params
+
   ps=subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
   ps.stdout.readlines()
   aln=io.LoadAlignment(out)
diff --git a/modules/bindings/pymod/msms.py b/modules/bindings/pymod/msms.py
index dc3b8590626aad471534d47ce660220d616800d9..d928f6c57ae1ddcdd8abd0f1af3d3163e070eac0 100644
--- a/modules/bindings/pymod/msms.py
+++ b/modules/bindings/pymod/msms.py
@@ -38,6 +38,21 @@ class MsmsProcessError(Exception):
     return repr(self.returncode)
 
 
+def GetVersion(msms_exe=None, msms_env=None):
+  msms_executable = _GetExecutable(msms_exe, msms_env)
+  command = "%s" % (msms_executable)
+  proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
+  stdout_value, stderr_value = proc.communicate()
+
+  version = ""
+  for l in stdout_value.splitlines():
+    if l[0:4]=='MSMS':
+      version = l.split(' ')[1]
+      return version
+  if version=="":
+    LogWarning('Could not parse MSMS version string')
+    return
+
 ## \brief Method to check if MSMS executable is present
 #
 # \param msms_exe Explicit path to msms executable
@@ -69,7 +84,7 @@ def _SetupFiles(entity, selection):
   for a in entity_view.GetAtomList():
     position=a.GetPos()
     tmp_file_handle.write('%8.3f %8.3f %8.3f %4.2f\n' % (position[0],
-                          position[1], position[2], a.GetAtomProps().radius))
+                          position[1], position[2], a.radius))
   tmp_file_handle.close()
   
   return (tmp_dir_name, tmp_file_name)
@@ -120,7 +135,7 @@ def _RunMSMS(command):
   #check for successful completion of msms
   if proc.returncode!=0:
     print "WARNING: msms error\n", stdout_value
-    raise subprocess.MsmsProcessError(proc.returncode, command)
+    raise MsmsProcessError(proc.returncode, command)
 
   return stdout_value
   
@@ -182,7 +197,7 @@ def CalculateSurfaceArea(entity, density=1.0, radius=1.5,  all_surf=False,
   if all_surf:
     command+=" -all"
   if attach_asa != None:
-      command+=" -af %s" % os.path.join(msms_data_dir, "asa_atom")
+    command+=" -af %s" % os.path.join(msms_data_dir, "asa_atom")
   # run msms
   stdout_value=_RunMSMS(command)
   
diff --git a/modules/bindings/pymod/tmtools.py b/modules/bindings/pymod/tmtools.py
index 9405a31df86e42656ac449db07679968af097928..04db235931de9885850cc2c412cb8ed7038c6399 100644
--- a/modules/bindings/pymod/tmtools.py
+++ b/modules/bindings/pymod/tmtools.py
@@ -120,10 +120,12 @@ def _RunTmScore(tmscore, tmp_dir):
   model2_filename=os.path.join(tmp_dir, 'model02.pdb')  
   if platform.system() == "Windows":
     tmscore_path=settings.Locate('tmscore.exe', explicit_file_name=tmscore)
-    command="\"%s\" %s %s" %(os.path.normpath(tmscore_path), model1_filename, model2_filename)
+    command="\"%s\" %s %s" %(os.path.normpath(tmscore_path), model1_filename, 
+                             model2_filename)
   else:
     tmscore_path=settings.Locate('tmscore', explicit_file_name=tmscore)
-    command="\"%s\" \"%s\" \"%s\"" %(tmscore_path, model1_filename, model2_filename)
+    command="\"%s\" \"%s\" \"%s\"" % (tmscore_path, model1_filename, 
+                                      model2_filename)
   ps=subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
   ps.wait()
   lines=ps.stdout.readlines()
@@ -137,7 +139,7 @@ def TMAlign(model1, model2, tmalign=None):
   """
   tmp_dir_name=_SetupFiles((model1, model2))
   result=_RunTmAlign(tmalign, tmp_dir_name)
-  model1.handle.RequestXCSEditor().ApplyTransform(result.transform)
+  model1.handle.EditXCS().ApplyTransform(result.transform)
   _CleanupFiles(tmp_dir_name)
   return result
 def TMScore(model1, model2, tmscore=None):
@@ -146,6 +148,6 @@ def TMScore(model1, model2, tmscore=None):
   """
   tmp_dir_name=_SetupFiles((model1, model2))
   result=_RunTmScore(tmscore, tmp_dir_name)
-  model1.handle.RequestXCSEditor().ApplyTransform(result.transform)  
+  model1.handle.EditXCS().ApplyTransform(result.transform)  
   _CleanupFiles(tmp_dir_name)
   return result
diff --git a/modules/bindings/tests/CMakeLists.txt b/modules/bindings/tests/CMakeLists.txt
index 5a3f44e3d827f7571b5aaed58fde891abc8543bb..a93d8aeaa8b0a21c4bd0370fba5bf51a06988800 100644
--- a/modules/bindings/tests/CMakeLists.txt
+++ b/modules/bindings/tests/CMakeLists.txt
@@ -1,6 +1,7 @@
 set(OST_BINDINGS_UNIT_TESTS
   test_msms.py
   test_clustalw.py
+  test_blast.py
 )
 
 ost_unittest(bindings "${OST_BINDINGS_UNIT_TESTS}")
diff --git a/modules/bindings/tests/test_blast.py b/modules/bindings/tests/test_blast.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b42bfd18ec4a612a602e86834f52e383149ee65
--- /dev/null
+++ b/modules/bindings/tests/test_blast.py
@@ -0,0 +1,50 @@
+import unittest
+from ost import *
+from ost import settings
+from ost.bindings import blast
+
+class TestBlastBindings(unittest.TestCase):
+  def setUp(self):
+    self.query=seq.CreateSequence('A', 'MKPHPWFFGKIPRAKAEEMLSKQRHDGAFLIRESESAPG'+
+                                       'DFSLSVKFGNDVQHFKVLRDGAGKYFLWVVKFNSLNELV'+
+                                       'DYHRSTSVSRNQQIFLRDIEQVP')
+  def testAllowedMatricesAndPenalties(self):
+    self.assertRaises(blast.BlastError, blast.Blast, self.query, 
+                      'testfiles/seqdb', matrix='BLOSUM45')
+    blast.Blast(self.query, 'testfiles/seqdb', matrix='BLOSUM45', 
+                gap_open=13, gap_ext=3)
+    blast.Blast(self.query, 'testfiles/seqdb', matrix='BLOSUM80')
+    blast.Blast(self.query, 'testfiles/seqdb', matrix='PAM70')
+    blast.Blast(self.query, 'testfiles/seqdb', matrix='PAM30', gap_open=7,
+                gap_ext=2)
+    blast.Blast(self.query, 'testfiles/seqdb', matrix='BLOSUM62')
+    self.assertRaises(ValueError, blast.Blast, self.query, 'testfiles/seqdb', 
+                      matrix='MUAHA')
+  def testMissingDB(self):
+    self.assertRaises(IOError, blast.Blast, self.query, 
+                      'testfiles/nonexistentdb')
+  
+  def testParseBlastOutput(self):
+    hits=blast.Blast(self.query, 'testfiles/seqdb')
+    expected_output=[{'evalue':2.366130E-59,'bitscore':211.460,'score':537}, 
+                     {'evalue':4.808930E-59,'bitscore':210.305,'score':534}, 
+                     {'evalue':5.361450E-58,'bitscore':206.838,'score':525}, 
+                     {'evalue':3.277500E+00,'bitscore':15.0086,'score':27}, 
+                     {'evalue':9.696520E+00,'bitscore':13.4678,'score':23}]
+    self.assertEqual(len(hits), 4)
+    for expected, hit in zip(expected_output, hits):
+      patch=hit.aligned_patches[0]
+      self.assertAlmostEqual(patch.evalue, expected['evalue'])
+      self.assertAlmostEqual(patch.bit_score, expected['bitscore'])
+      self.assertAlmostEqual(patch.score, expected['score'])
+if __name__ == "__main__":
+  # test if blast package is available on system, otherwise ignore tests
+  try:
+    blastpath=settings.Locate('blastall')
+  except(settings.FileNotFound):
+    print "Could not find blastall executable: ignoring unit tests"
+    exit(0)
+  try:
+    unittest.main()
+  except Exception, e:
+    print e
\ No newline at end of file
diff --git a/modules/bindings/tests/test_clustalw.py b/modules/bindings/tests/test_clustalw.py
index fc93a19b6d4c270d46f1c79a3554077e8295f908..0536df8f77f868c27b93edbf92fd37a5f9a3d31d 100644
--- a/modules/bindings/tests/test_clustalw.py
+++ b/modules/bindings/tests/test_clustalw.py
@@ -13,13 +13,27 @@ class TestClustalWBindings(unittest.TestCase):
     self.templseq = io.LoadSequence("testfiles/similar.fasta")
     self.multseq = io.LoadSequenceList("testfiles/multiple.fasta")
     self.pw_alignment = io.LoadAlignment("testfiles/pairwise_aln.fasta")
+    self.nopgap_pw_alignment = io.LoadAlignment("testfiles/nopgap_pairwise_aln.fasta")
     self.mult_alignment = io.LoadAlignment("testfiles/multiple_aln.fasta")
-    
+
+    self.strseq1 = self.targetseq.GetGaplessString()
+    self.strseq2 = self.templseq.GetGaplessString()
+
+    self.seq1 = io.LoadSequence("testfiles/seq1.fasta")
+    self.seq2 = io.LoadSequence("testfiles/seq2.fasta")
+    self.seq1_seq2_alignment = io.LoadAlignment("testfiles/seq1_seq2_aln.fasta")
+    self.seq1_seq2_alignment_options_changed = io.LoadAlignment("testfiles/seq1_seq2_aln_options_changed.fasta")
+
   def testPairwiseClustalW(self):
     aln=clustalw.ClustalW(self.targetseq, self.templseq)
     assert self.pw_alignment.ToString(80) == aln.ToString(80), \
            "Pairwise alignment differs from precomputed one"
   
+  def testNoPGapPariwiseClustalW(self):
+    aln=clustalw.ClustalW(self.targetseq, self.templseq, nopgap=True)
+    assert self.nopgap_pw_alignment.ToString(80) == aln.ToString(80), \
+           "NoPGap pairwise alignment differs from precomputed one"
+
   def testAttachedViewClustalW(self):
     aln=clustalw.ClustalW(self.targetseq, self.templseq)
     assert aln.FindSequence("testseq").HasAttachedView(), \
@@ -30,6 +44,22 @@ class TestClustalWBindings(unittest.TestCase):
     assert self.mult_alignment.ToString(80) == aln.ToString(80), \
            "Multiple alignment differs from precomputed one"
 
+  def testStringClustalW(self):
+    aln=clustalw.ClustalW(self.strseq1, self.strseq2)
+    aln.SetSequenceName(0,self.targetseq.GetName())
+    aln.SetSequenceName(1,self.templseq.GetName())
+    assert self.pw_alignment.ToString(80) == aln.ToString(80), \
+           "Pairwise alignment using two strings differs from precomputed one \n%s \n%s" \
+           %(self.pw_alignment.ToString(80),aln.ToString(80))
+
+  def testPairwiseClustalWChangedOptions(self):
+    # five residues removed two positions before the end of seq2
+    aln=clustalw.ClustalW(self.seq1,self.seq2)
+    assert self.seq1_seq2_alignment.ToString(80) == aln.ToString(80), \
+           "Pairwise alignment with default gap penalties differs from precomputed one"
+    aln=clustalw.ClustalW(self.seq1,self.seq2,clustalw_option_string="-GAPOPEN=2 -GAPEXT=0")
+    assert self.seq1_seq2_alignment_options_changed.ToString(80) == aln.ToString(80), \
+           "Pairwise alignment with modified gap penalties differs from precomputed one"
 
 if __name__ == "__main__":
   # test if clustalw package is available on system, otherwise ignore tests
diff --git a/modules/bindings/tests/test_msms.py b/modules/bindings/tests/test_msms.py
index 61810be5576058d45cbe6b929052eb9522ca1531..054a63cffa472d01fbef5d5cd20289cd0a409fb6 100755
--- a/modules/bindings/tests/test_msms.py
+++ b/modules/bindings/tests/test_msms.py
@@ -7,31 +7,41 @@ class TestMSMSBindings(unittest.TestCase):
   
   def setUp(self):
     self.protein = io.LoadEntity("testfiles/testprotein.pdb")
-    self.num_tri=45360
-    self.num_vert=22670
-    self.ases=19336.730
-    self.asas=21179.932
+
+    self.num_tri=111546
+    self.num_vert=55762
+    self.ases=20051.928
+    self.asas=21574.324
 
   def testCalculateSurface(self):
-    surf=msms.CalculateSurface(self.protein, msms_env='MSMSSERVER')[0]
+    surf=msms.CalculateSurface(self.protein,
+                               msms_env='MSMSSERVER',
+                               density=3,
+                               radius=1.4)[0]
     assert self.num_vert==len(surf.GetVertexIDList()) \
        and self.num_tri==len(surf.GetTriIDList()), \
        "Number of surface vertices (%i) or triangles (%i) do not match precalculated values (%i/%i)"%(len(surf.GetVertexIDList()),len(surf.GetTriIDList()),self.num_vert,self.num_tri)
   
   def testCalculateSurfaceAres(self):
      (msms_ases, msms_asas)=msms.CalculateSurfaceArea(self.protein, \
-                                                      msms_env='MSMSSERVER')
+                                                      msms_env='MSMSSERVER',
+                                                      density=3,
+                                                      radius=1.4)
      assert self.ases==msms_ases[0] and self.asas==msms_asas[0], \
      "SASA (%f) or SESA (%f) do not match precalculated values (%f/%f)"%(msms_asas[0],msms_ases[0],self.asas,self.ases)
 
 
 if __name__ == "__main__":
   # test if msms package is available on system, otherwise ignore tests
+  VERSION_REQUIRED = '2.6.1'
   try:
     msms._GetExecutable(msms_exe=None, msms_env='MSMSSERVER')
   except(settings.FileNotFound):
     print "Could not find msms executable: ignoring unit tests"
     exit(0)
+  version = msms.GetVersion(msms_exe=None, msms_env='MSMSSERVER')
+  if version!=VERSION_REQUIRED:
+    print "MSMS version (%s) does not match required version %s: ignoring unit tests"%(version, VERSION_REQUIRED)
   try:
     unittest.main()
   except Exception, e:
diff --git a/modules/bindings/tests/testfiles/nopgap_pairwise_aln.fasta b/modules/bindings/tests/testfiles/nopgap_pairwise_aln.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..4ec3472614489c3a34e353fdb33f986a094d4654
--- /dev/null
+++ b/modules/bindings/tests/testfiles/nopgap_pairwise_aln.fasta
@@ -0,0 +1,4 @@
+>testseq
+------MRLDGKTALITGSARGIGRAFAEAYVREGARVAIADIN---LEAARATAAEIGPAACAIALDVTDQASIDRCVAELLDRWGSIDILVNNAALFDLAPIVEITRESYDRLFAINVSGTLFMMQAVARAMIAGGRGGKIINMASQAGRRGEALVGVYCATKAAVISLTQSAGLNLIRHGINVNAIAPGVVDGEHWDGVDAKFADYENLPRGEKKRQVGAAVPFGRMGRAEDLTGMAIFLATPEADYIVAQTYNVDGGNWMS-
+>P50199.1
+MSHPDLFSLSGARALVTGASRGIGLTLAKGLARYGAEVVLNGRNAESLDSAQSGFEAEGLKASTAVFDVTDQDAVIDGVAAIERDMGPIDILINNAGIQRRAPLEEFSRKDWDDLMSTNVNAVFFVGQAVARHMIPRGRG-KIVNICSVQSELARPGIAPYTATKGAVKNLTKGMATDWGRHGLQINGLAPGYFATE----MTERLVADEEFTDWLCKR-----TPAGRWGQVEELVGAAVFLSSRASSFVNGQVLMVDGGITVSL
diff --git a/modules/bindings/tests/testfiles/seq1.fasta b/modules/bindings/tests/testfiles/seq1.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..7aa326305015b25f0416e416fe14afe19984e29a
--- /dev/null
+++ b/modules/bindings/tests/testfiles/seq1.fasta
@@ -0,0 +1,2 @@
+>target
+MAETLIKVDLNQSPYDNPQVHNRWHPDIPMAVWVEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWVHMKVSLIKGGMAKYGIKNPIFKPSPMTPNYKDYLIFEGISVDEKGKQHYLDVTVAYRQACLNAIEYLKKFGYSGAQAYSLLGTAPVQGHISGVVDVPNACATLWLPTEIFDFDINPTAEGPQKIITGGVDLPIAQDK
\ No newline at end of file
diff --git a/modules/bindings/tests/testfiles/seq1_seq2_aln.fasta b/modules/bindings/tests/testfiles/seq1_seq2_aln.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..e735762a95916b563ad735f89eaa3c22376fd505
--- /dev/null
+++ b/modules/bindings/tests/testfiles/seq1_seq2_aln.fasta
@@ -0,0 +1,4 @@
+>target
+MAETLIKVDLNQSPYDNPQVHNRWHPDIPMAVWVEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWVHMKVSLIKGGMAKYGIKNPIFKPSPMTPNYKDYLIFEGISVDEKGKQHYLDVTVAYRQACLNAIEYLKKFGYSGAQAYSLLGTAPVQGHISGVVDVPNACATLWLPTEIFDFDINPTAEGPQKIITGGVDLPIAQDK
+>model
+---------------------------------VEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWVIK---------------------------------------------------------------------------------------------------------------------------------------
\ No newline at end of file
diff --git a/modules/bindings/tests/testfiles/seq1_seq2_aln_options_changed.fasta b/modules/bindings/tests/testfiles/seq1_seq2_aln_options_changed.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..3efdc6cd889b07a900a1f63e6d5e8f1d13552af9
--- /dev/null
+++ b/modules/bindings/tests/testfiles/seq1_seq2_aln_options_changed.fasta
@@ -0,0 +1,4 @@
+>target
+MAETLIKVDLNQSPYDNPQVHNRWHPDIPMAVWVEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWVHMKVSLIKGGMAKYGIKNPIFKPSPMTPNYKDYLIFEGISVDEKGKQHYLDVTVAYRQACLNAIEYLKKFGYSGAQAYSLLGTAPVQGHISGVVDVPNACATLWLPTEIFDFDINPTAEGPQKIITGGVDLPIAQDK
+>model
+---------------------------------VEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWV------IK---------------------------------------------------------------------------------------------------------------------------------
\ No newline at end of file
diff --git a/modules/bindings/tests/testfiles/seq2.fasta b/modules/bindings/tests/testfiles/seq2.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..72a58bd2acab10c6be354a59e75b28eea045a906
--- /dev/null
+++ b/modules/bindings/tests/testfiles/seq2.fasta
@@ -0,0 +1,2 @@
+>model
+VEPGAEFKLETYDWTGGAIKNDDSAEDVRDVDLSTVHFLSGPVGVKGAEPGDLLVVDLLDIGARDDSLWGFNGFFSKQNGGGFLDEHFPLAQKSIWDFHGMFTKSRHIPGVNFAGLIHPGLIGCLPDPKMLASWNERETGLIATDPDRIPGLANPPNATTAHMGQMQGEARDKAAAEGARTVPPREHGGNCDIKDLSRGSRVFFPVYVDGAGLSVGDLHFSQGDGEITFCGAIEMAGWVIK
\ No newline at end of file
diff --git a/modules/bindings/tests/testfiles/seqdb.fasta b/modules/bindings/tests/testfiles/seqdb.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..5e665b80f9857d04dc2440182bd226931dcc13c3
--- /dev/null
+++ b/modules/bindings/tests/testfiles/seqdb.fasta
@@ -0,0 +1,41 @@
+>1fhsA
+GIEMKPHPWFFGKIPRAKAEEMLSKQRHDGAFLIRESESAPGDFSLSVKF
+GNDVQHFKVLRDGAGKYFLWVVKFNSLNELVDYHRSTSVSRNQQIFLRDI
+EQVPQQPTYVQA
+>1griA
+MEAIAKYDFKATADDELSFKRGDILKVQNWYKAELNGKDGFIPKNYIEMK
+PHPWFFGKIPRAKAEEMLSKQRHDGAFLIRESESAPGDFSLSVKFGNDVQ
+HFKVLRDGAGKYFLWVVKFNSLNELVDYHRSTSVSRNQQIFLRDIEQVPQ
+QPTYVQALFDFDPQEDGELGFRRGDFIHVMDNSDPNWWKGACHGQTGMFP
+RNYVTPVNRNV
+>3n84E
+MIEMKPHPWFFGKIPRAKAEEMLSKQRHDGAFLIRESESAPGDFSLSVKF
+GNDVQHFKVLRDGAGKYFLWVVKFNSLNELVDYHRSTSVSRNQQIFLRDI
+EQ
+>3dwgB
+RHMTRYDSLLQALGNTPLVGLQRLSPRWDDGRDGPHVRLWAKLEDRNPTG
+SIKDRPAVRMIEQAEADGLLRPGATILEPTSGNTGISLAMAARLKGYRLI
+CVMPENTSVERRQLLELYGAQIIFSAANTAVATAKELAATNPSWVMLYQY
+GNPANTDSHYCGTGPELLADLPEITHFVAGLGTTGTLMGTGRFLREHVAN
+VKIVAAEPRYGEGVYALRNMDEGFVPELYDPEILTARYSVGAVDAVRRTR
+ELVHTEGIFAGISTGAVLHAALGVGAGALAAGERADIALVVADAGWKYLS
+TGAYAGSLDDAETALEGQLWA
+>3hkfA
+SSVFIFPPKPKDVLTITLTPKVTCVVVDISKDDPEVQFSWFVDDVEVHTA
+QTQPREEQFNSTFRSVSELPIMHQDWLNGKEFKCRVNSAAFPAPIEKTIS
+KTKGRPKAPQVYTIPPPKEQMAKDKVSLTCMITDFFPEDITVEWQWNGQP
+AENYKNTQPIMDTDGSYFVYSKLNVQKSNWEAGNTFTCSVLHEGLHNHHT
+EKSLS
+>1mw9X
+GKALVIVESPAKAKTINKYLGSDYVVKSSVGHIRDLPTERGALVNRMGVD
+PWHNWEAHYEVLPGKEKVVSELKQLAEKADHIYLATDLDREGEAIAWHLR
+EVIGGDDARYSRVVFNEITKNAIRQAFNKPGELNIDRVNAQQARRFMDRV
+VGYMVSPLLWKKIARGLSAGRVQSVAVRLVVEREREIKAFVPEEFWEVDA
+STTTPSGEALALQVTHQNDKPFRPVNKEQTQAAVSLLEKARYSVLEREDK
+PTTSKPGAPFITSTLQQAASTRLGFGVKKTMMMAQRLYEAGYITYMRTDS
+TNLSQDAVNMVRGYISDNFGKKYLPESPNQYAREAIRPSDVNVMAESLKD
+MEADAQKLYQLIWRQFVACQMTPAKYDSTTLTVGAGDFRLKARGRILRFD
+GWTKVMPALEDRILPAVNKGDALTLVELTPAQHFTKPPARFSEASLVKEL
+EKRGIGRPSTYASIISTIQDRGYVRVENRRFYAEKMGEIVTDRLEENFRE
+LMNYDFTAQMENNLDQVANHEAEWKAVLDHFFSDFTQQLDKAEKDPEEGG
+MRPNQM
\ No newline at end of file
diff --git a/modules/bindings/tests/testfiles/seqdb.phr b/modules/bindings/tests/testfiles/seqdb.phr
new file mode 100644
index 0000000000000000000000000000000000000000..b4cfd67e27cc18f5e7b199476a4083e6f4ff8a56
Binary files /dev/null and b/modules/bindings/tests/testfiles/seqdb.phr differ
diff --git a/modules/bindings/tests/testfiles/seqdb.pin b/modules/bindings/tests/testfiles/seqdb.pin
new file mode 100644
index 0000000000000000000000000000000000000000..1f6f5be753acd11950e085c4971e9fe0ea7d78e2
Binary files /dev/null and b/modules/bindings/tests/testfiles/seqdb.pin differ
diff --git a/modules/bindings/tests/testfiles/seqdb.psq b/modules/bindings/tests/testfiles/seqdb.psq
new file mode 100644
index 0000000000000000000000000000000000000000..b55326094e5594efaa5f3a695ece541dd46669ee
Binary files /dev/null and b/modules/bindings/tests/testfiles/seqdb.psq differ
diff --git a/modules/config/version.hh b/modules/config/version.hh
index ee0bde0544b477904c9c52953a16a64f9d95e811..683356005409e658914c5edda2a256b9e4fa0157 100644
--- a/modules/config/version.hh
+++ b/modules/config/version.hh
@@ -20,8 +20,8 @@
 #define OST_VERSION_HH_
 
 #define OST_VERSION_MAJOR 1
-#define OST_VERSION_MINOR 0
+#define OST_VERSION_MINOR 1
 #define OST_VERSION_PATCH 0
-#define OST_VERSION_STRING "1.0.0"
+#define OST_VERSION_STRING "1.1.0"
 
 #endif /* OST_VERSION_HH_ */
diff --git a/modules/conop/doc/conop.rst b/modules/conop/doc/conop.rst
index 6e8443558c8345033692c55e3d84c302d200b93d..8eed48919c547cadf4465a44d0d0388176c1e532 100644
--- a/modules/conop/doc/conop.rst
+++ b/modules/conop/doc/conop.rst
@@ -169,6 +169,14 @@ files to use the rule-based builder.
      :param residue: must be a valid residue
      :type  residue: mol.ResidueHandle
      
+  .. method:: GuessChemClass(residue)
+
+    Guesses the chemical class of the residue based on its atom and
+    connectivity.
+
+    So far, the method only guesses whether the residue is a peptide. A residue
+    is a peptide if all the backbone atoms N,CA,C,O are present, have the right
+    element and are in a suitable orientation to form bonds.
 
 .. class:: RuleBasedBuilder
    
diff --git a/modules/conop/pymod/export_conop.cc b/modules/conop/pymod/export_conop.cc
index 8b2509ec3a70a9fd8620919496a58ffa8f0cead5..64d12ffd224f8add296c035390c21803616f5d9b 100644
--- a/modules/conop/pymod/export_conop.cc
+++ b/modules/conop/pymod/export_conop.cc
@@ -31,7 +31,6 @@ void export_Conop() {
      .def("Instance", &Conopology::Instance, return_value_policy<reference_existing_object>()).staticmethod("Instance")
     .def("ConnectAll", &Conopology::ConnectAll)
     .def("GetBuilder", &Conopology::GetBuilder)
-    .def("GetDefaultAtomRadius", &Conopology::GetDefaultAtomRadius)
     .def("ConnectAll", &Conopology::ConnectAll)
     .def("RegisterBuilder", &Conopology::RegisterBuilder)
     .def("SetDefaultBuilder", &Conopology::SetDefaultBuilder)
diff --git a/modules/conop/src/CMakeLists.txt b/modules/conop/src/CMakeLists.txt
index 4d0840ea34d18bbe4f983c24f17d8ad8603769fd..e69c45689648a82ad4d086eb9e1657fa639d1131 100644
--- a/modules/conop/src/CMakeLists.txt
+++ b/modules/conop/src/CMakeLists.txt
@@ -23,7 +23,7 @@ ring_finder.cc
 module(NAME conop SOURCES ${OST_CONOP_SOURCES}
        HEADERS ${OST_CONOP_HEADERS} DEPENDS_ON mol geom db)
 
-executable(NAME chemdict_tool SOURCES chemdict_tool.cc DEPENDS_ON io)
+executable(NAME chemdict_tool SOURCES chemdict_tool.cc DEPENDS_ON io STATIC)
 
 if (COMPOUND_LIB)
   if (EXISTS "${COMPOUND_LIB}")
diff --git a/modules/conop/src/builder.cc b/modules/conop/src/builder.cc
index 9fce604d833a0d25508c231360a95642a48e5152..b50048c5e707c8d82d2743e1e7a109e440fa311d 100644
--- a/modules/conop/src/builder.cc
+++ b/modules/conop/src/builder.cc
@@ -163,12 +163,31 @@ bool Builder::AreResiduesConsecutive(const mol::ResidueHandle& r1,
          r2.GetNumber().GetInsCode()==r1.GetNumber().NextInsertionCode().GetInsCode();
 }
 
+void Builder::GuessChemClass(mol::ResidueHandle res)
+{
+  // try peptide
+  res.SetChemClass(mol::ChemClass());
+  mol::AtomHandle ca=res.FindAtom("CA");
+  if (!ca.IsValid() || ca.GetElement()!="C") return;
+  mol::AtomHandle n=res.FindAtom("N");
+  if (!n.IsValid() || n.GetElement()!="N") return;
+  mol::AtomHandle c=res.FindAtom("C");
+  if (!c.IsValid() || c.GetElement()!="C") return;
+  mol::AtomHandle o=res.FindAtom("O");
+  if (!o.IsValid() || o.GetElement()!="O") return;
+  if (this->IsBondFeasible(n, ca) && this->IsBondFeasible(ca, c) &&
+      this->IsBondFeasible(c, o)) {
+    res.SetChemClass(mol::ChemClass(mol::ChemClass::PeptideLinking));
+  }
+}
+
+
 void Builder::AssignBackBoneTorsionsToResidue(mol::ResidueHandle res)
 {
 
   mol::ResidueHandle prev=res.GetPrev();
   mol::ResidueHandle next=res.GetNext();
-  mol::XCSEditor e=res.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor e=res.GetEntity().EditXCS(mol::BUFFERED_EDIT);
   //psi
   if (next.IsValid() && next.IsPeptideLinking()){
     mol::AtomHandle ca_this=res.FindAtom("CA");
@@ -209,7 +228,7 @@ void Builder::AssignBackBoneTorsionsToResidue(mol::ResidueHandle res)
 void Builder::DistanceBasedConnect(mol::AtomHandle atom)
 {
   mol::EntityHandle ent=atom.GetEntity();
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   mol::AtomHandleList alist = ent.FindWithin(atom.GetPos(),4.0);
   mol::ResidueHandle res_a=atom.GetResidue();
   for (mol::AtomHandleList::const_iterator it=alist.begin(),
diff --git a/modules/conop/src/builder.hh b/modules/conop/src/builder.hh
index 5312d80e9e455293b16d6568a8d66971934b8718..3946780d1b1986c4030e3d5563e8bc0d485a9a22 100644
--- a/modules/conop/src/builder.hh
+++ b/modules/conop/src/builder.hh
@@ -137,7 +137,9 @@ public:
   /// \brief whether the r1 and r2 have consecutive residue numbers
   static bool AreResiduesConsecutive(const mol::ResidueHandle& r1, 
                                      const mol::ResidueHandle& r2);
-
+  /// \brief guess and assign chemical class of residue based on atoms and
+  ///     connectivity
+  void GuessChemClass(mol::ResidueHandle res);
   /// |brief Connect \p atom with all atoms for whith IsBondFeasible() and 
   ///    AreResiduesConsecutive() returns true
   void DistanceBasedConnect(mol::AtomHandle atom);
diff --git a/modules/conop/src/conop.cc b/modules/conop/src/conop.cc
index d7edd9aa8ef5b451128a45b742d1b74ffb45b954..b1448aa8ff32522b4e9a2c4444eb7e4711e17b77 100644
--- a/modules/conop/src/conop.cc
+++ b/modules/conop/src/conop.cc
@@ -33,165 +33,129 @@ Conopology& Conopology::Instance()
 }
 
 Conopology::Conopology():
-  builder_map_(),
-  ele_rad_map_(),
-  ele_mass_map_()
+  builder_map_()
 {
   builder_map_["HEURISTIC"]=BuilderP(new HeuristicBuilder());
   builder_map_["DEFAULT"]=builder_map_["HEURISTIC"];
-
-  ele_rad_map_["H"]  = 1.09;
-                 
-  ele_rad_map_["C"]  = 1.70;  //was 1.75
-  ele_rad_map_["N"]  = 1.55;
-  ele_rad_map_["O"]  = 1.52;
-  ele_rad_map_["F"]  = 1.47;
-                 
-  ele_rad_map_["NA"] = 2.27;
-  ele_rad_map_["MG"] = 1.73;
-  ele_rad_map_["SI"] = 2.10;
-  ele_rad_map_["P"]  = 1.80;
-  ele_rad_map_["S"]  = 1.80;
-  ele_rad_map_["CL"] = 1.75;
-                 
-  ele_rad_map_["K"]  = 2.75;
-  ele_rad_map_["CA"] = 2.00;
-  ele_rad_map_["MN"] = 2.00;
-  ele_rad_map_["FE"] = 2.00;
-  ele_rad_map_["CO"] = 2.00;
-  ele_rad_map_["NI"] = 1.63;
-  ele_rad_map_["CU"] = 1.40;
-  ele_rad_map_["ZN"] = 1.39;
-  ele_rad_map_["BR"] = 1.85;
-
-  ele_rad_map_["I"]  = 1.98;
-
-
-  // Element masses according to IUPAC standards
-  // see http://www.chem.qmul.ac.uk/iupac/AtWt/
-  ele_mass_map_["H"]  = 1.00794;
-  ele_mass_map_["HE"] = 4.002602;
-  ele_mass_map_["LI"] = 6.941;
-  ele_mass_map_["BE"] = 9.012182;
-  ele_mass_map_["B"]  = 10.811;
-  ele_mass_map_["C"]  = 12.0107;
-  ele_mass_map_["N"]  = 14.0067;
-  ele_mass_map_["O"]  = 15.9994;
-  ele_mass_map_["F"]  = 18.9984032;
-  ele_mass_map_["NE"] = 20.1797;
-  ele_mass_map_["NA"] = 22.98976928;
-  ele_mass_map_["MG"] = 24.3050;
-  ele_mass_map_["AL"] = 26.9815386;
-  ele_mass_map_["SI"] = 28.0855;
-  ele_mass_map_["P"]  = 30.973762;
-  ele_mass_map_["S"]  = 32.065;
-  ele_mass_map_["CL"] = 35.453;
-  ele_mass_map_["AR"] = 39.948;
-  ele_mass_map_["K"]  = 39.0983;
-  ele_mass_map_["CA"] = 40.078;
-  ele_mass_map_["SC"] = 44.955912;
-  ele_mass_map_["TI"] = 47.867;
-  ele_mass_map_["V"]  = 50.9415;
-  ele_mass_map_["CR"] = 51.9961;
-  ele_mass_map_["MN"] = 54.938045;
-  ele_mass_map_["FE"] = 55.845;
-  ele_mass_map_["CO"] = 58.933195;
-  ele_mass_map_["NI"] = 58.6934;
-  ele_mass_map_["CU"] = 63.546;
-  ele_mass_map_["ZN"] = 65.38;
-  ele_mass_map_["GA"] = 69.723;
-  ele_mass_map_["GE"] = 72.64;
-  ele_mass_map_["AS"] = 74.92160;
-  ele_mass_map_["SE"] = 78.96;
-  ele_mass_map_["BR"] = 79.904;
-  ele_mass_map_["KR"] = 83.798;
-  ele_mass_map_["RB"] = 85.4678;
-  ele_mass_map_["SR"] = 87.62;
-  ele_mass_map_["Y"]  = 88.90585;
-  ele_mass_map_["ZR"] = 91.224;
-  ele_mass_map_["NB"] = 92.90638;
-  ele_mass_map_["MO"] = 95.96;
-  ele_mass_map_["TC"] = 98.0;
-  ele_mass_map_["RU"] = 101.07;
-  ele_mass_map_["RH"] = 102.90550;
-  ele_mass_map_["PD"] = 106.42;
-  ele_mass_map_["AG"] = 107.8682;
-  ele_mass_map_["CD"] = 112.411;
-  ele_mass_map_["IN"] = 114.818;
-  ele_mass_map_["SN"] = 118.710;
-  ele_mass_map_["SB"] = 121.760;
-  ele_mass_map_["TE"] = 127.60;
-  ele_mass_map_["I"]  = 126.90447;
-  ele_mass_map_["XE"] = 131.293;
-  ele_mass_map_["CS"] = 132.9054519;
-  ele_mass_map_["BA"] = 137.327;
-  ele_mass_map_["LA"] = 138.90547;
-  ele_mass_map_["CE"] = 140.116;
-  ele_mass_map_["PR"] = 140.90765;
-  ele_mass_map_["ND"] = 144.242;
-  ele_mass_map_["PM"] = 145.0;
-  ele_mass_map_["SM"] = 150.36;
-  ele_mass_map_["EU"] = 151.964;
-  ele_mass_map_["GD"] = 157.25;
-  ele_mass_map_["TB"] = 158.92535;
-  ele_mass_map_["DY"] = 162.500;
-  ele_mass_map_["HO"] = 164.93032;
-  ele_mass_map_["ER"] = 167.259;
-  ele_mass_map_["TM"] = 168.93421;
-  ele_mass_map_["YB"] = 173.054;
-  ele_mass_map_["LU"] = 174.9668;
-  ele_mass_map_["HF"] = 178.49;
-  ele_mass_map_["TA"] = 180.94788;
-  ele_mass_map_["W"]  = 183.84;
-  ele_mass_map_["RE"] = 186.207;
-  ele_mass_map_["OS"] = 190.23;
-  ele_mass_map_["IR"] = 192.217;
-  ele_mass_map_["PT"] = 195.084;
-  ele_mass_map_["AU"] = 196.966569;
-  ele_mass_map_["HG"] = 200.59;
-  ele_mass_map_["TL"] = 204.3833;
-  ele_mass_map_["PB"] = 207.2;
-  ele_mass_map_["BI"] = 208.98040;
-  ele_mass_map_["PO"] = 209.0;
-  ele_mass_map_["AT"] = 210.0;
-  ele_mass_map_["RN"] = 222.0;
-  ele_mass_map_["FR"] = 223.0;
-  ele_mass_map_["RA"] = 226.0;
-  ele_mass_map_["AC"] = 227.0;
-  ele_mass_map_["TH"] = 232.03806;
-  ele_mass_map_["PA"] = 231.03588;
-  ele_mass_map_["U"]  = 238.02891;
-  ele_mass_map_["NP"] = 237.0;
-  ele_mass_map_["PU"] = 244.0;
-  ele_mass_map_["AM"] = 243.0;
-  ele_mass_map_["CM"] = 247.0;
-  ele_mass_map_["BK"] = 247.0;
-  ele_mass_map_["CF"] = 251.0;
-  ele_mass_map_["ES"] = 252.0;
-  ele_mass_map_["FM"] = 257.0;
-  ele_mass_map_["MD"] = 258.0;
-  ele_mass_map_["NO"] = 259.0;
-  ele_mass_map_["LR"] = 262.0;
-  ele_mass_map_["RF"] = 267.0;
-  ele_mass_map_["DB"] = 268.0;
-  ele_mass_map_["SG"] = 271.0;
-  ele_mass_map_["BH"] = 272.0;
-  ele_mass_map_["HS"] = 270.0;
-  ele_mass_map_["MT"] = 276.0;
-  ele_mass_map_["DS"] = 281.0;
-  ele_mass_map_["RG"] = 280.0;
-  ele_mass_map_["CN"] = 285.0;
-  ele_mass_map_["UUT"]= 284.0;
-  ele_mass_map_["UUQ"]= 289.0;
-  ele_mass_map_["UUP"]= 288.0;
-  ele_mass_map_["UUH"]= 293.0;
-  ele_mass_map_["UUO"]= 294.0;  
+  
+  known_elements_.insert("AC");
+  known_elements_.insert("AG");
+  known_elements_.insert("AL");
+  known_elements_.insert("AM");
+  known_elements_.insert("AR");
+  known_elements_.insert("AS");
+  known_elements_.insert("AT");
+  known_elements_.insert("AU");
+  known_elements_.insert("B");
+  known_elements_.insert("BA");
+  known_elements_.insert("BE");
+  known_elements_.insert("BH");
+  known_elements_.insert("BI");
+  known_elements_.insert("BK");
+  known_elements_.insert("BR");
+  known_elements_.insert("C");
+  known_elements_.insert("CA");
+  known_elements_.insert("D");
+  known_elements_.insert("CD");
+  known_elements_.insert("CE");
+  known_elements_.insert("CF");
+  known_elements_.insert("CL");
+  known_elements_.insert("CM");
+  known_elements_.insert("CO");
+  known_elements_.insert("CR");
+  known_elements_.insert("CS");
+  known_elements_.insert("CU");
+  known_elements_.insert("DB");
+  known_elements_.insert("DS");
+  known_elements_.insert("DY");
+  known_elements_.insert("ER");
+  known_elements_.insert("ES");
+  known_elements_.insert("EU");
+  known_elements_.insert("F");
+  known_elements_.insert("FE");
+  known_elements_.insert("FM");
+  known_elements_.insert("FR");
+  known_elements_.insert("GA");
+  known_elements_.insert("GD");
+  known_elements_.insert("GE");
+  known_elements_.insert("H");
+  known_elements_.insert("HE");
+  known_elements_.insert("HF");
+  known_elements_.insert("HG");
+  known_elements_.insert("HO");
+  known_elements_.insert("HS");
+  known_elements_.insert("I");
+  known_elements_.insert("IN");
+  known_elements_.insert("IR");
+  known_elements_.insert("K");
+  known_elements_.insert("KR");
+  known_elements_.insert("LA");
+  known_elements_.insert("LI");
+  known_elements_.insert("LR");
+  known_elements_.insert("LU");
+  known_elements_.insert("MD");
+  known_elements_.insert("MG");
+  known_elements_.insert("MN");
+  known_elements_.insert("MO");
+  known_elements_.insert("MT");
+  known_elements_.insert("N");
+  known_elements_.insert("NA");
+  known_elements_.insert("NB");
+  known_elements_.insert("ND");
+  known_elements_.insert("NE");
+  known_elements_.insert("NI");
+  known_elements_.insert("NO");
+  known_elements_.insert("NP");
+  known_elements_.insert("O");
+  known_elements_.insert("OS");
+  known_elements_.insert("P");
+  known_elements_.insert("PA");
+  known_elements_.insert("PB");
+  known_elements_.insert("PD");
+  known_elements_.insert("PM");
+  known_elements_.insert("PO");
+  known_elements_.insert("PR");
+  known_elements_.insert("PT");
+  known_elements_.insert("PU");
+  known_elements_.insert("RA");
+  known_elements_.insert("RB");
+  known_elements_.insert("RE");
+  known_elements_.insert("RF");
+  known_elements_.insert("RH");
+  known_elements_.insert("RN");
+  known_elements_.insert("RU");
+  known_elements_.insert("S");
+  known_elements_.insert("SB");
+  known_elements_.insert("SC");
+  known_elements_.insert("SE");
+  known_elements_.insert("SG");
+  known_elements_.insert("SI");
+  known_elements_.insert("SM");
+  known_elements_.insert("SN");
+  known_elements_.insert("SR");
+  known_elements_.insert("TA");
+  known_elements_.insert("TB");
+  known_elements_.insert("TC");
+  known_elements_.insert("TE");
+  known_elements_.insert("TH");
+  known_elements_.insert("TI");
+  known_elements_.insert("TL");
+  known_elements_.insert("TM");
+  known_elements_.insert("U");
+  known_elements_.insert("V");
+  known_elements_.insert("W");
+  known_elements_.insert("XE");
+  known_elements_.insert("Y");
+  known_elements_.insert("YB");
+  known_elements_.insert("ZN");
+  known_elements_.insert("ZR");
 }
 
 void Conopology::RegisterBuilder(const BuilderP& b, const String& name) {
   if (!GetBuilder(name))
   builder_map_[name]=b;
 }
+
 void Conopology::SetDefaultBuilder(const String& default_name) {
   BuilderP builder=GetBuilder(default_name);
   if (builder)
@@ -218,7 +182,7 @@ public:
   virtual bool VisitResidue(const mol::ResidueHandle& res)
   {
     String key=builder_->IdentifyResidue(res);
-    if (key=="UNK") {
+    if (key=="UNK" && res.GetKey()!="UNK" && res.GetKey()!="UNL") {
       unk_res_[res.GetKey()]+=1;
     }
     builder_->FillResidueProps(res);
@@ -249,13 +213,26 @@ private:
   std::map<String, int>  unk_res_;  
 };
 
-
+class ChemClassAssigner : public mol::EntityVisitor {
+public:
+  ChemClassAssigner(BuilderP b): builder(b) { }
+  virtual bool VisitResidue(const mol::ResidueHandle& res)
+  {
+    if (res.GetChemClass()==mol::ChemClass()) {
+      builder->GuessChemClass(res);
+    }
+    return false;
+  }
+private:
+  BuilderP builder;
+};
 class Connector: public mol::EntityVisitor
 {
 public:
-  Connector(const BuilderP& b):
+  Connector(const BuilderP& b, bool peptide_bonds):
     builder_(b),
-    prev_()
+    prev_(),
+    peptide_bonds_(peptide_bonds)
   {}
 
   virtual bool VisitChain(const mol::ChainHandle& chain) {
@@ -265,7 +242,7 @@ public:
 
   virtual bool VisitResidue(const mol::ResidueHandle& res) {
     builder_->ConnectAtomsOfResidue(res);
-    if (prev_) {
+    if (peptide_bonds_ && prev_) {
       builder_->ConnectResidueToPrev(res,prev_);
     }
     prev_=res;
@@ -275,6 +252,7 @@ public:
 private:
   BuilderP builder_;
   mol::ResidueHandle prev_;
+  bool peptide_bonds_;
 };
 
 class TorsionMaker: public mol::EntityVisitor
@@ -294,15 +272,17 @@ private:
 };
 } // ns
 
-void Conopology::ConnectAll(const BuilderP& b, mol::EntityHandle eh, int flag)
+void Conopology::ConnectAll(const BuilderP& b, mol::EntityHandle eh, int flags)
 {
   Profile profile_connect("ConnectAll");
   LOG_DEBUG("Conopology: ConnectAll: building internal coordinate system");
-  mol::XCSEditor xcs_e=eh.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor xcs_e=eh.EditXCS(mol::BUFFERED_EDIT);
   PropAssigner a(b);
   eh.Apply(a);
+  ChemClassAssigner cca(b);
+  eh.Apply(cca);
   LOG_DEBUG("Conopology: ConnectAll: connecting all bonds");
-  Connector connector(b);
+  Connector connector(b, !(flags & NO_PEPTIDE_BONDS));
   eh.Apply(connector);
 
   LOG_DEBUG("Conopology: ConnectAll: assigning all torsions");
@@ -310,31 +290,11 @@ void Conopology::ConnectAll(const BuilderP& b, mol::EntityHandle eh, int flag)
   eh.Apply(tmaker);
 }
 
-Real Conopology::GetDefaultAtomRadius(const String& element) const
-{
-  String upper_ele=element;
-  std::transform(upper_ele.begin(),upper_ele.end(),upper_ele.begin(),toupper);  
-  std::map<String,Real>::const_iterator it = ele_rad_map_.find(upper_ele);
-  return it==ele_rad_map_.end() ? 1.5 : it->second;
-}
-
-bool Conopology::IsValidElement(const String& element) const
+bool Conopology::IsValidElement(const String& ele) const
 {
-  String upper_ele=element;
-  std::transform(upper_ele.begin(),upper_ele.end(),upper_ele.begin(),toupper);  
-  
-  std::map<String,Real>::const_iterator it = ele_mass_map_.find(upper_ele);
-  return it!=ele_mass_map_.end();
-}
-
-Real Conopology::GetDefaultAtomMass(const String& element) const
-{
-  String upper_ele=element;
-  std::transform(upper_ele.begin(),upper_ele.end(),upper_ele.begin(),toupper);  
-  
-  std::map<String,Real>::const_iterator it = ele_mass_map_.find(upper_ele);
-  return it==ele_mass_map_.end() ? 1.0 : it->second;
+  String upper_ele=ele;
+  std::transform(upper_ele.begin(),upper_ele.end(),upper_ele.begin(),toupper);
+  return known_elements_.find(upper_ele)!=known_elements_.end();
 }
 
-
 }} // ns
diff --git a/modules/conop/src/conop.hh b/modules/conop/src/conop.hh
index e8ad4bc0b7034942a446a0726c3cb2949ba76d36..0d9fccf7b9c2d9db2c3e7b4f559ebdfe304fc44b 100644
--- a/modules/conop/src/conop.hh
+++ b/modules/conop/src/conop.hh
@@ -26,6 +26,12 @@
 
 namespace ost { namespace conop {
 
+
+typedef enum {
+  NO_PEPTIDE_BONDS=1,
+} ConopFlag;
+
+  
 class DLLEXPORT_OST_CONOP Conopology {
   typedef std::map<String,BuilderP> BuilderMap;
 
@@ -36,20 +42,14 @@ public:
   // retrieve a builder by name
   BuilderP GetBuilder(const String& name="DEFAULT");
 
-  // return default vdW radius
-  // temporary location until more elaborate chemical information is impl
-  Real GetDefaultAtomRadius(const String& element) const;
-
-  // return default mass
-  Real GetDefaultAtomMass(const String& element) const;
-
   /*
     convenience function, connect all atoms with given coordinates,
     such as after coordinate file import, based on a given builder
 
     does this need to live within Conopology ?
   */
-  void ConnectAll(const BuilderP& b, mol::EntityHandle eh, int flag=0);
+  void ConnectAll(const BuilderP& b, mol::EntityHandle eh, 
+                  int flags=0);
 
   void RegisterBuilder(const BuilderP& b, const String& name);
   void SetDefaultBuilder(const String& default_name);
@@ -61,8 +61,7 @@ private:
   Conopology& operator=(const Conopology&) {return *this;}
 
   BuilderMap builder_map_;
-  std::map<String,Real> ele_rad_map_;
-  std::map<String,Real> ele_mass_map_;
+  std::set<String> known_elements_;
 };
 
 }} //
diff --git a/modules/conop/src/heuristic_builder.cc b/modules/conop/src/heuristic_builder.cc
index bb4a63a229bfdc5b270b447538115df02a8b9659..c808dbd083f43204855c10c9dd24ff768d312508 100644
--- a/modules/conop/src/heuristic_builder.cc
+++ b/modules/conop/src/heuristic_builder.cc
@@ -195,7 +195,7 @@ void HeuristicBuilder::ConnectivityFromAtomNames(const mol::ResidueHandle& res,
                                                  mol::AtomHandleList& unknown_atoms) {
  unknown_atoms.clear();
  mol::AtomHandleList atomlist=res.GetAtomList();
- mol::XCSEditor editor=res.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+ mol::XCSEditor editor=res.GetEntity().EditXCS(mol::BUFFERED_EDIT);
  for (mol::AtomHandleList::iterator it1=atomlist.begin();it1!=atomlist.end();++it1) {
    if (centry.HasAtom(it1->GetName())) {
      mol::AtomHandleList::iterator it2=it1;
@@ -265,7 +265,7 @@ void ConnectPrevNext(HeuristicBuilder* builder,mol::ResidueHandle res0,
 {
   static String fname=flag ? "HeuristicBuilder: ConnectNextXCS" : "HeuristicBuilder: ConnectPrevXCS";
   if(!res0) return; // return if invalid
-  mol::XCSEditor editor=res0.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=res0.GetEntity().EditXCS(mol::BUFFERED_EDIT);
   LOG_DEBUG(fname << " on " << res0.GetKey() << " " << res0.GetNumber());
 
   if(!res1) {
@@ -333,7 +333,7 @@ void ConnectPrevNext(HeuristicBuilder* builder,mol::ResidueHandle res0,
 void HeuristicBuilder::AssignTorsionsToResidue(mol::ResidueHandle res)
 {
 
-  mol::XCSEditor editor=res.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=res.GetEntity().EditXCS(mol::BUFFERED_EDIT);
   mol::ChainHandle chain=res.GetChain();
   std::pair<detail::ConnResEntry,bool> centry2 = LookupResEntry(res.GetKey());
   if (centry2.second) {
@@ -474,18 +474,9 @@ bool HeuristicBuilder::IsResidueComplete(const mol::ResidueHandle& rh)
 
 void HeuristicBuilder::FillAtomProps(mol::AtomHandle atom)
 {
-  mol::AtomProp prop=atom.GetAtomProps();
-  if (prop.element=="") {
-    prop.element=Builder::GuessAtomElement(atom.GetName(), prop.is_hetatm);
+  if (atom.GetElement()=="") {
+    atom.SetElement(Builder::GuessAtomElement(atom.GetName(), atom.IsHetAtom()));
   }
-  Conopology& conop_inst=Conopology::Instance();
-  if (prop.radius==0.0) {
-    prop.radius=conop_inst.GetDefaultAtomRadius(prop.element);    
-  }
-  if (prop.mass==0.0) {
-    prop.mass=conop_inst.GetDefaultAtomMass(prop.element);    
-  }
-  atom.SetAtomProps(prop);  
 }
 
 }} // ns
diff --git a/modules/conop/src/rule_based_builder.cc b/modules/conop/src/rule_based_builder.cc
index e47c96e358850eb5f89111d575366577e2e9eab7..03bfb13a25deba48e28b5f24aa46a44a7954b757 100644
--- a/modules/conop/src/rule_based_builder.cc
+++ b/modules/conop/src/rule_based_builder.cc
@@ -49,7 +49,7 @@ void RuleBasedBuilder::CheckResidueCompleteness(const mol::ResidueHandle& rh)
   mol::AtomHandleList atoms=rh.GetAtomList();
   mol::AtomHandleList::iterator i=atoms.begin();
   for (; j!=last_compound_->GetAtomSpecs().end() && i!=atoms.end(); ++j) {
-    if ((*j).is_leaving || (*j).element=="H")
+    if ((*j).is_leaving || (*j).element=="H" || (*j).element=="D")
       continue;
     if ((*j).ordinal!=static_cast<int>((*i).Impl()->GetState())) {
       this->OnMissingAtom(rh, (*j).name);
@@ -72,7 +72,8 @@ bool RuleBasedBuilder::HasUnknownAtoms(mol::ResidueHandle res)
   for (mol::AtomHandleList::iterator 
        i=atoms.begin(), e=atoms.end(); i!=e; ++i) {
     if ((*i).Impl()->GetState()==std::numeric_limits<unsigned int>::max()) {
-      if ((*i).GetElement()=="H" && this->GetStrictHydrogenMode()==false) {
+      if (((*i).GetElement()=="H" || (*i).GetElement()=="D") && 
+          this->GetStrictHydrogenMode()==false) {
         continue;
       }
       return true;
@@ -84,17 +85,9 @@ bool RuleBasedBuilder::HasUnknownAtoms(mol::ResidueHandle res)
 void RuleBasedBuilder::FillAtomProps(mol::AtomHandle atom, const AtomSpec& spec) 
 {
   Conopology& conop_inst=Conopology::Instance();
-  mol::AtomProp props=atom.GetAtomProps();
-  if (!conop_inst.IsValidElement(props.element)) {
-    props.element=spec.element;
-  }
-  if (props.radius==0.0) {
-    props.radius=conop_inst.GetDefaultAtomRadius(spec.element);    
-  }
-  if (props.mass==0.0) {
-    props.mass=conop_inst.GetDefaultAtomMass(spec.element);
-  }
-  atom.SetAtomProps(props);  
+  if (!conop_inst.IsValidElement(atom.GetElement())) {
+    atom.SetElement(spec.element);
+  } 
 }
 
 void RuleBasedBuilder::FillResidueProps(mol::ResidueHandle residue) 
@@ -209,7 +202,7 @@ void RuleBasedBuilder::ConnectAtomsOfResidue(mol::ResidueHandle rh)
     dist_connect(this, rh.GetAtomList());
     return;
   }
-  mol::XCSEditor e=rh.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor e=rh.GetEntity().EditXCS(mol::BUFFERED_EDIT);
   BondSpecList::const_iterator j=last_compound_->GetBondSpecs().begin();
   mol::AtomHandleList atoms=rh.GetAtomList();
   for(; j!=last_compound_->GetBondSpecs().end(); ++j) {
@@ -218,14 +211,15 @@ void RuleBasedBuilder::ConnectAtomsOfResidue(mol::ResidueHandle rh)
       mol::AtomHandle a2=this->LocateAtom(atoms, bond.atom_two);
       if (a1.IsValid() && a2.IsValid() && this->IsBondFeasible(a1, a2)) {
         if (this->GetStrictHydrogenMode() && 
-            (a1.GetElement()=="H" || a2.GetElement()=="H")) {
+            (a1.GetElement()=="H" || a2.GetElement()=="D")) {
           continue;
         }
         e.Connect(a1, a2, bond.order);
       }
   }
   for (mol::AtomHandleList::iterator i=atoms.begin(), e=atoms.end(); i!=e; ++i) {
-    if ((*i).GetElement()=="H" && (*i).GetBondCount()==0) {
+    if (((*i).GetElement()=="H" || (*i).GetElement()=="D") && 
+        (*i).GetBondCount()==0) {
       this->DistanceBasedConnect(*i);
     }
   }
@@ -238,7 +232,7 @@ void RuleBasedBuilder::ConnectResidueToNext(mol::ResidueHandle rh,
     return;
   }
   Compound::Dialect dialect=this->GetDialect()==PDB_DIALECT ? Compound::PDB : Compound::CHARMM;
-  mol::XCSEditor e=rh.GetEntity().RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor e=rh.GetEntity().EditXCS(mol::BUFFERED_EDIT);
   CompoundPtr mc=compound_lib_->FindCompound(rh.GetName(), dialect);
   CompoundPtr nc=compound_lib_->FindCompound(next.GetName(), dialect);
   if (!(mc && nc))
@@ -301,7 +295,7 @@ bool RuleBasedBuilder::IsResidueComplete(const mol::ResidueHandle& residue)
   mol::AtomHandleList::iterator i=atoms.begin();
   for (AtomSpecList::const_iterator j=last_compound_->GetAtomSpecs().begin(),
        e=last_compound_->GetAtomSpecs().end(); j!=e; ++j) {
-    if ((*j).is_leaving || (*j).element=="H") {
+    if ((*j).is_leaving || (*j).element=="H" || (*j).element=="D") {
       continue;      
     }
     if (!(residue.FindAtom(j->name) || residue.FindAtom(j->alt_name))) {
@@ -330,18 +324,10 @@ void RuleBasedBuilder::FillAtomProps(mol::AtomHandle atom)
 
 bool RuleBasedBuilder::OnUnknownAtom(mol::AtomHandle atom)
 {
-  mol::AtomProp props=atom.GetAtomProps();
   Conopology& conop_inst=Conopology::Instance();
-  if (!conop_inst.IsValidElement(props.element)) {
-    props.element=Builder::GuessAtomElement(atom.GetName(), props.is_hetatm);
-  }
-  if (props.radius==0.0) {
-    props.radius=conop_inst.GetDefaultAtomRadius(props.element);    
-  }
-  if (props.mass==0.0) {
-    props.mass=conop_inst.GetDefaultAtomMass(props.element);
+  if (!conop_inst.IsValidElement(atom.GetElement())) {
+    atom.SetElement(Builder::GuessAtomElement(atom.GetName(), atom.IsHetAtom()));
   }
-  atom.SetAtomProps(props); 
   return false;
 }
 
diff --git a/modules/conop/tests/test_builder.cc b/modules/conop/tests/test_builder.cc
index 4ba860bb1ecad1c498a7b7a42caba41138d3df03..9a4ff6aa6e60c3784352e3d5f03d7fc0b4f58afd 100644
--- a/modules/conop/tests/test_builder.cc
+++ b/modules/conop/tests/test_builder.cc
@@ -18,6 +18,7 @@
 //------------------------------------------------------------------------------
 #include <ost/mol/mol.hh>
 #include <ost/conop/builder.hh>
+#include <ost/conop/heuristic_builder.hh>
 #define BOOST_TEST_DYN_LINK
 #include <boost/test/unit_test.hpp>
 
@@ -29,6 +30,24 @@ using namespace ost::mol;
 
 BOOST_AUTO_TEST_SUITE( conop )
 
+BOOST_AUTO_TEST_CASE(test_guess_chem_class)
+{
+  HeuristicBuilder h;
+  EntityHandle ent=mol::CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  ChainHandle chain=edi.InsertChain("A");
+  ResidueHandle res=edi.AppendResidue(chain, "DUMMY");
+  AtomHandle n=edi.InsertAtom(res, "N", geom::Vec3(1, 0, 0), "N");
+  AtomHandle ca=edi.InsertAtom(res, "CA", geom::Vec3(2, 0, 0), "C");
+  AtomHandle c=edi.InsertAtom(res, "C", geom::Vec3(3, 0, 0), "C");
+  AtomHandle o=edi.InsertAtom(res, "O", geom::Vec3(4, 0, 0), "O");
+  h.GuessChemClass(res);
+  BOOST_CHECK(res.IsPeptideLinking());
+  res.SetChemClass(ChemClass());
+  edi.SetAtomPos(n, geom::Vec3(-1,0,0));
+  h.GuessChemClass(res);
+  BOOST_CHECK(!res.IsPeptideLinking());
+}
 
 BOOST_AUTO_TEST_CASE( test_builder )
 {
diff --git a/modules/conop/tests/test_heuristic_builder.cc b/modules/conop/tests/test_heuristic_builder.cc
index 473ff46dd7c1addd82403eeebdfd09e15793ccdb..33a1aaa7606a8fcfce335c28102293b83f98b48e 100644
--- a/modules/conop/tests/test_heuristic_builder.cc
+++ b/modules/conop/tests/test_heuristic_builder.cc
@@ -33,7 +33,7 @@ namespace {
 
 ResidueHandle make_arg(ChainHandle chain) 
 {
-  XCSEditor e=chain.GetEntity().RequestXCSEditor();
+  XCSEditor e=chain.GetEntity().EditXCS();
   ResidueHandle res = e.AppendResidue(chain, "ARG");
   e.InsertAtom(res, "N",geom::Vec3(20.202,33.112,58.011));
   e.InsertAtom(res, "CA",geom::Vec3(19.396,31.903,58.033));
@@ -51,7 +51,7 @@ ResidueHandle make_arg(ChainHandle chain)
 
 ResidueHandle make_leu(ChainHandle chain) 
 {
-  XCSEditor e=chain.GetEntity().RequestXCSEditor();  
+  XCSEditor e=chain.GetEntity().EditXCS();  
   ResidueHandle res=e.AppendResidue(chain, "LEU");
 
   e.InsertAtom(res, "N", geom::Vec3(19.003,32.473,60.366));
@@ -146,7 +146,7 @@ BOOST_AUTO_TEST_SUITE( conop )
 BOOST_AUTO_TEST_CASE(name_based_connect) 
 {
   EntityHandle e=CreateEntity();
-  ChainHandle c=e.RequestXCSEditor().InsertChain("A");
+  ChainHandle c=e.EditXCS().InsertChain("A");
   ResidueHandle ile=make_leu(c);
   ResidueHandle arg=make_arg(c);
   HeuristicBuilder heuristic_builder;  
@@ -164,7 +164,7 @@ BOOST_AUTO_TEST_CASE(name_based_connect)
 
 BOOST_AUTO_TEST_CASE(test_assign_torsions){
   EntityHandle e=CreateEntity();
-  ChainHandle c=e.RequestXCSEditor().InsertChain("A");
+  ChainHandle c=e.EditXCS().InsertChain("A");
   ResidueHandle l1=make_leu(c);
   ResidueHandle a2=make_arg(c);
   ResidueHandle l3=make_leu(c);
@@ -178,7 +178,7 @@ BOOST_AUTO_TEST_CASE(test_assign_torsions){
   heuristic_builder.ConnectAtomsOfResidue(l1);
   heuristic_builder.ConnectAtomsOfResidue(a2);
   heuristic_builder.ConnectAtomsOfResidue(l3);
-  XCSEditor edi=e.RequestXCSEditor();
+  XCSEditor edi=e.EditXCS();
   edi.Connect(l1.FindAtom("C"), a2.FindAtom("N"));
   edi.Connect(a2.FindAtom("C"), l3.FindAtom("N"));  
   heuristic_builder.AssignTorsions(c);
diff --git a/modules/doc/contributing.rst b/modules/doc/contributing.rst
new file mode 100644
index 0000000000000000000000000000000000000000..a698032336c1157391ed64abbe726d4959bbbcc8
--- /dev/null
+++ b/modules/doc/contributing.rst
@@ -0,0 +1,102 @@
+Contributing to OpenStructure
+================================================================================
+
+.. note::
+
+  This document describes how to develop features to be included in OpenStructure. If you are mainly planning to use the framework, from Python you probably shouldn't read this document and refer to the :doc:`API docs <index>` instead.
+
+OpenStructure uses `git <http://git-scm.org>`_ as the revision control system. It allows for branch-and-merge driven workflows ideal for a scientific environment. 
+
+The main repository can be browsed `here <http://dng.biozentrum.unibas.ch/git/>`_. 
+
+
+Even though, technically, there is no such a thing as a central repository in git, we use a central "repository of truth" where everyone is pulling from. You can get the source code with ``git clone``:
+
+.. code-block:: bash
+
+  git clone https://dng.biozentrum.unibas.ch/git/ost.git
+
+
+For information on how to install OpenStructure from source, refer to :doc:`install`. 
+
+Leaving aside all the short-lived features branches, the OpenStructure repository has two long-lived branches, one called master and one called develop. Master contains the latest stable changes, develop contains features currently under development that are  potentially not working. Once stable, the changes in develop will be merged into master and together will form the next release. A very detailed description of the branching model used for OpenStructure is available at `this site <http://nvie.com/posts/a-successful-git-branching-model/>`_.
+
+
+
+Making Changes
+--------------------------------------------------------------------------------
+
+The common workflow of making changes to OpenStructure is depicted in the following section.
+
+Even though it is not neccessary, it is advised to carry out your changes in a separate branch. The new branch can be created with:
+
+.. code-block:: bash
+  
+  # checkout branch my_branch and create it if it doesn't exist yet.
+  # Of course you are free to name the branch whatever you want.
+  git checkout -b my_branch
+
+From now on, all your work will be carried out in my_branch. Make your changes and once you are happy, commit them to your repository.
+
+
+Writing Good Commit Messages
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Your commit message should have a one-line description that summarize the change and optionally a more detailed description of what the changes imply. An example from the commit history. The one-liner and the detailed description are separated by an empty line. The reason for this format is that the one-line description will be used as the subject line for the patches generated by format-patch and the ones sent to the commit mailing lists. People can quickly see if the change is of interest to that they can savely ignore the e-mail. 
+
+Additionally, they also come in handy when using the --online option of ``git log``.
+
+Writing Documentation
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+OpenStructure uses `sphinx <http://sphinx.pocoo.org>`_ as the documentation generator. The main part of the documentation  each module resides in files with the ``.rst`` extension in a sub-folder called doc.
+
+To convert the .rst files to html use the doc/make.py script:
+
+.. code-block:: bash
+
+  ost doc/make.py
+
+The script first recursively searches for modified ``.rst`` files, starting at the modules directory and copies the files that have changed to ``doc/source``. It also copies images to the source directory. Then it runs sphinx to convert the documentation to html. If no further options are given to the script, the html documentation is generated. The HTML, CSS and static media files will be put into ``doc/html/build``.
+
+For classes and functions written in Python, it is possible to tell sphinx to  extract the documentation directly from the doc-string. For example, to get the documentation for :func:`~ost.io.LoadPDB`, you can use:
+
+.. code-block:: rest
+
+  .. autofunction:: ost.io.LoadPDB
+
+
+Synchronizing with upstream changes
+--------------------------------------------------------------------------------
+
+In the meanwhile, someone else might have committed changes to the develop branch. The best and cleanest way to incorporate these changes is to rebase your changes onto the latest develop branch:
+
+.. code-block:: bash
+
+  git checkout develop
+  # pull the latest changes to make sure we are up to date
+  git pull
+  git checkout my_branch
+  # rebase the changes
+  git rebase develop
+
+
+Sending Patches
+--------------------------------------------------------------------------------
+
+Changes always go into develop first before being integrated into master. Unless, you have commit access, the easiest way to share your changes is to create a patch and send it by email to the mailing list or one of the developers. To create a suitable diff, rebase your changes onto the latest develop branch and use the ``format-patch`` command:
+
+.. code-block:: bash
+
+  # this takes all the changes you introduced and writes them to 
+  # changeset.diff
+  git format-patch --stdout develop > changeset.diff
+
+Applying Patches
+--------------------------------------------------------------------------------
+
+If you got a patch from someone else and would like to use apply it to your repository, use ``git am``.
+
+.. code-block:: bash
+
+  git am < changeset.diff
\ No newline at end of file
diff --git a/modules/doc/install.rst b/modules/doc/install.rst
index abd0b2b88fc0b8a8847d45fecad463bda6219b5c..525561543c3cb201d7ff8ed417a7fd86041a3fa0 100644
--- a/modules/doc/install.rst
+++ b/modules/doc/install.rst
@@ -7,6 +7,7 @@ Installing OpenStructure From Source
   mainly insterested in using OpenStructure and are not planning to modify the
   code of OpenStructure itself, please use one of the binaries `available for
   download <http://www.openstructure.org/download/>`_.
+  
 
 Brief Overview
 --------------------------------------------------------------------------------
@@ -14,7 +15,7 @@ Brief Overview
 Compiling OpenStructure consists of several steps that are described below in more detail. In essence, these steps are:
 
  * Installing the Dependencies
- * Checking out the source code from SVN
+ * Checking out the source code from GIT
  * Configuring the build with cmake
  * Compiling an Linking
  
@@ -54,20 +55,20 @@ Solutions->VC++ directories. Choose 'bin' directories to enter program paths to
 cmake, qmake and python, 'lib' directories to point to the location(s) of your 
 dependencies.
 
-Checking out the Source
+
+
+Getting the Source Code
 --------------------------------------------------------------------------------
 
-You can checkout the source from SVN. The repository is located at
 
-   https://dng.biozentrum.unibas.ch/svn/openstructure/trunk
+OpenStructure uses `git` as the revision control system. The main repository can be browsed `here <http://dng.biozentrum.unibas.ch/git/>`_. To get the source code, use git clone:
 
-If you are using the commandline client, type in your shell 
 
 .. code-block:: bash
 
-   svn co https://dng.biozentrum.unibas.ch/svn/openstructure/trunk
-
-On Windows, we recommend to install a graphical frontend for svn, for example `tortoisesvn <http://tortoisesvn.tigris.org>`_. 
+  git clone https://dng.biozentrum.unibas.ch/git/ost.git <directory-name>
+  
+The above command will clone OpenStructre into the directory called `directory-name`. If omitted, the directory will be called ost. Alternatively, you might consider getting one of the nightly source code snapshots from the `downloads section <http://www.openstructure.org/downloads/>`_.
 
 
 Configuring
diff --git a/modules/doc/intro-01.rst b/modules/doc/intro-01.rst
index da448f8c3e05e5c03572377bf31e52af81df0c84..cca9e786b16581faa973456fa6cd069a4cb81779 100644
--- a/modules/doc/intro-01.rst
+++ b/modules/doc/intro-01.rst
@@ -1,7 +1,7 @@
 Introduction to the :mod:`~ost.mol` Module
 ================================================================================
 
-For the course of this tutorial, we assume that you have :ref:`DNG up and running<start-dng>`.
+For the course of this tutorial, we assume that you have :ref:`DNG up and running <start-dng>`.
 
 Loading and inspecting a protein structure
 --------------------------------------------------------------------------------
@@ -21,10 +21,10 @@ To load a PDB file, simply type
 
 .. code-block:: python
 
-   fragment=io.LoadPDB('/path/to/examples/entity/fragment.pdb')
+   fragment=io.LoadPDB('/path/to/examples/code_fragments/entity/fragment.pdb')
 
 This will load the fragment from the specified file 'fragment.pdb' and store the 
-result in fragment.  The :func:`~ost.io.LoadPDB` has many option, which, for 
+result in fragment.  The :func:`~ost.io.LoadPDB` has many options, which, for
 simplicity will not be discussed here. If you want to know more about the 
 function, type:
 
@@ -58,7 +58,7 @@ This will group the atoms by residue. And, for completeness, we will first group
 
 .. code-block:: python
 
-  for chain in fragments.chains:
+  for chain in fragment.chains:
     print 'chain', chain.name, 'has', len(chain.residues), 'residue(s)'
     for residue in chain.residues:
       print ' ', residue, 'has', len(residue.atoms), 'atom(s).'
@@ -75,17 +75,16 @@ what bonds we have in there:
     
 From these short code examples we already see how the entity is structured: On 
 one hand we have a hierarchy of chains, residues and atoms. On the other hand, 
-we have bonds that form a network overlayed on the hierarchy. This is 
-illustrated in the picture on the left. An important feature of entities is that 
-we can always assume that the hierarchy is intact. You will never find an atom 
-without residues, no residue can exist without a parent chain and chains belong 
-always to an entity. 
+we have bonds that form a network overlayed on the hierarchy. An important 
+feature of entities is that we can always assume that the hierarchy is intact. 
+You will never find an atom without residues, no residue can exist without a 
+parent chain and chains belong always to an entity. 
 
 Let There Be Shiny Graphics
 --------------------------------------------------------------------------------
 
 For visually inspecting the fragment, we now create a graphical representation 
-of the entity. The graphical representation os completely separate from the :class:`~ost.mol.EntityHandle` class. This is on purpose. When writing processing scripts, usually no graphical representation is required and things would be slowed down without any reason. The following code will take our fragment and initialise a :class:`gfx.Entity<ost.gfx.Entity>`, add it to the scene, and center the camera on it.
+of the entity. The graphical representation is completely separate from the :class:`~ost.mol.EntityHandle` class. This is on purpose. When writing processing scripts, usually no graphical representation is required and things would be slowed down without any reason. The following code will take our fragment and initialise a :class:`gfx.Entity<ost.gfx.Entity>`, add it to the scene, and center the camera on it.
 
 .. code-block:: python
   
@@ -96,8 +95,8 @@ of the entity. The graphical representation os completely separate from the :cla
 
 Now you will see the fragment in the 3D window.
 
-Use the mouse to rotate, zoom in an shift the camera. Double clicking on an atom 
-will center the camera on that atom. If you want to learn more about the 
+Use the mouse to rotate, zoom in an shift the camera. Double clicking on an 
+atom will center the camera on that atom. If you want to learn more about the 
 :mod:`~ost.gfx` module, you are encouraged to read :doc:`the gfx 
 intro<intro-03>` and the :mod:`gfx documentation<ost.gfx`.
 
diff --git a/modules/doc/newmodule.rst b/modules/doc/newmodule.rst
index d821de02c707988b92138eae1426e70407e7bc53..beca4c215e9723498ce9fdef31aee723f9b41c95 100644
--- a/modules/doc/newmodule.rst
+++ b/modules/doc/newmodule.rst
@@ -51,8 +51,8 @@ Here is a skeleton of one of the files in  the directory , `modeling_new_class.h
 
 .. code-block:: cpp 
 
-  #ifndef OST_MOD_NEW_CLASS_H
-  #define OST_MOD_NEW_CLASS_H
+  #ifndef OST_MOD_NEW_CLASS_HH
+  #define OST_MOD_NEW_CLASS_HH
   
   #include <ost/mod/module_config.hh>
   
@@ -160,73 +160,47 @@ The Testing Framework
 The `tests` directory contains code for unit tests. The code is compiled and 
 executed when one invokes compilation using the 'make check' command.  Tests are 
 run by means of the `Boost Unitests Library 
-<http://www.boost.org/doc/libs/1_37_0/libs/test/doc/html/index.html>`_, which is 
-used throughout OpenStructure. Before coding the test routines, the required 
-skeleton needs to be put in place.
+<http://www.boost.org/doc/libs/1_37_0/libs/test/doc/html/index.html>`_. Before coding the test routines, the required skeleton needs to be put in place.
 
-The main code is put into 'tests.cc', which will become the test executable:
+The main code is put into 'tests.cc', which will become the test executable. There are only 3 lines required
     
 .. code-block:: cpp
 
+  #define BOOST_TEST_DYN_LINK
+  #define BOOST_TEST_MODULE ost_mod
   #include <boost/test/unit_test.hpp>
-  using boost::unit_test_framework::test_suite;
-  
-  #include "test_modeling.hh"
-  
-  test_suite*
-  unit_unit_test_suite( int argc, char * argv[] ) {
-    std::auto_ptr<test_suite> test(BOOST_TEST_SUITE( "Module Mod Test" ));
-  
-    test->add(CreateModelingTest()); 
-  
-    return test.release(); 
-  }
   
         
-The most relevant line adds the test suite for the new module to the global test 
-list. The test suite is created by the factory function CreateModelingTest(), 
-which is declared in the `test_modeling.hh` header file. 
+Based on the two macros BOOST_TEST_DYN_LINK and BOOST_TEST_MODULE, the boost unit test framework will introduce a main function that executes all the unit tests that we will define next.
+      
+The definition of the actual unit tests is done in separate .cc files. Create the test_modeling_new_class.cc file and fill it with the following code:
 
 .. code-block:: cpp
 
-  #ifndef OST_MOD_TEST_MODELING_H
-  #define OST_MOD_TEST_MODELING_H
-  
+  #define BOOST_TEST_DYN_LINK
   #include <boost/test/unit_test.hpp>
-  using boost::unit_test_framework::test_suite;
-  
-  test_suite* CreateModelingTest();
-  
-  #endif
-      
-The definition of the factory function is found in the actual test code,
-which we put in `test_modeling.cc`. Here is a skeleton version of that file:
 
-.. code-block:: cpp
+  #include <ost/mod/modeling_new_class.hh>
 
-  #include "test_modeling.hh"
-  
-  // additional include statements will go here
-  
-  namespace test_modeling {
-  
-    void test() 
-    {
-      // test code will go here
-    }
-  
+	using namespace ost;
+  using namespace ost::mod;
+
+
+  BOOST_AUTO_TEST_SUITE(mod_new_class)
+
+  BOOST_AUTO_TEST_CASE(mode_trivial_case)
+  {
+    // ... your test code here...
   }
-  
-  test_suite* CreateModelingTest()
+
+  BOOST_AUTO_TEST_CASE(somewhat_more_involved_case)
   {
-    using namespace test_modeling;
-    test_suite* ts=BOOST_TEST_SUITE("Modeling Test");
-     ts->add(BOOST_TEST_CASE(&test));
-  
-     return ts;
+    // ... your test code here...
   }
+
+  BOOST_AUTO_TEST_SUITE_END()
   
-In this file, all the normal Boost Test Library macros and functions can be used. (For example `BOOST_CHECK`, `BOOST_FAIL`, etc.)
+We again have to define the BOOST_TEST_DYN_LINK macro before including the bosot unit test headers. This will tell the boost unit test libraries that we intend to use dynamic linking. Then we include the functions and classes we would like to write unit tests for. In this file, all the normal Boost Test Library macros and functions can be used. (For example `BOOST_CHECK`, `BOOST_FAIL`, etc.)
 
 Here is finally the build script skeleton that needs to be put into 
 `mod/tests/`:
diff --git a/modules/geom/pymod/export_mat3.cc b/modules/geom/pymod/export_mat3.cc
index ee66e38d6439c54dab43058f9e2d73d1cca3a56b..9f9e245324622d47862239fe3b26ea90f1183cd2 100644
--- a/modules/geom/pymod/export_mat3.cc
+++ b/modules/geom/pymod/export_mat3.cc
@@ -58,6 +58,7 @@ void export_Mat3()
   class_<Mat3>("Mat3",init<>())
     .def(init<Real,Real,Real,Real,Real,Real,Real,Real,Real>())
     .def(init<const Mat2&>())
+    .def(init<Real,Real,Real>())
     .def(self += self)
     .def(self -= self)
     .def(self + self)
diff --git a/modules/geom/pymod/export_vec3.cc b/modules/geom/pymod/export_vec3.cc
index 25c9cd164f961bdd21fa236bf0a1cea8ff715b83..a077c25dda83cea0680b72f8e135bc885609f080 100644
--- a/modules/geom/pymod/export_vec3.cc
+++ b/modules/geom/pymod/export_vec3.cc
@@ -31,6 +31,13 @@ geom::Vec3 NormalizeV3(const geom::Vec3& v) {
   return geom::Normalize(v);
 }
 
+
+void vec_test(const geom::Vec3List& v)
+{
+  for (size_t i=0; i<v.size(); ++i) {
+    std::cout << i << v[i] << std::endl;
+  }
+}
 void export_Vec3()
 {
   using namespace geom;
@@ -75,4 +82,5 @@ void export_Vec3()
     .add_property("inertia", &Vec3List::GetInertia)
     .add_property("principal_axes", &Vec3List::GetPrincipalAxes)
   ;
+  def("vec_test", &vec_test);
 }
diff --git a/modules/geom/pymod/export_vecmat3_op.cc b/modules/geom/pymod/export_vecmat3_op.cc
index cdafc821ce62797a555c1c2b98e29f661208e3ce..5f0939b1a2f2441e646ba4dd0e1593cbba1ddfea 100644
--- a/modules/geom/pymod/export_vecmat3_op.cc
+++ b/modules/geom/pymod/export_vecmat3_op.cc
@@ -49,6 +49,7 @@ void export_VecMat3_op()
   def("CompDivide",Vec3CompDivide);
   def("Distance",Vec3Distance);  
   def("Equal",Mat3Equal);
+  def("DihedralAngle", &DihedralAngle);
   def("Dot",Mat3Dot);
   def("Det",Mat3Det);
   def("Cross",Vec3Cross);
diff --git a/modules/geom/src/aligned_cuboid.hh b/modules/geom/src/aligned_cuboid.hh
index 18438cc78b4b85fc4657e1df9e784a21061b56a3..2cc123e6269633b16d0eeee81ea399e402204744 100644
--- a/modules/geom/src/aligned_cuboid.hh
+++ b/modules/geom/src/aligned_cuboid.hh
@@ -48,6 +48,12 @@ private:
   Vec3 max_;
 };
 
+inline std::ostream& operator<<(std::ostream& os, const AlignedCuboid& c)
+{
+  os << "(" << c.GetMin() << "," << c.GetMax() << ")";
+  return os;
+}
+
 AlignedCuboid DLLEXPORT_OST_GEOM Union(const AlignedCuboid& lhs, const AlignedCuboid& rhs);
 
 }
diff --git a/modules/geom/src/mat3.hh b/modules/geom/src/mat3.hh
index 15815863328fe4ca1039ced2b5d48250eef952cd..d16a14f5569eaa6c84504dda1facba0a3aaf8991 100644
--- a/modules/geom/src/mat3.hh
+++ b/modules/geom/src/mat3.hh
@@ -27,10 +27,8 @@
 
 #include <ost/geom/module_config.hh>
 #include <ost/geom/mat2.hh>
-
 namespace geom {
 
-class Mat2;
 class Vec3;
 
 class DLLEXPORT_OST_GEOM Mat3:
@@ -76,8 +74,12 @@ public:
   explicit Mat3(const Real arr[9])
   {
     this->set(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7],arr[8]);
-  }  
+  }
 
+  explicit Mat3(Real x, Real y, Real z)
+  {
+    this->set(x, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, z);
+  }
   //! element access
   Real& operator()(std::size_t r, std::size_t c)
   {
diff --git a/modules/geom/src/quat.cc b/modules/geom/src/quat.cc
index ceb178713e8641862d763a06f09023faa039004b..14aa5e60c55934c22930a433d707baea4eea6543 100644
--- a/modules/geom/src/quat.cc
+++ b/modules/geom/src/quat.cc
@@ -404,6 +404,54 @@ Quat Slerp(const Quat& q0, const Quat& q1, Real t)
   return nrvo;
 }
 
+Quat Inv(const Quat& q)
+{
+  Real l=q.w*q.w+q.x*q.x+q.y*q.y+q.z*q.z;
+  Quat ret;
+  if(l>0.0) {
+    ret.w=q.w/l;
+    ret.x=-q.x/l;
+    ret.y=-q.y/l;
+    ret.z=-q.z/l;
+  }
+  return ret;
+}
+
+Quat Exp(const Quat& q)
+{
+  Real a = sqrt(q.x*q.x+q.y*q.y+q.z*q.z);
+  Real sina = sin(a);
+  Real cosa = cos(a);
+  Quat ret;
+
+  ret.w = cosa;
+  if(a>0.0) {
+    ret.x = sina * q.x/a;
+    ret.y = sina * q.y/a;
+    ret.z = sina * q.z/a;
+  } else {
+    ret.x = ret.y = ret.z = 0.0;
+  }
+  return ret;
+}
+
+Quat Log(const Quat& q)
+{
+  Real a = acos(q.w);
+  Real sina = sin(a);
+  Quat ret;
+
+  ret.w = 0.0;
+  if(sina>0.0) {
+    ret.x = a*q.x/sina;
+    ret.y = a*q.y/sina;
+    ret.z = a*q.z/sina;
+  } else {
+    ret.x= ret.y= ret.z= 0.0;
+  }
+  return ret;
+}
+
 Vec3 Quat::Rotate(const Vec3& vec) const {
   Quat tmp(0.0, vec[0], vec[1], vec[2]);
   Quat conj=Conjugate(*this);
diff --git a/modules/geom/src/quat.hh b/modules/geom/src/quat.hh
index f8babf8668e8763c5b98b42d23abaaf99317919f..d2d1ea3e45c2841df0d402ccba5675e6c894a49d 100644
--- a/modules/geom/src/quat.hh
+++ b/modules/geom/src/quat.hh
@@ -111,6 +111,10 @@ Real DLLEXPORT_OST_GEOM Dot(const Quat& q0, const Quat& q1);
 // spherical linear interpolation, with t in range [0,1]
 Quat DLLEXPORT_OST_GEOM Slerp(const Quat& q0, const Quat& q1, Real t);
 
+Quat DLLEXPORT_OST_GEOM Inv(const Quat& q);
+Quat DLLEXPORT_OST_GEOM Exp(const Quat& q);
+Quat DLLEXPORT_OST_GEOM Log(const Quat& q);
+
 Quat DLLEXPORT_OST_GEOM Grassmann(const Quat& lhs, const Quat& rhs);
 
 //normalize quaternion
diff --git a/modules/geom/src/vec3.hh b/modules/geom/src/vec3.hh
index 4d139a3211980d7a41c656c97d9b323e2fb69e92..47b301fb32ad4657130e34dfdb3e6ac10364c7c9 100644
--- a/modules/geom/src/vec3.hh
+++ b/modules/geom/src/vec3.hh
@@ -208,7 +208,7 @@ public:
   
   Vec3List& operator=(const Vec3List& rhs) 
   {
-    *this=rhs;
+    base_type::operator=(rhs);
     return *this;
   }
   Mat3 GetInertia() const;
diff --git a/modules/geom/src/vecmat3_op.cc b/modules/geom/src/vecmat3_op.cc
index 4c6a2732a70ecb9f02b0325300bd534aaa64e7fb..3066deef9a85a45d42fc6a77641d673667a7e89f 100644
--- a/modules/geom/src/vecmat3_op.cc
+++ b/modules/geom/src/vecmat3_op.cc
@@ -101,6 +101,14 @@ Real Angle(const Vec3& v1, const Vec3& v2)
   return std::acos(dot_product);
 }
 
+Real SignedAngle(const Vec3& v1, const Vec3& v2, const Vec3& ref_normal )
+{
+  Vec3 a=Normalize(v1);
+  Vec3 b=Normalize(v2);
+  Vec3 c=Normalize(ref_normal);
+  return std::atan2(Dot(c,Cross(a,b)), Dot(a,b));
+}
+
 Mat3 EulerTransformation(Real theta, Real phi, Real xi)
 {
   Real costheta=cos(theta);
@@ -171,4 +179,17 @@ Mat3 AxisRotation(const Vec3& axis, Real angle)
           xz-ca*xz-sa*y, yz-ca*yz+sa*x,zz+ca-ca*zz);
 }
 
+
+Real DihedralAngle(const Vec3& p1, const Vec3& p2, const Vec3& p3, 
+                   const Vec3&p4)
+{
+  Vec3 r1=p2-p1;
+  Vec3 r2=p3-p2;
+  Vec3 r3=p4-p3;
+  Vec3 r12cross = Cross(r1, r2);
+  Vec3 r23cross = Cross(r2, r3);
+  return atan2(Dot(r1*Length(r2), r23cross),
+               Dot(r12cross, r23cross));
+}
+
 } // ns
diff --git a/modules/geom/src/vecmat3_op.hh b/modules/geom/src/vecmat3_op.hh
index e4ca5a65b5eb0b2a9d11717fb68fa7a2c2c14a9d..94c3c77b32d2fe7cb45a34d0a66c5bc001a9a3fe 100644
--- a/modules/geom/src/vecmat3_op.hh
+++ b/modules/geom/src/vecmat3_op.hh
@@ -151,9 +151,12 @@ Real DLLEXPORT_OST_GEOM Minor(const Mat3& m, unsigned int i, unsigned int j);
 // determinant
 Real DLLEXPORT_OST_GEOM Det(const Mat3& m);
 
-// angle between zwo vectors
+// angle between two vectors
 Real DLLEXPORT_OST_GEOM Angle(const Vec3& v1, const Vec3& v2);
 
+// signed angle between two vectors, based on a reference normal
+Real DLLEXPORT_OST_GEOM SignedAngle(const Vec3& v1, const Vec3& v2, const Vec3& ref);
+
 Mat3 DLLEXPORT_OST_GEOM EulerTransformation(Real theta, Real phi, Real xi);
 
 Mat3 DLLEXPORT_OST_GEOM AxisRotation(const Vec3& axis, Real angle);
@@ -163,6 +166,10 @@ Mat3 DLLEXPORT_OST_GEOM AxisRotation(const Vec3& axis, Real angle);
 /// The returned vector is of length 1
 Vec3 DLLEXPORT_OST_GEOM OrthogonalVector(const Vec3& axis);
 
+
+Real DLLEXPORT_OST_GEOM DihedralAngle(const Vec3& p1, const Vec3& p2, 
+                                      const Vec3& p3, const Vec3&p4);
+
 //! returns std::min of each component
 inline Vec3 Min(const Vec3& v1, const Vec3& v2)
 {
diff --git a/modules/gfx/pymod/__init__.py b/modules/gfx/pymod/__init__.py
index badf23fbe8a0f766abe5f2defd45fbc298c30765..5788da8cfeaedcc6b400f545dd5a8ab5d99b711d 100644
--- a/modules/gfx/pymod/__init__.py
+++ b/modules/gfx/pymod/__init__.py
@@ -18,24 +18,174 @@
 #------------------------------------------------------------------------------
 from _gfx import *
 
-WHITE=Color(0xffffff)
-BLACK=Color(0x000000)
-GREY=Color(0x7f7f7f)
-RED=Color(0xff0000)
-DARKRED=Color(0x7f0000)
-LIGHTRED=Color(0xff7f7f)
-GREEN=Color(0x00ff00)
-DARKGREEN=Color(0x007f00)
-LIGHTGREEN=Color(0x7fff7f)
-BLUE=Color(0x0000ff)
-DARKBLUE=Color(0x00007f)
-LIGHTBLUE=Color(0x7f7fff)
-YELLOW=Color(0xffff00)
-DARKYELLOW=Color(0x7f7f00)
-LIGHTYELLOW=Color(0xffff7f)
-CYAN=Color(0x00ffff)
-DARKCYAN=Color(0x007f7f)
-LIGHTCYAN=Color(0x7fffff)
-MAGENTA=Color(0xff00ff)
-DARKMAGENTA=Color(0x7f00ff)
-LIGHTMAGENTA=Color(0xff7fff)
+WHITE=Color(1.0,1.0,1.0)
+BLACK=Color(0.0,0.0,0.0)
+GREY=Color(0.5,0.5,0.5)
+RED=Color(1.0,0.0,0.0)
+DARKRED=Color(0.5,0.0,0.0)
+LIGHTRED=Color(1.0,0.5,0.5)
+GREEN=Color(0.0,1.0,0.0)
+DARKGREEN=Color(0.0,0.5,0.0)
+LIGHTGREEN=Color(0.5,1.0,0.5)
+BLUE=Color(0.0,0.0,1.0)
+DARKBLUE=Color(0.0,0.0,0.5)
+LIGHTBLUE=Color(0.5,0.5,1.0)
+YELLOW=Color(1.0,1.0,0.0)
+DARKYELLOW=Color(0.5,0.5,0.0)
+LIGHTYELLOW=Color(1.0,1.0,0.5)
+CYAN=Color(0.0,1.0,1.0)
+DARKCYAN=Color(0.0,0.5,0.5)
+LIGHTCYAN=Color(0.5,1.0,1.0)
+MAGENTA=Color(1.0,0.0,1.0)
+DARKMAGENTA=Color(0.5,0.0,0.5)
+LIGHTMAGENTA=Color(1.0,0.5,1.0)
+PURPLE=MAGENTA
+DARKPURPLE=DARKMAGENTA
+LIGHTPURPLE=LIGHTMAGENTA
+ORANGE=Color(1.0,0.5,0.0)
+DARKORANGE=Color(0.5,0.25,0.0)
+LIGHTORANGE=Color(1.0,0.75,0.5)
+
+
+def Stereo(mode,flip=None,alg=None):
+  """
+  Stereo control
+
+  :param mode: 0=off, 1=quad-buffered, 2=interlaced
+  :type mode: int
+  :param flip: invert order of left/right display
+  :type flip: bool
+  :param alg: stereo algorithm (0 or 1)
+  :type param: int
+  """
+  if(flip):
+    _gfx.Scene().SetStereoFlip(flip)
+  if(alg):
+    _gfx.Scene().SetStereoAlg(alg)
+
+  _gfx.Scene().SetStereoMode(mode)
+
+def FitToScreen(gfx_ent, width=None, height=None, margin=0.01):
+  """
+  Setup camera such that it is centered on the graphical entity and the entity 
+  fits the entire viewport. The longest axes of the entity are aligned along 
+  the x- and y- axes of the screen.
+  
+  :param gfx_ent: The graphical entity
+  :type gfx_ent: str or :class:`Entity`
+  
+  
+  """
+  from ost import geom
+  import math
+  def _XYZ(view, axes):
+    """
+    returns the vectors in x, y and z direction respectively. The smallest 
+    vector is in z, then y, and the largest along x.
+    """
+    rows=[axes.GetRow(i) for i in range(3)]
+    lengths=[]
+    for axe in rows:
+      min_proj=geom.Dot(axe, view.atoms[0].pos)
+      max_proj=min_proj
+      for atom in view.atoms[1:]:
+        proj=geom.Dot(axe, atom.pos)
+        min_proj=min(proj, min_proj)
+        max_proj=max(proj, max_proj)
+      lengths.append(max_proj-min_proj)
+    def cmp_x(rhs, lhs):
+      return cmp(lhs[1], rhs[1])
+    sorted_axes=sorted(zip(rows, lengths), cmp_x)
+    return [r*l for r,l in sorted_axes]
+  scene=Scene()
+  if not isinstance(gfx_ent, Entity):
+    gfx_ent=scene[str(gfx_ent)]
+  width=width and width or scene.viewport.width
+  height=height and height or scene.viewport.height
+  atom_positions=geom.Vec3List([atom.pos for atom in gfx_ent.view.atoms])
+  axes=atom_positions.principal_axes
+  sorted_axes=_XYZ(gfx_ent.view, axes)
+  x_bigger_than_y=geom.Length(sorted_axes[0])>geom.Length(sorted_axes[1])
+  if x_bigger_than_y:
+    if width>height:    
+      x_axes=geom.Normalize(sorted_axes[0])
+      y_axes=geom.Normalize(sorted_axes[1])
+    else:
+      x_axes=geom.Normalize(sorted_axes[1])
+      y_axes=geom.Normalize(sorted_axes[0])
+  else:
+    if width>height:    
+      x_axes=geom.Normalize(sorted_axes[1])
+      y_axes=geom.Normalize(sorted_axes[0])
+    else:
+      x_axes=geom.Normalize(sorted_axes[0])
+      y_axes=geom.Normalize(sorted_axes[1])
+  z_axes=geom.Normalize(geom.Cross(x_axes, y_axes))
+  rotation=geom.Mat3(x_axes[0], x_axes[1], x_axes[2],
+                     y_axes[0], y_axes[1], y_axes[2],
+                     z_axes[0], z_axes[1], z_axes[2])
+  rtc=geom.Mat4(rotation)
+  
+  center=gfx_ent.center
+  aspect=float(width)/float(height)
+  factor_y=1.0/math.tan(math.radians(scene.fov))
+  factor_x=factor_y/aspect
+  z_off=geom.Length(sorted_axes[2])*0.5
+  rtc[0,3]=center[0]
+  rtc[1,3]=center[1]
+  rtc[2,3]=center[2]
+  rtc[3,0]=0
+  rtc[3,1]=0
+  rtc[3,2]=-(max(factor_x*(1+margin)*geom.Length(sorted_axes[0]), 
+                factor_y*(1+margin)*geom.Length(sorted_axes[1]))+z_off)
+  scene.SetRTC(rtc)
+
+
+class GfxNodeListAttrProxy(object):
+  def __init__(self, node_list, name):
+    self._node_list=node_list
+    self._name=name
+
+  def __iter__(self):
+    for node in self._node_list:
+      yield getattr(node, self._name)
+
+  def __call__(self, *args, **kwargs):
+    for node in self._node_list:
+      bound_method=getattr(node, self._name)
+      bound_method(*args, **kwargs)
+
+class GfxNodeListProxy(object):
+  def __init__(self, node_list):
+    self._nodes=node_list
+
+  def __getattr__(self, name):
+    if name.startswith('_'):
+      return super(GfxNodeListProxy, self).__getattr__(name)
+    return GfxNodeListAttrProxy(self._nodes, name)
+
+  def __dir__(self):
+    if len(self._nodes)==0:
+      return dir(None)
+    return dir(self._nodes[0])
+
+  def __setattr__(self, name, value):
+    if name.startswith('_'):
+      super(GfxNodeListProxy, self).__setattr__(name, value)
+    for node in self._nodes:
+      setattr(node, name, value)
+
+def _Match(scene, pattern="*"):
+  import os
+  import fnmatch
+  def _Recurse(path, node, pattern):
+    matches=[]
+    for child in node.children:
+      full_name=os.path.join(path, child.name)
+      if fnmatch.fnmatchcase(full_name, pattern):
+        matches.append(child)
+      matches.extend(_Recurse(full_name, child, pattern))
+    return matches
+  return GfxNodeListProxy(_Recurse("", Scene().root_node, pattern))
+
+SceneSingleton.Match=_Match
diff --git a/modules/gfx/pymod/color_by_def.hh b/modules/gfx/pymod/color_by_def.hh
index 1c4643acd6ec55c61df7a483d5c05a13282da574..d45bb327e87db0772e4e09f41b939cc467727ecd 100644
--- a/modules/gfx/pymod/color_by_def.hh
+++ b/modules/gfx/pymod/color_by_def.hh
@@ -22,13 +22,16 @@
 #include <ost/config.hh>
 #include <ost/gfx/gfx_object.hh>
 
+#if OST_IMG_ENABLED
+#include <ost/img/alg/stat.hh>
+#endif
+
 using namespace ost;
 using namespace ost::gfx;
 
 namespace ost_gfx {
 
-#if OST_IMG_ENABLED
-inline void color_by_01(GfxObj* go,
+inline void color_by_e0(GfxObj* go,
                 const mol::EntityView& ev, 
                 const String& prop,
                 const Gradient& g, float minv, float maxv)
@@ -36,117 +39,141 @@ inline void color_by_01(GfxObj* go,
   go->ColorBy(ev,prop,g,minv,maxv);
 }
 
-inline void color_by_02(GfxObj* go,
-                const ::img::MapHandle& mh, 
-                const String& prop,
-                const Gradient& g, float minv, float maxv)
+inline void color_by_e1(GfxObj* go,
+			const mol::EntityView& ev, 
+			const String& prop,
+			const Color& c1, const Color& c2, float minv, float maxv)
 {
-  go->ColorBy(mh,prop,g,minv,maxv);
+  Gradient g;
+  g.SetColorAt(0.0,c1);
+  g.SetColorAt(1.0,c2);
+  go->ColorBy(ev,prop,g,minv,maxv);
 }
 
-
-inline void color_by_11(GfxObj* go,
-                 const ::img::MapHandle& mh, 
-                 const String& prop,
-                 const Gradient& g)
+inline void color_by_e2(GfxObj* go,
+			const mol::EntityHandle& eh, 
+			const String& prop,
+			const Gradient& g, float minv, float maxv)
 {
-  go->ColorBy(mh,prop,g);
+  go->ColorBy(eh.CreateFullView(),prop,g,minv,maxv);
 }
 
-inline void color_by_12(GfxObj* go,
-                 const ::img::MapHandle& mh, 
-                 const String& prop,
-                 const Color& c1, const Color& c2)
+inline void color_by_e3(GfxObj* go,
+			const mol::EntityHandle& eh, 
+			const String& prop,
+			const Color& c1, const Color& c2, float minv, float maxv)
 {
-  go->ColorBy(mh,prop,c1,c2);
+  Gradient g;
+  g.SetColorAt(0.0,c1);
+  g.SetColorAt(1.0,c2);
+  go->ColorBy(eh.CreateFullView(),prop,g,minv,maxv);
 }
 
-
-inline void color_by_04(GfxObj* go,
-                const ::img::MapHandle& mh, 
-                const String& prop,
-                const Color& c1, const Color& c2, float minv, float maxv)
+inline void color_by_e4(GfxObj* go,
+			const mol::EntityView& ev, 
+			const String& prop,
+			const Gradient& g)
 {
-  go->ColorBy(mh,prop,c1,c2,minv,maxv);
+  std::pair<float,float> minmax = ev.GetMinMax(prop);
+  go->ColorBy(ev,prop,g,minmax.first, minmax.second);
 }
 
-#endif
-
-inline void color_by_03(GfxObj* go,
-                const mol::EntityView& ev, 
-                const String& prop,
-                const Color& c1, const Color& c2, float minv, float maxv)
+inline void color_by_e5(GfxObj* go,
+			const mol::EntityView& ev, 
+			const String& prop,
+			const Color& c1, const Color& c2)
 {
-  go->ColorBy(ev,prop,c1,c2,minv,maxv);
+  Gradient g;
+  g.SetColorAt(0.0,c1);
+  g.SetColorAt(1.0,c2);
+  std::pair<float,float> minmax = ev.GetMinMax(prop);
+  go->ColorBy(ev,prop,g,minmax.first, minmax.second);
 }
 
-
-
-inline void color_by_05(GfxObj* go,
-                const mol::EntityHandle& eh, 
-                const String& prop,
-                const Gradient& g, float minv, float maxv)
+inline void color_by_e6(GfxObj* go,
+			const mol::EntityHandle& eh, 
+			const String& prop,
+			const Gradient& g)
 {
-  go->ColorBy(eh,prop,g,minv,maxv);
+  color_by_e4(go,eh.CreateFullView(),prop,g);
 }
 
-inline void color_by_06(GfxObj* go,
-                const mol::EntityHandle& eh, 
-                const String& prop,
-                const Color& c1, const Color& c2, float minv, float maxv)
+inline void color_by_e7(GfxObj* go,
+			const mol::EntityHandle& eh, 
+			const String& prop,
+			const Color& c1, const Color& c2)
 {
-  go->ColorBy(eh,prop,c1,c2,minv,maxv);
+  color_by_e5(go,eh.CreateFullView(),prop,c1,c2);
 }
 
-inline void color_by_07(GfxObj* go,
-                const mol::EntityView& ev, 
-                const String& prop,
-                const Gradient& g){
-  go->ColorBy(ev,prop,g);
+#if OST_IMG_ENABLED
+inline void color_by_m0(GfxObj* go,
+			const ::img::MapHandle& mh, 
+			const String& prop,
+			const Gradient& g, float minv, float maxv)
+{
+  go->ColorBy(mh,prop,g,minv,maxv);
 }
 
-inline void color_by_08(GfxObj* go,
-                const mol::EntityView& ev, 
-                const String& prop,
-                const Color& c1, const Color& c2)
+inline void color_by_m1(GfxObj* go,
+			  const ::img::MapHandle& mh, 
+			  const String& prop,
+			  const Gradient& g)
 {
-  go->ColorBy(ev,prop,c1,c2);
+  ost::img::alg::Stat stat;
+  mh.Apply(stat);
+  float min = static_cast<float>(stat.GetMinimum());
+  float max = static_cast<float>(stat.GetMaximum());
+  std::pair<float,float> minmax = std::make_pair(min,max);
+  go->ColorBy(mh,prop,g,minmax.first, minmax.second);
 }
 
-inline void color_by_09(GfxObj* go,
-                const mol::EntityHandle& ev, 
-                const String& prop,
-                const Gradient& g)
+inline void color_by_m2(GfxObj* go,
+			const ::img::MapHandle& mh, 
+			const String& prop,
+			const Color& c1, const Color& c2)
 {
-  go->ColorBy(ev,prop,g);
+  Gradient g;
+  g.SetColorAt(0.0,c1);
+  g.SetColorAt(1.0,c2);
+  ost::img::alg::Stat stat;
+  mh.Apply(stat);
+  float min = static_cast<float>(stat.GetMinimum());
+  float max = static_cast<float>(stat.GetMaximum());
+  std::pair<float,float> minmax = std::make_pair(min,max);
+  go->ColorBy(mh,prop,g,minmax.first, minmax.second);
 }
 
-inline void color_by_10(GfxObj* go,
-                 const mol::EntityHandle& ev, 
-                 const String& prop,
-                 const Color& c1, const Color& c2)
+inline void color_by_m3(GfxObj* go,
+			const ::img::MapHandle& mh, 
+			const String& prop,
+			const Color& c1, const Color& c2, float minv, float maxv)
 {
-  go->ColorBy(ev,prop,c1,c2);
+  Gradient g;
+  g.SetColorAt(0.0,c1);
+  g.SetColorAt(1.0,c2);
+  go->ColorBy(mh,prop,g,minv, maxv);
 }
+#endif
 
 }
 
 #define COLOR_BY_DEF_STD() \
-    .def("ColorBy",ost_gfx::color_by_03)\
-    .def("ColorBy",ost_gfx::color_by_05)\
-    .def("ColorBy",ost_gfx::color_by_06)\
-    .def("ColorBy",ost_gfx::color_by_07)\
-    .def("ColorBy",ost_gfx::color_by_08)\
-    .def("ColorBy",ost_gfx::color_by_09)\
-    .def("ColorBy",ost_gfx::color_by_10)
+    .def("ColorBy",ost_gfx::color_by_e0)\
+    .def("ColorBy",ost_gfx::color_by_e1)\
+    .def("ColorBy",ost_gfx::color_by_e2)\
+    .def("ColorBy",ost_gfx::color_by_e3)\
+    .def("ColorBy",ost_gfx::color_by_e4)\
+    .def("ColorBy",ost_gfx::color_by_e5)\
+    .def("ColorBy",ost_gfx::color_by_e6)\
+    .def("ColorBy",ost_gfx::color_by_e7)
 
 #if OST_IMG_ENABLED
 #  define COLOR_BY_DEF_MAP() \
-    .def("ColorBy",ost_gfx::color_by_01)\
-    .def("ColorBy",ost_gfx::color_by_02)\
-    .def("ColorBy",ost_gfx::color_by_04)\
-    .def("ColorBy",ost_gfx::color_by_11)\
-    .def("ColorBy",ost_gfx::color_by_12)
+    .def("ColorBy",ost_gfx::color_by_m0)\
+    .def("ColorBy",ost_gfx::color_by_m1)\
+    .def("ColorBy",ost_gfx::color_by_m2)\
+    .def("ColorBy",ost_gfx::color_by_m3)
 #else
 #  define COLOR_BY_DEF_MAP()
 #endif
diff --git a/modules/gfx/pymod/export_entity.cc b/modules/gfx/pymod/export_entity.cc
index 2e5a0f13f61d33a52fdb888308f2dfff83bc6202..9092a63442554ca4a2906abdf0715a3559528734 100644
--- a/modules/gfx/pymod/export_entity.cc
+++ b/modules/gfx/pymod/export_entity.cc
@@ -92,6 +92,16 @@ void color_by_08(Entity* e,
   e->ColorBy(prop,c1,c2);
 }
 
+// temporary, see comment in gfx/entity.hh
+void detail_color_by_02(Entity* e,
+                        const String& prop, 
+                        const Gradient& gradient,
+                        float minv,float maxv)
+{
+  e->DetailColorBy(prop,gradient,minv,maxv);
+}
+
+
 void radius_by_01(Entity* e,
                   const String& prop, 
                   float rmin,float rmax,
@@ -175,8 +185,8 @@ void ent_apply_61(Entity* e, MapHandleColorOp& mhco, bool store){
 void ent_apply_62(Entity* e, MapHandleColorOp& mhco){
   e->Apply(mhco);
 }
-#endif //OST_IMG_ENABLED
 
+#endif //OST_IMG_ENABLED
 
 RenderOptionsPtr ent_sline_opts(Entity* ent)
 {
@@ -214,17 +224,39 @@ RenderOptionsPtr ent_cpk_opts(Entity* ent)
   return ent->GetOptions(RenderMode::CPK);
 }
 
+void set_query1(Entity* e, const mol::Query& q)
+{
+  e->SetQuery(q);
+}
+
+void set_query2(Entity* e, const std::string& q)
+{
+  e->SetQuery(mol::Query(q));
+}
+
 RenderOptionsPtr ent_ltrace_opts(Entity* ent)
 {
   return ent->GetOptions(RenderMode::LINE_TRACE);
 }
 
+void set_selection(Entity* ent, object sel)
+{
+  try {
+    String sel_string=extract<String>(sel);
+    ent->SetSelection(ent->GetView().Select(sel_string));
+  } catch (error_already_set& e) {
+    PyErr_Clear();
+    mol::EntityView view=extract<mol::EntityView>(sel);
+    ent->SetSelection(view);
+  }
+}
+
 }
 
 void export_Entity()
 {
-  class_<Entity, boost::shared_ptr<Entity>, bases<GfxObj>, boost::noncopyable>("Entity", init<const String&, const mol:: EntityHandle&, optional<const mol:: Query&> >())
-    .def(init<const String&, RenderMode::Type, const mol::EntityHandle&, optional<const mol::Query&> >())
+  class_<Entity, boost::shared_ptr<Entity>, bases<GfxObj>, boost::noncopyable>("Entity", init<const String&, const mol:: EntityHandle&, optional<const mol:: Query&, mol::QueryFlags> >())
+    .def(init<const String&, RenderMode::Type, const mol::EntityHandle&, optional<const mol::Query&, mol::QueryFlags> >())
     .def(init<const String&, const mol::EntityView&>())
     .def(init<const String&, RenderMode::Type, const mol::EntityView&>())
     .def("SetColor",ent_set_color1)
@@ -240,8 +272,11 @@ void export_Entity()
     .def("SetSelection",&Entity::SetSelection)
     .def("GetSelection",&Entity::GetSelection)    
     .add_property("selection", &Entity::GetSelection, 
-                  &Entity::SetSelection)
+                  &set_selection)
     .def("GetView", &Entity::GetView)
+    .def("UpdateView", &Entity::UpdateView)
+    .def("SetQuery", set_query1)
+    .def("SetQuery", set_query2)
     .def("GetRenderModeName", &Entity::GetRenderModeName)
     .def("GetNotEmptyRenderModes", &Entity::GetNotEmptyRenderModes)
     .def("SetRenderMode", set_rm1, arg("keep")=false)
@@ -258,6 +293,7 @@ void export_Entity()
     .def("ColorBy", color_by_06)
     .def("ColorBy", color_by_07)
     .def("ColorBy", color_by_08)
+    .def("DetailColorBy", detail_color_by_02)
     COLOR_BY_DEF()
     .def("RadiusBy", radius_by_01)
     .def("RadiusBy", radius_by_02)
@@ -295,6 +331,7 @@ void export_Entity()
     .def("Apply",&ent_apply_61)
     .def("Apply",&ent_apply_62)
 #endif //OST_IMG_ENABLED
+    .add_property("seq_hack",&Entity::GetSeqHack,&Entity::SetSeqHack)
   ;
   //register_ptr_to_python<EntityP>();
   
diff --git a/modules/gfx/pymod/export_gfx_node.cc b/modules/gfx/pymod/export_gfx_node.cc
index b7791e8e67e51232d3988876d2b44d6a697fb179..3bab8f34c7e3de34bfdd2377e7bf7f699c25ef96 100644
--- a/modules/gfx/pymod/export_gfx_node.cc
+++ b/modules/gfx/pymod/export_gfx_node.cc
@@ -17,12 +17,20 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 #include <boost/python.hpp>
+#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
+
 using namespace boost::python;
 
+#include <ost/export_helper/vector.hh>
 #include <ost/gfx/gfx_node.hh>
+
+
 using namespace ost;
 using namespace ost::gfx;
 
+
+const GfxNodeVector& (GfxNode::*get_children)() const=&GfxNode::GetChildren;
+
 void export_GfxNode()
 {
   void (GfxNode::* node_add1)(GfxObjP) = &GfxNode::Add;
@@ -31,7 +39,12 @@ void export_GfxNode()
   void (GfxNode::* node_rem2)(GfxNodeP) = &GfxNode::Remove;
   void (GfxNode::* node_rem3)(const String&) = &GfxNode::Remove;
 
-  class_<GfxNode, boost::noncopyable>("GfxNode",no_init)
+  class_<GfxNodeVector>("GfxNodeList", init<>())
+    .def(vector_indexing_suite<GfxNodeVector, true>())
+    .def(ost::VectorAdditions<GfxNodeVector>())
+  ;
+  class_<GfxNode, GfxNodeP, 
+         boost::noncopyable>("GfxNode", init<const String&>())
     .def("GetName",&GfxNode::GetName)
     .def("Hide",&GfxNode::Hide)
     .def("Show",&GfxNode::Show)
@@ -42,6 +55,8 @@ void export_GfxNode()
     .add_property("name", &GfxNode::GetName)    
     .def("Remove",node_rem2)
     .def("Remove",node_rem3)
+    .add_property("parent", &GfxNode::GetParent)
+    .add_property("children", make_function(get_children, 
+                                            return_value_policy<copy_const_reference>()))
     ;
-  register_ptr_to_python<GfxNodeP>();
 }
diff --git a/modules/gfx/pymod/export_gfx_obj.cc b/modules/gfx/pymod/export_gfx_obj.cc
index 18e3454eead7e34dcfc09493cfcf87dc219a74ac..565ef921a3070b123d2b55035a702436bf472164 100644
--- a/modules/gfx/pymod/export_gfx_obj.cc
+++ b/modules/gfx/pymod/export_gfx_obj.cc
@@ -25,61 +25,90 @@ using namespace ost::gfx;
 
 #include "color_by_def.hh"
 
+namespace {
+  // convenience for python
+  void set_mat_amb2(GfxObjBase* b, float c) {b->SetMatAmb(Color(c,c,c,1.0));}
+  void set_mat_diff2(GfxObjBase* b, float c) {b->SetMatDiff(Color(c,c,c,1.0));}
+  void set_mat_spec2(GfxObjBase* b, float c) {b->SetMatSpec(Color(c,c,c,1.0));}
+  void set_mat_emm2(GfxObjBase* b, float c) {b->SetMatEmm(Color(c,c,c,1.0));}
+  void set_mat1(GfxObjBase* b, float a, float d, float s, float p)
+  {
+    set_mat_amb2(b,a);
+    set_mat_diff2(b,d);
+    set_mat_spec2(b,s);
+    b->SetMatShin(p);
+    set_mat_emm2(b,0.0);
+  }
+  void set_mat2(GfxObjBase* b, Color a, Color d, Color s, float p)
+  {
+    b->SetMatAmb(a);
+    b->SetMatDiff(d);
+    b->SetMatSpec(s);
+    b->SetMatShin(p);
+    set_mat_emm2(b,0.0);
+  }
+
+  void set_outline(GfxObjBase* b, bool f)
+  {
+    LOG_INFO("Outline(bool) is deprecated, use SetOutline(bool) instead");
+    b->SetOutline(f);
+  }
+  void set_aalines(GfxObjBase* b, bool f)
+  {
+    LOG_INFO("AALines(bool) is deprecated, use SetAALines(bool) instead");
+    b->SetAALines(f);
+  }
+}
+
 void export_GfxObj()
 {
-  void (GfxObj::* set_mat_amb1)(const Color&) = &GfxObj::SetMatAmb;
-  void (GfxObj::* set_mat_amb2)(float) = &GfxObj::SetMatAmb;
-  void (GfxObj::* set_mat_diff1)(const Color&) = &GfxObj::SetMatDiff;
-  void (GfxObj::* set_mat_diff2)(float) = &GfxObj::SetMatDiff;
-  void (GfxObj::* set_mat_spec1)(const Color&) = &GfxObj::SetMatSpec;
-  void (GfxObj::* set_mat_spec2)(float) = &GfxObj::SetMatSpec;
-  void (GfxObj::* set_mat_emm1)(const Color&) = &GfxObj::SetMatEmm;
-  void (GfxObj::* set_mat_emm2)(float) = &GfxObj::SetMatEmm;
-  void (GfxObj::* set_mat1)(const Color&,const Color&, 
-                            const Color&, float) = &GfxObj::SetMat;
-  void (GfxObj::* set_mat2)(float,float,float,float) = &GfxObj::SetMat;
-
-  class_<GfxObj, bases<GfxNode>, boost::noncopyable>("GfxObj",no_init)
-    .def("GetCenter",&GfxObj::GetCenter)
-    .def("SetRenderMode", &GfxObj::SetRenderMode)
-    .def("GetRenderMode", &GfxObj::GetRenderMode)
-    .def("SetLineWidth", &GfxObj::SetLineWidth)
-    .def("GetLineWidth", &GfxObj::GetLineWidth)
-    .def("SetLineHalo",&GfxObj::SetLineHalo)
-    .def("GetLineHalo",&GfxObj::GetLineHalo)
-    .def("SetSphereDetail",&GfxObj::SetSphereDetail)
-    .def("SetArcDetail",&GfxObj::SetArcDetail)
-    .def("SetSplineDetail",&GfxObj::SetSplineDetail)
-    .def("SetMatAmb",set_mat_amb1)
+  class_<GfxObjBase, boost::shared_ptr<GfxObjBase>, bases<GfxNode>, boost::noncopyable>("GfxObjBase",no_init)
+    .def("SetMatAmb",&GfxObjBase::SetMatAmb)
     .def("SetMatAmb",set_mat_amb2)
-    .def("SetMatDiff",set_mat_diff1)
+    .def("SetMatDiff",&GfxObjBase::SetMatDiff)
     .def("SetMatDiff",set_mat_diff2)
-    .def("GetTF", &GfxObj::GetTF, return_value_policy<copy_const_reference>())
-    .def("SetTF", &GfxObj::SetTF)
-    .def("SetMatSpec",set_mat_spec1)
+    .def("SetMatSpec",&GfxObjBase::SetMatSpec)
     .def("SetMatSpec",set_mat_spec2)
-    .def("SetMatEmm",set_mat_emm1)
+    .def("SetMatEmm",&GfxObjBase::SetMatEmm)
     .def("SetMatEmm",set_mat_emm2)
-    .def("SetMatShin",&GfxObj::SetMatShin)
+    .def("SetMatShin",&GfxObjBase::SetMatShin)
     .def("SetMat",set_mat1)
     .def("SetMat",set_mat2)
-    .def("SetPolyMode",&GfxObj::SetPolyMode)
-    .def("SetAALines",&GfxObj::SetAALines)
-    .def("SetOpacity",&GfxObj::SetOpacity)
-    .def("GetOpacity",&GfxObj::GetOpacity)
+    .def("ContextSwitch", &GfxObjBase::ContextSwitch)
+    .def("SetRenderMode", &GfxObjBase::SetRenderMode)
+    .def("GetRenderMode", &GfxObjBase::GetRenderMode)
+    .def("GetCenter",&GfxObjBase::GetCenter)
+    .def("SetLineWidth", &GfxObjBase::SetLineWidth)
+    .def("SetPolyMode",&GfxObjBase::SetPolyMode)
+    .def("AALines",set_aalines)
+    .def("SetAALines",&GfxObjBase::SetAALines)
+    .def("SetLineHalo",&GfxObjBase::SetLineHalo)
+    .def("Outline",set_outline)
+    .def("SetOutline",&GfxObjBase::SetOutline)
+    .def("SetOutlineMode",&GfxObjBase::SetOutlineMode)
+    .def("SetOutlineWidth",&GfxObjBase::SetOutlineWidth)
+    .def("SetOutlineExpandFactor",&GfxObjBase::SetOutlineExpandFactor)
+    .def("SetOutlineExpandColor",&GfxObjBase::SetOutlineExpandColor)
+    .def("SetOpacity",&GfxObjBase::SetOpacity)
+    .def("GetOpacity",&GfxObjBase::GetOpacity)
+    .add_property("center", &GfxObjBase::GetCenter)
+    COLOR_BY_DEF()
+   ;
+  //register_ptr_to_python<GfxObjBaseP>();
+
+  class_<GfxObj, boost::shared_ptr<GfxObj>, bases<GfxObjBase>, boost::noncopyable>("GfxObj",no_init)
+    .def("GetTF", &GfxObj::GetTF, return_value_policy<copy_const_reference>())
+    .def("SetTF", &GfxObj::SetTF)
     .def("FlagRebuild",&GfxObj::FlagRebuild)
     .def("FlagRefresh",&GfxObj::FlagRefresh)
     .def("SetNormalSmoothFactor",&GfxObj::SetNormalSmoothFactor)
     .def("GetNormalSmoothFactor",&GfxObj::GetNormalSmoothFactor)
-    .def("SetOutlineMode",&GfxObj::SetOutlineMode)
-    .def("SetOutlineExpandFactor",&GfxObj::SetOutlineExpandFactor)
-    .def("SetOutlineExpandColor",&GfxObj::SetOutlineExpandColor)
     .def("SmoothVertices",&GfxObj::SmoothVertices)
-    .def("AmbientOcclusion",&GfxObj::AmbientOcclusion)
     .def("Debug",&GfxObj::Debug)
-    .add_property("center", &GfxObj::GetCenter)
-    COLOR_BY_DEF()
+    .def("GetAALines",&GfxObj::GetAALines)
+    .def("GetLineWidth",&GfxObj::GetLineWidth)
+    .def("GetLineHalo",&GfxObj::GetLineHalo)
     ;
-  register_ptr_to_python<GfxObjP>();
+  //register_ptr_to_python<GfxObjP>();
 
 }
diff --git a/modules/gfx/pymod/export_render_options.cc b/modules/gfx/pymod/export_render_options.cc
index 712da0edf269c8030dc4eff83f475b211dbf224b..54830abc9edff349d773b538d2871691ef345934 100644
--- a/modules/gfx/pymod/export_render_options.cc
+++ b/modules/gfx/pymod/export_render_options.cc
@@ -44,22 +44,24 @@ void export_RenderOptions()
   class_<LineRenderOptions, boost::shared_ptr<LineRenderOptions>, bases<RenderOptions>, boost::noncopyable>("LineRenderOptions", no_init)
     .def("SetLineWidth",&LineRenderOptions::SetLineWidth)
     .def("GetLineWidth",&LineRenderOptions::GetLineWidth)
+    .add_property("line_width", &LineRenderOptions::GetLineWidth, 
+                  &LineRenderOptions::SetLineWidth)    
     .def("SetAALines",&LineRenderOptions::SetAALines)
     .def("GetAALines",&LineRenderOptions::GetAALines)
     .add_property("aa_lines", &LineRenderOptions::GetAALines, 
                   &LineRenderOptions::SetAALines)
-    .add_property("line_width", &LineRenderOptions::GetLineWidth, 
-                  &LineRenderOptions::SetLineWidth)    
   ;
 
   class_<SimpleRenderOptions, boost::shared_ptr<SimpleRenderOptions>, bases<LineRenderOptions>, boost::noncopyable>("SimpleRenderOptions")
     .def(init<const SimpleRenderOptions&>())
-    .def("SetBondOrderFlag", &SimpleRenderOptions::SetBondOrderFlag)
-    .def("SetBondOrderDistance", &SimpleRenderOptions::SetBondOrderDistance)
     .def("GetBondOrderFlag", &SimpleRenderOptions::GetBondOrderFlag)
-    .def("GetBondOrderDistance", &SimpleRenderOptions::GetBondOrderDistance)
+    .def("SetBondOrderFlag", &SimpleRenderOptions::SetBondOrderFlag) 
     .add_property("draw_bond_order", &SimpleRenderOptions::GetBondOrderFlag, 
                   &SimpleRenderOptions::SetBondOrderFlag)
+    .add_property("bond_order_flag", &SimpleRenderOptions::GetBondOrderFlag, 
+                  &SimpleRenderOptions::SetBondOrderFlag)
+    .def("GetBondOrderDistance", &SimpleRenderOptions::GetBondOrderDistance)
+    .def("SetBondOrderDistance", &SimpleRenderOptions::SetBondOrderDistance)
     .add_property("bond_order_distance", &SimpleRenderOptions::GetBondOrderDistance, 
                   &SimpleRenderOptions::SetBondOrderDistance)    
   ;
@@ -72,35 +74,40 @@ void export_RenderOptions()
     .def(init<const SlineRenderOptions&>())
     .def("SetSplineDetail", &SlineRenderOptions::SetSplineDetail)
     .def("GetSplineDetail", &SlineRenderOptions::GetSplineDetail)
+    .add_property("spline_detail",&SlineRenderOptions::GetSplineDetail,&SlineRenderOptions::SetSplineDetail)
   ;
 
   class_<CPKRenderOptions, boost::shared_ptr<CPKRenderOptions>, bases<RenderOptions>, boost::noncopyable>("CPKRenderOptions")
     .def(init<const CPKRenderOptions&>())
     .def("SetSphereDetail", &CPKRenderOptions::SetSphereDetail)
     .def("GetSphereDetail", &CPKRenderOptions::GetSphereDetail)
-    .def("SetCPKMode", &CPKRenderOptions::SetCPKMode)
-    .def("GetCPKMode", &CPKRenderOptions::GetCPKMode)
-    .add_property("cpk_mode", &CPKRenderOptions::GetCPKMode, 
-                  &CPKRenderOptions::SetCPKMode)
     .add_property("sphere_detail", &CPKRenderOptions::GetSphereDetail, 
                   &CPKRenderOptions::SetSphereDetail)
+    .def("SetSphereMode", &CPKRenderOptions::SetSphereMode)
+    .def("GetSphereMode", &CPKRenderOptions::GetSphereMode)
+    .add_property("sphere_mode", &CPKRenderOptions::GetSphereMode, 
+                  &CPKRenderOptions::SetSphereMode)
+    .def("SetCPKMode", &CPKRenderOptions::SetSphereMode)
+    .def("GetCPKMode", &CPKRenderOptions::GetSphereMode)
+    .add_property("cpk_mode", &CPKRenderOptions::GetSphereMode, 
+                  &CPKRenderOptions::SetSphereMode)
   ;
 
   class_<CustomRenderOptions, boost::shared_ptr<CustomRenderOptions>, bases<RenderOptions>, boost::noncopyable>("CustomRenderOptions")
     .def(init<const CustomRenderOptions&>())
     .def("SetSphereDetail", &CustomRenderOptions::SetSphereDetail)
     .def("GetSphereDetail", &CustomRenderOptions::GetSphereDetail)
+    .add_property("sphere_detail", &CustomRenderOptions::GetSphereDetail, &CustomRenderOptions::SetSphereDetail)
     .def("SetArcDetail", &CustomRenderOptions::SetArcDetail)
     .def("GetArcDetail", &CustomRenderOptions::GetArcDetail)
+    .add_property("arc_detail", &CustomRenderOptions::GetArcDetail, 
+                  &CustomRenderOptions::SetArcDetail)
     .def("SetSphereRad", &CustomRenderOptions::SetSphereRad)
     .def("GetSphereRad", &CustomRenderOptions::GetSphereRad)
+    .add_property("sphere_rad", &CustomRenderOptions::GetSphereRad, &CustomRenderOptions::SetSphereRad)    
     .def("SetBondRad", &CustomRenderOptions::SetBondRad)
     .def("GetBondRad", &CustomRenderOptions::GetBondRad)
-    .add_property("sphere_detail", &CustomRenderOptions::GetSphereDetail, &CustomRenderOptions::SetSphereDetail)
     .add_property("bond_rad", &CustomRenderOptions::GetBondRad, &CustomRenderOptions::SetBondRad)
-    .add_property("sphere_rad", &CustomRenderOptions::GetSphereRad, &CustomRenderOptions::SetSphereRad)    
-    .add_property("arc_detail", &CustomRenderOptions::GetArcDetail, 
-                  &CustomRenderOptions::SetArcDetail)
   ;
 
   class_<CartoonRenderOptions, boost::shared_ptr<CartoonRenderOptions>, bases<RenderOptions>, boost::noncopyable>("CartoonRenderOptions")
@@ -108,51 +115,92 @@ void export_RenderOptions()
     .def(init<optional<bool> >())
     .def("SetSplineDetail", &CartoonRenderOptions::SetSplineDetail)
     .def("GetSplineDetail", &CartoonRenderOptions::GetSplineDetail)
+    .add_property("spline_detail", &CartoonRenderOptions::GetSplineDetail, 
+                  &CartoonRenderOptions::SetSplineDetail)
     .def("SetPolyMode", &CartoonRenderOptions::SetPolyMode)
     .def("GetPolyMode", &CartoonRenderOptions::GetPolyMode)
+    .add_property("poly_mode", &CartoonRenderOptions::GetPolyMode,&CartoonRenderOptions::SetPolyMode)
     .def("SetArcDetail", &CartoonRenderOptions::SetArcDetail)
     .def("GetArcDetail", &CartoonRenderOptions::GetArcDetail)
+    .add_property("arc_detail", &CartoonRenderOptions::GetArcDetail, 
+                  &CartoonRenderOptions::SetArcDetail)
     .def("SetNormalSmoothFactor", &CartoonRenderOptions::SetNormalSmoothFactor)
     .def("GetNormalSmoothFactor", &CartoonRenderOptions::GetNormalSmoothFactor)
+    .add_property("normal_smooth_factor",&CartoonRenderOptions::GetNormalSmoothFactor,
+                  &CartoonRenderOptions::SetNormalSmoothFactor)
     .def("SetTubeRadius", &CartoonRenderOptions::SetTubeRadius)
     .def("GetTubeRadius", &CartoonRenderOptions::GetTubeRadius)
+    .add_property("tube_radius",&CartoonRenderOptions::GetTubeRadius,
+                  &CartoonRenderOptions::SetTubeRadius)
     .def("SetTubeRatio", &CartoonRenderOptions::SetTubeRatio)
     .def("GetTubeRatio", &CartoonRenderOptions::GetTubeRatio)
+    .add_property("tube_ratio",&CartoonRenderOptions::GetTubeRatio,
+                  &CartoonRenderOptions::SetTubeRatio)
     .def("SetTubeProfileType", &CartoonRenderOptions::SetTubeProfileType)
     .def("GetTubeProfileType", &CartoonRenderOptions::GetTubeProfileType)
+    .add_property("tube_profile_type",&CartoonRenderOptions::GetTubeProfileType,
+                  &CartoonRenderOptions::SetTubeProfileType)
     .def("SetHelixWidth", &CartoonRenderOptions::SetHelixWidth)
     .def("GetHelixWidth", &CartoonRenderOptions::GetHelixWidth)
+    .add_property("helix_width",&CartoonRenderOptions::GetHelixWidth,
+                  &CartoonRenderOptions::SetHelixWidth)
     .def("SetHelixThickness", &CartoonRenderOptions::SetHelixThickness)
     .def("GetHelixThickness", &CartoonRenderOptions::GetHelixThickness)
+    .add_property("helix_thickness",&CartoonRenderOptions::GetHelixThickness,
+                  &CartoonRenderOptions::SetHelixThickness)
     .def("SetHelixEcc", &CartoonRenderOptions::SetHelixEcc)
     .def("GetHelixEcc", &CartoonRenderOptions::GetHelixEcc)
+    .add_property("helix_ecc",&CartoonRenderOptions::GetHelixEcc,
+                  &CartoonRenderOptions::SetHelixEcc)
     .def("SetHelixProfileType", &CartoonRenderOptions::SetHelixProfileType)
     .def("GetHelixProfileType", &CartoonRenderOptions::GetHelixProfileType)
+    .add_property("helix_profile_type",&CartoonRenderOptions::GetHelixProfileType,
+                  &CartoonRenderOptions::SetHelixProfileType)
+    .def("SetHelixMode", &CartoonRenderOptions::SetHelixMode)
+    .def("GetHelixMode", &CartoonRenderOptions::GetHelixMode)
+    .add_property("helix_mode",&CartoonRenderOptions::GetHelixMode,
+                  &CartoonRenderOptions::SetHelixMode)
     .def("SetStrandWidth", &CartoonRenderOptions::SetStrandWidth)
     .def("GetStrandWidth", &CartoonRenderOptions::GetStrandWidth)
+    .add_property("strand_width",&CartoonRenderOptions::GetStrandWidth,
+                  &CartoonRenderOptions::SetStrandWidth)
     .def("SetStrandThickness", &CartoonRenderOptions::SetStrandThickness)
     .def("GetStrandThickness", &CartoonRenderOptions::GetStrandThickness)
+    .add_property("strand_thickness",&CartoonRenderOptions::GetStrandThickness,
+                  &CartoonRenderOptions::SetStrandThickness)
     .def("SetStrandEcc", &CartoonRenderOptions::SetStrandEcc)
     .def("GetStrandEcc", &CartoonRenderOptions::GetStrandEcc)
+    .add_property("strand_ecc",&CartoonRenderOptions::GetStrandEcc,
+                  &CartoonRenderOptions::SetStrandEcc)
     .def("SetStrandProfileType", &CartoonRenderOptions::SetStrandProfileType)
     .def("GetStrandProfileType", &CartoonRenderOptions::GetStrandProfileType)
+    .add_property("strand_profile_type",&CartoonRenderOptions::GetStrandProfileType,
+                  &CartoonRenderOptions::SetStrandProfileType)
+    .def("SetStrandMode", &CartoonRenderOptions::SetStrandMode)
+    .def("GetStrandMode", &CartoonRenderOptions::GetStrandMode)
+    .add_property("strand_mode",&CartoonRenderOptions::GetStrandMode,
+                  &CartoonRenderOptions::SetStrandMode)
+    .def("SetColorBlendMode", &CartoonRenderOptions::SetColorBlendMode)
+    .def("GetColorBlendMode", &CartoonRenderOptions::GetColorBlendMode)
+    .add_property("color_blend_mode",&CartoonRenderOptions::GetColorBlendMode,
+                  &CartoonRenderOptions::SetColorBlendMode)
   ;
   
   class_<TraceRenderOptions, boost::shared_ptr<TraceRenderOptions>, bases<RenderOptions>, boost::noncopyable>("TraceRenderOptions")
     .def(init<const TraceRenderOptions&>())
     .def("SetArcDetail", &TraceRenderOptions::SetArcDetail)
     .def("GetArcDetail", &TraceRenderOptions::GetArcDetail)
+    .add_property("arc_detail", &TraceRenderOptions::GetArcDetail, 
+                  &TraceRenderOptions::SetArcDetail)
     .def("SetNormalSmoothFactor", &TraceRenderOptions::SetNormalSmoothFactor)
     .def("GetNormalSmoothFactor", &TraceRenderOptions::GetNormalSmoothFactor)
+    .add_property("normal_smooth_factor", 
+                  &TraceRenderOptions::GetNormalSmoothFactor, 
+                  &TraceRenderOptions::SetNormalSmoothFactor)    
     .def("SetTubeRadius", &TraceRenderOptions::SetTubeRadius)
     .def("GetTubeRadius", &TraceRenderOptions::GetTubeRadius)
     .add_property("tube_radius", &TraceRenderOptions::GetTubeRadius, 
                   &TraceRenderOptions::SetTubeRadius)
-    .add_property("arc_detail", &TraceRenderOptions::GetArcDetail, 
-                  &TraceRenderOptions::SetArcDetail)
-    .add_property("normal_smooth_factor", 
-                  &TraceRenderOptions::GetNormalSmoothFactor, 
-                  &TraceRenderOptions::SetNormalSmoothFactor)    
   ;
 }
 
diff --git a/modules/gfx/pymod/export_scene.cc b/modules/gfx/pymod/export_scene.cc
index fab0931f04baebbc357a50458f875d02844be74a..bf590ea04f2734e404ca6d63ff1deb496adccbde 100644
--- a/modules/gfx/pymod/export_scene.cc
+++ b/modules/gfx/pymod/export_scene.cc
@@ -33,7 +33,6 @@ BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(scene_autoslab_overloads,
 BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(scene_export_pov_overloads,
                                        Scene::ExportPov, 1,2)
 void (Scene::*apply)(const InputEvent&, bool)=&Scene::Apply;
-namespace {
 
 Scene* get_scene()
 {
@@ -49,16 +48,13 @@ GfxObjP scene_getitem(Scene* scene, const String& item)
   return scene->operator[](item);
 }
 
-}
+} // anon ns
 
-}
 
 void export_Scene()
 {
   def("Scene",get_scene,return_value_policy<reference_existing_object>());
 
-  def("set_offscreen_mode",&Scene::SetOffscreenMode);
-  
   // will be removed...
   def("PickAtom", &pick_atom);
 
@@ -71,69 +67,123 @@ void export_Scene()
   void (Scene::*remove2)(const String&) = &Scene::Remove;
   void (Scene::*center_on1)(const String&) = &Scene::CenterOn;
   void (Scene::*center_on2)(const GfxObjP&) = &Scene::CenterOn;
-
+  
+  class_<Viewport>("Viewport", init<>())
+    .def_readwrite("x", &Viewport::x)
+    .def_readwrite("y", &Viewport::y)
+    .def_readwrite("width", &Viewport::width)
+    .def_readwrite("height", &Viewport::height)
+  ;
+  
   class_<Scene, boost::noncopyable>("SceneSingleton",no_init)
     .def("Add", &Scene::Add, 
          scene_add_overloads())
     .def("Autoslab", &Scene::Autoslab, 
          scene_autoslab_overloads())
     .def("AutoAutoslab",&Scene::AutoAutoslab)
+    .def("GetAutoAutoslab",&Scene::GetAutoAutoslab)
     .def("AutoslabMax",&Scene::AutoslabMax)
     .def("Remove", remove1)
     .def("Remove", remove2)
+    .add_property("viewport", &Scene::GetViewport)
     .def("RequestRedraw", &Scene::RequestRedraw)
     .def("SetCenter",&Scene::SetCenter)
     .def("GetCenter",&Scene::GetCenter)
+    .add_property("center", &Scene::GetCenter, &Scene::SetCenter)
     .def("CenterOn",center_on1)
     .def("CenterOn",center_on2)
     .def("UnProject",  &Scene::UnProject, arg("ignore_vp")=false)
+    .def("Project",  &Scene::Project, arg("ignore_vp")=false)
     .def("InitGL", &Scene::InitGL)
     .def("RenderGL", &Scene::RenderGL)
     .def("Resize", &Scene::Resize)
     .def("HasNode", &Scene::HasNode)
+    .def("GetBackground", &Scene::GetBackground)
     .def("SetBackground", &Scene::SetBackground)
-    .add_property("transform", &Scene::GetTransform, &Scene::SetTransform)
-    .add_property("fov", &Scene::GetFOV, &Scene::SetFOV)
-    .add_property("center", &Scene::GetCenter, &Scene::SetCenter)
+    .add_property("bg",
+                  &Scene::GetBackground, 
+                  &Scene::SetBackground)
+    .def("SetNear",&Scene::SetNear)
+    .def("GetNear",&Scene::GetNear)
     .add_property("near", &Scene::GetNear, &Scene::SetNear)
+    .def("SetFar",&Scene::SetFar)
+    .def("GetFar",&Scene::GetFar)
     .add_property("far", &Scene::GetFar, &Scene::SetFar)
     .def("SetNearFar",&Scene::SetNearFar)
     .def("SetFog",&Scene::SetFog)
+    .def("GetFog",&Scene::GetFog)
+    .add_property("fog", &Scene::GetFog, &Scene::SetFog)
     .def("SetFogColor",&Scene::SetFogColor)
-    .add_property("fog_near_offset", &Scene::GetFogNearOffset, 
-                  &Scene::SetFogNearOffset)
-    .add_property("fog_far_offset", &Scene::GetFogFarOffset, 
-                  &Scene::SetFogFarOffset)
+    .def("GetFogColor",&Scene::GetFogColor)
+    .add_property("fogcol", &Scene::GetFogColor, &Scene::SetFogColor)
     .def("SetFOV",&Scene::SetFOV)
     .def("GetFOV",&Scene::GetFOV)
+    .add_property("fov", &Scene::GetFOV, &Scene::SetFOV)
     .def("SetFogOffsets",&Scene::SetFogOffsets)
-    .def("Stereo",&Scene::Stereo)
-    .def("SetStereoInverted",&Scene::SetStereoInverted)
-    .def("Apply", apply)
-    .def("SetStereoEye",&Scene::SetStereoEye)
+    .add_property("fogno",
+                  &Scene::GetFogNearOffset, 
+                  &Scene::SetFogNearOffset)
+    .add_property("fogfo",
+                  &Scene::GetFogFarOffset, 
+                  &Scene::SetFogFarOffset)
+    .def("GetRTC",&Scene::GetRTC)
+    .def("SetRTC",&Scene::SetRTC)
+    .add_property("rtc",&Scene::GetRTC,&Scene::SetRTC)
+    .def("GetTransform",&Scene::GetTransform)
+    .def("SetTransform",&Scene::SetTransform)
+    .add_property("transform", &Scene::GetTransform, &Scene::SetTransform)
+    .def("SetSelectionMode",&Scene::SetSelectionMode)
+    .def("GetSelectionMode",&Scene::GetSelectionMode)
+    .add_property("smode",
+                 &Scene::GetSelectionMode,
+                 &Scene::SetSelectionMode)
+    .def("SetStereoMode",&Scene::SetStereoMode)
+    .def("GetStereoMode",&Scene::GetStereoMode)
+    .add_property("stereo_mode",&Scene::GetStereoMode,&Scene::SetStereoMode)
+    .def("SetStereoFlip",&Scene::SetStereoFlip)
+    .def("GetStereoFlip",&Scene::GetStereoFlip)
+    .add_property("stereo_flip",&Scene::GetStereoFlip,&Scene::SetStereoFlip)
+    .def("SetStereoView",&Scene::SetStereoView)
+    .def("GetStereoView",&Scene::GetStereoView)
+    .add_property("stereo_view",&Scene::GetStereoView,&Scene::SetStereoView)
+    .def("SetStereoIOD",&Scene::SetStereoIOD)
+    .def("GetStereoIOD",&Scene::GetStereoIOD)
+    .add_property("stereo_iod",&Scene::GetStereoIOD,&Scene::SetStereoIOD)
+    .def("SetStereoDistance",&Scene::SetStereoDistance)
+    .def("GetStereoDistance",&Scene::GetStereoDistance)
+    .add_property("stereo_distance",&Scene::GetStereoDistance,&Scene::SetStereoDistance)
+    .def("SetStereoAlg",&Scene::SetStereoAlg)
+    .def("GetStereoAlg",&Scene::GetStereoAlg)
+    .add_property("stereo_alg",&Scene::GetStereoAlg,&Scene::SetStereoAlg)
     .def("SetLightDir",&Scene::SetLightDir)
     .def("SetLightProp",set_light_prop1)
     .def("SetLightProp",set_light_prop2)
+    .def("Apply", apply)
     .def("Export",export1, arg("transparent")=true)
     .def("Export",export2, arg("transparent")=true)
     .def("ExportPov",&Scene::ExportPov,
          scene_export_pov_overloads())
-    .def("GetRTC",&Scene::GetRTC)
-    .def("SetRTC",&Scene::SetRTC)
-    .def("GetTransform",&Scene::GetTransform)
-    .def("SetTransform",&Scene::SetTransform)
     .def("PushView",&Scene::PushView)
     .def("PopView",&Scene::PopView)
-    .def("SetSelectionMode",&Scene::SetSelectionMode)
-    .def("GetSelectionMode",&Scene::GetSelectionMode)
     .def("SetBlur",&Scene::SetBlur)
     .def("BlurSnapshot",&Scene::BlurSnapshot)
     .def("RemoveAll", &Scene::RemoveAll)
     .def("SetShadow",&Scene::SetShadow)
     .def("SetShadowQuality",&Scene::SetShadowQuality)
+    .def("SetShadowWeight",&Scene::SetShadowWeight)
+    .def("SetDepthDarkening",&Scene::SetDepthDarkening)
+    .def("SetDepthDarkeningWeight",&Scene::SetDepthDarkeningWeight)
+    .def("SetAmbientOcclusion",&Scene::SetAmbientOcclusion)
+    .def("SetAmbientOcclusionWeight",&Scene::SetAmbientOcclusionWeight)
+    .def("SetAmbientOcclusionMode",&Scene::SetAmbientOcclusionMode)
+    .def("SetAmbientOcclusionQuality",&Scene::SetAmbientOcclusionQuality)
     .def("AttachObserver",&Scene::AttachObserver)
-    .add_property("selection_mode", &Scene::GetSelectionMode,
-                   &Scene::SetSelectionMode)
+    .def("StartOffscreenMode",&Scene::StartOffscreenMode)
+    .def("StopOffscreenMode",&Scene::StopOffscreenMode)
+    .def("SetShadingMode",&Scene::SetShadingMode)
+    .def("SetBeacon",&Scene::SetBeacon)
+    .add_property("root_node", &Scene::GetRootNode)
+    .def("SetBeaconOff",&Scene::SetBeaconOff)
     .def("__getitem__",scene_getitem)
   ;
 }
diff --git a/modules/gfx/pymod/export_surface.cc b/modules/gfx/pymod/export_surface.cc
index 4a4ebc88287f4ea3521a47f998ee9fbeb9b6b266..9a589d077148396f5c93c090ead481cbca2d5f08 100644
--- a/modules/gfx/pymod/export_surface.cc
+++ b/modules/gfx/pymod/export_surface.cc
@@ -122,4 +122,5 @@ void export_Surface()
     .def("CleanColorOps", &Surface::CleanColorOps)
     .def("ReapplyColorOps", &Surface::ReapplyColorOps)
     ;
+
 }
diff --git a/modules/gfx/pymod/glwin_base_proxy.hh b/modules/gfx/pymod/glwin_base_proxy.hh
index 6c73fd142d7f6fa083e936d2e27a718646afdd0d..b8b47975fb06fc8ad1a61b0468de2e0faaed603c 100644
--- a/modules/gfx/pymod/glwin_base_proxy.hh
+++ b/modules/gfx/pymod/glwin_base_proxy.hh
@@ -22,10 +22,15 @@ public:
   virtual void DoRefresh() {
     call_method<void>(self, "DoRefresh");
   }
-  virtual void SetStereo(bool flag) { }
+  virtual bool HasStereo() const { 
+    return call_method<bool>(self,"HasStereo");
+  }
   virtual void StatusMessage(const String& m) {
     call_method<void, const String>(self, "StatusMessage", m);
   }
+  virtual bool HasMultisample() const {
+    return call_method<bool>(self,"HasMultisample");
+  }
 
 private:
   PyObject* self;
diff --git a/modules/gfx/pymod/wrap_gfx.cc b/modules/gfx/pymod/wrap_gfx.cc
index 741675581e2632b2b8fa0bba181db6b8fc89c3ed..430c355952b06bedbd884b5ac48d44335ca4c29a 100644
--- a/modules/gfx/pymod/wrap_gfx.cc
+++ b/modules/gfx/pymod/wrap_gfx.cc
@@ -19,11 +19,14 @@
 #include <boost/python.hpp>
 using namespace boost::python;
 
+#include <ost/gfx/module_config.hh>
+#if OST_SHADER_SUPPORT_ENABLED
+#include <ost/gfx/shader.hh>
+#endif
 #include <ost/info/info.hh>
 #include <ost/gfx/prim_list.hh>
 #include <ost/gfx/gradient.hh>
 #include <ost/gfx/gfx_test_object.hh>
-
 #include <boost/python/suite/indexing/vector_indexing_suite.hpp>
 
 extern void export_Scene();
@@ -144,14 +147,17 @@ BOOST_PYTHON_MODULE(_gfx)
 
   
   class_<Color>("Color",init<>())
-    .def(init<int>())
     .def(init<float, float, float, optional<float> >())
     .def(self_ns::str(self))
     .def("Red",color_get_red)
     .def("Green",color_get_green)
     .def("Blue",color_get_blue)
     .def("Alpha",color_get_alpha)
+    .def("ToHSV",&Color::ToHSV)
+    .def("FromRGBA",&Color::FromRGB)
     ;
+
+  def("HSV",HSV);
   
   class_<Gradient>("Gradient", init<>())
     .def(init<const String&>())
@@ -172,6 +178,15 @@ BOOST_PYTHON_MODULE(_gfx)
 	.def("GetRel", &Stop::GetRel)
   ;
 
+#if OST_SHADER_SUPPORT_ENABLED
+  class_<Shader, boost::noncopyable>("Shader", no_init)
+    .def("Instance",&Shader::Instance,
+         return_value_policy<reference_existing_object>()).staticmethod("Instance")
+    .def("PushProgram",&Shader::PushProgram)
+    .def("PopProgram",&Shader::PopProgram)
+    .def("Activate",&Shader::Activate)
+    ;
+#endif
 
   export_primitives();
 }
diff --git a/modules/gfx/src/CMakeLists.txt b/modules/gfx/src/CMakeLists.txt
index 0d10efc8c48a9857bc12a3dcd04e8e6038f13383..b34e424a10d41b4f97cb7cbdaf32a056d139cf62 100644
--- a/modules/gfx/src/CMakeLists.txt
+++ b/modules/gfx/src/CMakeLists.txt
@@ -10,6 +10,7 @@ gfx_fw.hh
 gfx_node.hh
 gfx_node_fw.hh
 gfx_node_visitor.hh
+gfx_object_base.hh
 gfx_object.hh
 gfx_object_fw.hh
 gfx_prim.hh
@@ -21,6 +22,7 @@ prim_list.hh
 scene.hh
 selection.hh
 surface.hh
+texture.hh
 vertex_array.hh
 vertex_array_helper.hh
 scene_observer.hh
@@ -62,7 +64,6 @@ trace_render_options.hh
 
 
 set(OST_GFX_IMPL_HEADERS
-calc_ambient.hh
 cartoon_renderer.hh
 custom_renderer.hh
 cpk_renderer.hh
@@ -90,11 +91,8 @@ set(OST_GFX_SOURCES
 bitmap_io.cc
 color.cc
 primitives.cc
-offscreen_buffer.cc
 entity.cc
-
 symmetry_node.cc
-
 gfx_node.cc
 gfx_object.cc
 gfx_prim.cc
@@ -110,6 +108,7 @@ vertex_array.cc
 vertex_array_helper.cc
 material.cc
 povray.cc
+texture.cc
 color_ops/color_op.cc
 color_ops/by_element_color_op.cc
 color_ops/by_chain_color_op.cc
@@ -118,7 +117,6 @@ color_ops/gradient_color_op.cc
 color_ops/entity_view_color_op.cc
 color_ops/basic_gradient_color_op.cc
 color_ops/gradient_level_color_op.cc
-impl/calc_ambient.cc
 impl/entity_renderer.cc
 impl/entity_detail.cc
 impl/cartoon_renderer.cc
@@ -175,10 +173,27 @@ else()
   set(OST_GFX_MAP_SOURCES "")  
 endif()
 
+if (UNIX AND NOT APPLE)
+  list(APPEND OST_GFX_SOURCES impl/glx_offscreen_buffer.cc)
+  list(APPEND OST_GFX_IMPL_HEADERS glx_offscreen_buffer.hh)
+endif()
+
+if (APPLE)
+  list(APPEND OST_GFX_SOURCES impl/cgl_offscreen_buffer.cc)
+  list(APPEND OST_GFX_IMPL_HEADERS cgl_offscreen_buffer.hh)
+endif()
+
+if(WIN32)
+  list(APPEND OST_GFX_SOURCES impl/wgl_offscreen_buffer.cc)
+  list(APPEND OST_GFX_IMPL_HEADERS wgl_offscreen_buffer.hh)
+endif()
+
 if (USE_SHADER)
   message("Compiling with Shader Support")
   list(APPEND OST_GFX_SOURCES shader.cc)
   list(APPEND OST_GFX_HEADERS shader.hh)
+  list(APPEND OST_GFX_SOURCES impl/scene_fx.cc)
+  list(APPEND OST_GFX_IMPL_HEADERS scene_fx.hh)
   if (NOT APPLE)
     set(OST_GLEW_HEADERS
        glew.h
@@ -210,27 +225,35 @@ target_link_libraries(ost_gfx ${OPENGL_LIBRARIES} ${PNG_LIBRARIES})
 
 if (USE_SHADER)
   set(SHADER_FILES
-    shader/basic_lf_vs.glsl
-    shader/basic_lf_fs.glsl
-    shader/fraglight_lf_vs.glsl
-    shader/fraglight_lf_fs.glsl
-    shader/basic_lfs_vs.glsl
-    shader/basic_lfs_fs.glsl
-    shader/fraglight_lfs_vs.glsl
-    shader/fraglight_lfs_fs.glsl
-    shader/basic_hf_vs.glsl
-    shader/selfx_vs.glsl
-    shader/selfx_fs.glsl
-    shader/toon_vs.glsl
-    shader/toon_fs.glsl
-    shader/toon2_fs.glsl
-    shader/noop_vs.glsl
     shader/aaline_fs.glsl
-    shader/iso_vs.glsl
-    shader/iso_fs.glsl
-    shader/fast_sphere_vs.glsl
+    shader/amboccl_fs.glsl
+    shader/basic_fs.glsl
+    shader/basic_hf_vs.glsl
+    shader/basic_lf_fs.glsl
+    shader/basic_lf_vs.glsl
+    shader/basic_vs.glsl
+    shader/beacon_fs.glsl
+    shader/convolute1_fs.glsl
+    shader/dumpnorm_fs.glsl
+    shader/dumpnorm_vs.glsl
     shader/fast_sphere_fs.glsl
+    shader/fast_sphere_vs.glsl
+    shader/fraglight_fs.glsl
+    shader/fraglight_vs.glsl
+    shader/iso_fs.glsl
+    shader/iso_vs.glsl
+    shader/noop_vs.glsl
     shader/outline_vs.glsl
+    shader/quadpp_vs.glsl
+    shader/scenefx_fs.glsl
+    shader/scenefx_vs.glsl
+    shader/selfx_fs.glsl
+    shader/selfx_vs.glsl
+    shader/toon2_fs.glsl
+    shader/toon_fs.glsl
+    shader/toon_vs.glsl
+    shader/screenblur4_fs.glsl
+    shader/test_tex_fs.glsl
   )
   copy_if_different("./" "${SHARED_DATA_PATH}/shader" "${SHADER_FILES}" 
                     "SHADER_TARGETS" ost_gfx)  
diff --git a/modules/gfx/src/GL/glew.c b/modules/gfx/src/GL/glew.c
index 24c6a726c38153020710e146051590788d76bfc2..987236b7d30f9e55fcaf110a729725d6f0d060d6 100644
--- a/modules/gfx/src/GL/glew.c
+++ b/modules/gfx/src/GL/glew.c
@@ -66,9 +66,26 @@
 #endif /* GLEW_MX */
 
 #if defined(__APPLE__)
-#include <mach-o/dyld.h>
 #include <stdlib.h>
 #include <string.h>
+#include <AvailabilityMacros.h>
+
+#ifdef MAC_OS_X_VERSION_10_3
+
+#include <dlfcn.h>
+
+void* NSGLGetProcAddress (const GLubyte *name)
+{
+  static void* image = NULL;
+  if (NULL == image) 
+  {
+    image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
+  }
+  return image ? dlsym(image, (const char*)name) : NULL;
+}
+#else
+
+#include <mach-o/dyld.h>
 
 void* NSGLGetProcAddress (const GLubyte *name)
 {
@@ -90,6 +107,7 @@ void* NSGLGetProcAddress (const GLubyte *name)
   free(symbolName);
   return symbol ? NSAddressOfSymbol(symbol) : NULL;
 }
+#endif /* MAC_OS_X_VERSION_10_3 */
 #endif /* __APPLE__ */
 
 #if defined(__sgi) || defined (__sun)
@@ -444,8 +462,6 @@ PFNGLUNIFORMMATRIX4X3FVPROC __glewUniformMatrix4x3fv = NULL;
 
 PFNGLBEGINCONDITIONALRENDERPROC __glewBeginConditionalRender = NULL;
 PFNGLBEGINTRANSFORMFEEDBACKPROC __glewBeginTransformFeedback = NULL;
-PFNGLBINDBUFFERBASEPROC __glewBindBufferBase = NULL;
-PFNGLBINDBUFFERRANGEPROC __glewBindBufferRange = NULL;
 PFNGLBINDFRAGDATALOCATIONPROC __glewBindFragDataLocation = NULL;
 PFNGLCLAMPCOLORPROC __glewClampColor = NULL;
 PFNGLCLEARBUFFERFIPROC __glewClearBufferfi = NULL;
@@ -459,7 +475,6 @@ PFNGLENDCONDITIONALRENDERPROC __glewEndConditionalRender = NULL;
 PFNGLENDTRANSFORMFEEDBACKPROC __glewEndTransformFeedback = NULL;
 PFNGLGETBOOLEANI_VPROC __glewGetBooleani_v = NULL;
 PFNGLGETFRAGDATALOCATIONPROC __glewGetFragDataLocation = NULL;
-PFNGLGETINTEGERI_VPROC __glewGetIntegeri_v = NULL;
 PFNGLGETSTRINGIPROC __glewGetStringi = NULL;
 PFNGLGETTEXPARAMETERIIVPROC __glewGetTexParameterIiv = NULL;
 PFNGLGETTEXPARAMETERIUIVPROC __glewGetTexParameterIuiv = NULL;
@@ -501,8 +516,43 @@ PFNGLVERTEXATTRIBI4UIVPROC __glewVertexAttribI4uiv = NULL;
 PFNGLVERTEXATTRIBI4USVPROC __glewVertexAttribI4usv = NULL;
 PFNGLVERTEXATTRIBIPOINTERPROC __glewVertexAttribIPointer = NULL;
 
+PFNGLDRAWARRAYSINSTANCEDPROC __glewDrawArraysInstanced = NULL;
+PFNGLDRAWELEMENTSINSTANCEDPROC __glewDrawElementsInstanced = NULL;
+PFNGLPRIMITIVERESTARTINDEXPROC __glewPrimitiveRestartIndex = NULL;
+PFNGLTEXBUFFERPROC __glewTexBuffer = NULL;
+
+PFNGLFRAMEBUFFERTEXTUREPROC __glewFramebufferTexture = NULL;
+PFNGLGETBUFFERPARAMETERI64VPROC __glewGetBufferParameteri64v = NULL;
+PFNGLGETINTEGER64I_VPROC __glewGetInteger64i_v = NULL;
+
+PFNGLBLENDEQUATIONSEPARATEIPROC __glewBlendEquationSeparatei = NULL;
+PFNGLBLENDEQUATIONIPROC __glewBlendEquationi = NULL;
+PFNGLBLENDFUNCSEPARATEIPROC __glewBlendFuncSeparatei = NULL;
+PFNGLBLENDFUNCIPROC __glewBlendFunci = NULL;
+PFNGLMINSAMPLESHADINGPROC __glewMinSampleShading = NULL;
+
 PFNGLTBUFFERMASK3DFXPROC __glewTbufferMask3DFX = NULL;
 
+PFNGLBLENDEQUATIONINDEXEDAMDPROC __glewBlendEquationIndexedAMD = NULL;
+PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC __glewBlendEquationSeparateIndexedAMD = NULL;
+PFNGLBLENDFUNCINDEXEDAMDPROC __glewBlendFuncIndexedAMD = NULL;
+PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC __glewBlendFuncSeparateIndexedAMD = NULL;
+
+PFNGLBEGINPERFMONITORAMDPROC __glewBeginPerfMonitorAMD = NULL;
+PFNGLDELETEPERFMONITORSAMDPROC __glewDeletePerfMonitorsAMD = NULL;
+PFNGLENDPERFMONITORAMDPROC __glewEndPerfMonitorAMD = NULL;
+PFNGLGENPERFMONITORSAMDPROC __glewGenPerfMonitorsAMD = NULL;
+PFNGLGETPERFMONITORCOUNTERDATAAMDPROC __glewGetPerfMonitorCounterDataAMD = NULL;
+PFNGLGETPERFMONITORCOUNTERINFOAMDPROC __glewGetPerfMonitorCounterInfoAMD = NULL;
+PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC __glewGetPerfMonitorCounterStringAMD = NULL;
+PFNGLGETPERFMONITORCOUNTERSAMDPROC __glewGetPerfMonitorCountersAMD = NULL;
+PFNGLGETPERFMONITORGROUPSTRINGAMDPROC __glewGetPerfMonitorGroupStringAMD = NULL;
+PFNGLGETPERFMONITORGROUPSAMDPROC __glewGetPerfMonitorGroupsAMD = NULL;
+PFNGLSELECTPERFMONITORCOUNTERSAMDPROC __glewSelectPerfMonitorCountersAMD = NULL;
+
+PFNGLTESSELLATIONFACTORAMDPROC __glewTessellationFactorAMD = NULL;
+PFNGLTESSELLATIONMODEAMDPROC __glewTessellationModeAMD = NULL;
+
 PFNGLDRAWELEMENTARRAYAPPLEPROC __glewDrawElementArrayAPPLE = NULL;
 PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC __glewDrawRangeElementArrayAPPLE = NULL;
 PFNGLELEMENTPOINTERAPPLEPROC __glewElementPointerAPPLE = NULL;
@@ -521,6 +571,10 @@ PFNGLTESTOBJECTAPPLEPROC __glewTestObjectAPPLE = NULL;
 PFNGLBUFFERPARAMETERIAPPLEPROC __glewBufferParameteriAPPLE = NULL;
 PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC __glewFlushMappedBufferRangeAPPLE = NULL;
 
+PFNGLGETOBJECTPARAMETERIVAPPLEPROC __glewGetObjectParameterivAPPLE = NULL;
+PFNGLOBJECTPURGEABLEAPPLEPROC __glewObjectPurgeableAPPLE = NULL;
+PFNGLOBJECTUNPURGEABLEAPPLEPROC __glewObjectUnpurgeableAPPLE = NULL;
+
 PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC __glewGetTexParameterPointervAPPLE = NULL;
 PFNGLTEXTURERANGEAPPLEPROC __glewTextureRangeAPPLE = NULL;
 
@@ -533,10 +587,36 @@ PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC __glewFlushVertexArrayRangeAPPLE = NULL;
 PFNGLVERTEXARRAYPARAMETERIAPPLEPROC __glewVertexArrayParameteriAPPLE = NULL;
 PFNGLVERTEXARRAYRANGEAPPLEPROC __glewVertexArrayRangeAPPLE = NULL;
 
+PFNGLDISABLEVERTEXATTRIBAPPLEPROC __glewDisableVertexAttribAPPLE = NULL;
+PFNGLENABLEVERTEXATTRIBAPPLEPROC __glewEnableVertexAttribAPPLE = NULL;
+PFNGLISVERTEXATTRIBENABLEDAPPLEPROC __glewIsVertexAttribEnabledAPPLE = NULL;
+PFNGLMAPVERTEXATTRIB1DAPPLEPROC __glewMapVertexAttrib1dAPPLE = NULL;
+PFNGLMAPVERTEXATTRIB1FAPPLEPROC __glewMapVertexAttrib1fAPPLE = NULL;
+PFNGLMAPVERTEXATTRIB2DAPPLEPROC __glewMapVertexAttrib2dAPPLE = NULL;
+PFNGLMAPVERTEXATTRIB2FAPPLEPROC __glewMapVertexAttrib2fAPPLE = NULL;
+
+PFNGLBINDFRAGDATALOCATIONINDEXEDPROC __glewBindFragDataLocationIndexed = NULL;
+PFNGLGETFRAGDATAINDEXPROC __glewGetFragDataIndex = NULL;
+
 PFNGLCLAMPCOLORARBPROC __glewClampColorARB = NULL;
 
+PFNGLCOPYBUFFERSUBDATAPROC __glewCopyBufferSubData = NULL;
+
 PFNGLDRAWBUFFERSARBPROC __glewDrawBuffersARB = NULL;
 
+PFNGLBLENDEQUATIONSEPARATEIARBPROC __glewBlendEquationSeparateiARB = NULL;
+PFNGLBLENDEQUATIONIARBPROC __glewBlendEquationiARB = NULL;
+PFNGLBLENDFUNCSEPARATEIARBPROC __glewBlendFuncSeparateiARB = NULL;
+PFNGLBLENDFUNCIARBPROC __glewBlendFunciARB = NULL;
+
+PFNGLDRAWELEMENTSBASEVERTEXPROC __glewDrawElementsBaseVertex = NULL;
+PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC __glewDrawElementsInstancedBaseVertex = NULL;
+PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC __glewDrawRangeElementsBaseVertex = NULL;
+PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC __glewMultiDrawElementsBaseVertex = NULL;
+
+PFNGLDRAWARRAYSINDIRECTPROC __glewDrawArraysIndirect = NULL;
+PFNGLDRAWELEMENTSINDIRECTPROC __glewDrawElementsIndirect = NULL;
+
 PFNGLDRAWARRAYSINSTANCEDARBPROC __glewDrawArraysInstancedARB = NULL;
 PFNGLDRAWELEMENTSINSTANCEDARBPROC __glewDrawElementsInstancedARB = NULL;
 
@@ -547,10 +627,10 @@ PFNGLCHECKFRAMEBUFFERSTATUSPROC __glewCheckFramebufferStatus = NULL;
 PFNGLDELETEFRAMEBUFFERSPROC __glewDeleteFramebuffers = NULL;
 PFNGLDELETERENDERBUFFERSPROC __glewDeleteRenderbuffers = NULL;
 PFNGLFRAMEBUFFERRENDERBUFFERPROC __glewFramebufferRenderbuffer = NULL;
-PFNGLFRAMEBUFFERTEXTURLAYERPROC __glewFramebufferTexturLayer = NULL;
 PFNGLFRAMEBUFFERTEXTURE1DPROC __glewFramebufferTexture1D = NULL;
 PFNGLFRAMEBUFFERTEXTURE2DPROC __glewFramebufferTexture2D = NULL;
 PFNGLFRAMEBUFFERTEXTURE3DPROC __glewFramebufferTexture3D = NULL;
+PFNGLFRAMEBUFFERTEXTURELAYERPROC __glewFramebufferTextureLayer = NULL;
 PFNGLGENFRAMEBUFFERSPROC __glewGenFramebuffers = NULL;
 PFNGLGENRENDERBUFFERSPROC __glewGenRenderbuffers = NULL;
 PFNGLGENERATEMIPMAPPROC __glewGenerateMipmap = NULL;
@@ -659,6 +739,25 @@ PFNGLISQUERYARBPROC __glewIsQueryARB = NULL;
 PFNGLPOINTPARAMETERFARBPROC __glewPointParameterfARB = NULL;
 PFNGLPOINTPARAMETERFVARBPROC __glewPointParameterfvARB = NULL;
 
+PFNGLPROVOKINGVERTEXPROC __glewProvokingVertex = NULL;
+
+PFNGLMINSAMPLESHADINGARBPROC __glewMinSampleShadingARB = NULL;
+
+PFNGLBINDSAMPLERPROC __glewBindSampler = NULL;
+PFNGLDELETESAMPLERSPROC __glewDeleteSamplers = NULL;
+PFNGLGENSAMPLERSPROC __glewGenSamplers = NULL;
+PFNGLGETSAMPLERPARAMETERIIVPROC __glewGetSamplerParameterIiv = NULL;
+PFNGLGETSAMPLERPARAMETERIUIVPROC __glewGetSamplerParameterIuiv = NULL;
+PFNGLGETSAMPLERPARAMETERFVPROC __glewGetSamplerParameterfv = NULL;
+PFNGLGETSAMPLERPARAMETERIVPROC __glewGetSamplerParameteriv = NULL;
+PFNGLISSAMPLERPROC __glewIsSampler = NULL;
+PFNGLSAMPLERPARAMETERIIVPROC __glewSamplerParameterIiv = NULL;
+PFNGLSAMPLERPARAMETERIUIVPROC __glewSamplerParameterIuiv = NULL;
+PFNGLSAMPLERPARAMETERFPROC __glewSamplerParameterf = NULL;
+PFNGLSAMPLERPARAMETERFVPROC __glewSamplerParameterfv = NULL;
+PFNGLSAMPLERPARAMETERIPROC __glewSamplerParameteri = NULL;
+PFNGLSAMPLERPARAMETERIVPROC __glewSamplerParameteriv = NULL;
+
 PFNGLATTACHOBJECTARBPROC __glewAttachObjectARB = NULL;
 PFNGLCOMPILESHADERARBPROC __glewCompileShaderARB = NULL;
 PFNGLCREATEPROGRAMOBJECTARBPROC __glewCreateProgramObjectARB = NULL;
@@ -699,6 +798,33 @@ PFNGLUNIFORMMATRIX4FVARBPROC __glewUniformMatrix4fvARB = NULL;
 PFNGLUSEPROGRAMOBJECTARBPROC __glewUseProgramObjectARB = NULL;
 PFNGLVALIDATEPROGRAMARBPROC __glewValidateProgramARB = NULL;
 
+PFNGLGETACTIVESUBROUTINENAMEPROC __glewGetActiveSubroutineName = NULL;
+PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC __glewGetActiveSubroutineUniformName = NULL;
+PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC __glewGetActiveSubroutineUniformiv = NULL;
+PFNGLGETPROGRAMSTAGEIVPROC __glewGetProgramStageiv = NULL;
+PFNGLGETSUBROUTINEINDEXPROC __glewGetSubroutineIndex = NULL;
+PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC __glewGetSubroutineUniformLocation = NULL;
+PFNGLGETUNIFORMSUBROUTINEUIVPROC __glewGetUniformSubroutineuiv = NULL;
+PFNGLUNIFORMSUBROUTINESUIVPROC __glewUniformSubroutinesuiv = NULL;
+
+PFNGLCOMPILESHADERINCLUDEARBPROC __glewCompileShaderIncludeARB = NULL;
+PFNGLDELETENAMEDSTRINGARBPROC __glewDeleteNamedStringARB = NULL;
+PFNGLGETNAMEDSTRINGARBPROC __glewGetNamedStringARB = NULL;
+PFNGLGETNAMEDSTRINGIVARBPROC __glewGetNamedStringivARB = NULL;
+PFNGLISNAMEDSTRINGARBPROC __glewIsNamedStringARB = NULL;
+PFNGLNAMEDSTRINGARBPROC __glewNamedStringARB = NULL;
+
+PFNGLCLIENTWAITSYNCPROC __glewClientWaitSync = NULL;
+PFNGLDELETESYNCPROC __glewDeleteSync = NULL;
+PFNGLFENCESYNCPROC __glewFenceSync = NULL;
+PFNGLGETINTEGER64VPROC __glewGetInteger64v = NULL;
+PFNGLGETSYNCIVPROC __glewGetSynciv = NULL;
+PFNGLISSYNCPROC __glewIsSync = NULL;
+PFNGLWAITSYNCPROC __glewWaitSync = NULL;
+
+PFNGLPATCHPARAMETERFVPROC __glewPatchParameterfv = NULL;
+PFNGLPATCHPARAMETERIPROC __glewPatchParameteri = NULL;
+
 PFNGLTEXBUFFERARBPROC __glewTexBufferARB = NULL;
 
 PFNGLCOMPRESSEDTEXIMAGE1DARBPROC __glewCompressedTexImage1DARB = NULL;
@@ -709,11 +835,44 @@ PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC __glewCompressedTexSubImage2DARB = NULL;
 PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC __glewCompressedTexSubImage3DARB = NULL;
 PFNGLGETCOMPRESSEDTEXIMAGEARBPROC __glewGetCompressedTexImageARB = NULL;
 
+PFNGLGETMULTISAMPLEFVPROC __glewGetMultisamplefv = NULL;
+PFNGLSAMPLEMASKIPROC __glewSampleMaski = NULL;
+PFNGLTEXIMAGE2DMULTISAMPLEPROC __glewTexImage2DMultisample = NULL;
+PFNGLTEXIMAGE3DMULTISAMPLEPROC __glewTexImage3DMultisample = NULL;
+
+PFNGLGETQUERYOBJECTI64VPROC __glewGetQueryObjecti64v = NULL;
+PFNGLGETQUERYOBJECTUI64VPROC __glewGetQueryObjectui64v = NULL;
+PFNGLQUERYCOUNTERPROC __glewQueryCounter = NULL;
+
+PFNGLBINDTRANSFORMFEEDBACKPROC __glewBindTransformFeedback = NULL;
+PFNGLDELETETRANSFORMFEEDBACKSPROC __glewDeleteTransformFeedbacks = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKPROC __glewDrawTransformFeedback = NULL;
+PFNGLGENTRANSFORMFEEDBACKSPROC __glewGenTransformFeedbacks = NULL;
+PFNGLISTRANSFORMFEEDBACKPROC __glewIsTransformFeedback = NULL;
+PFNGLPAUSETRANSFORMFEEDBACKPROC __glewPauseTransformFeedback = NULL;
+PFNGLRESUMETRANSFORMFEEDBACKPROC __glewResumeTransformFeedback = NULL;
+
+PFNGLBEGINQUERYINDEXEDPROC __glewBeginQueryIndexed = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC __glewDrawTransformFeedbackStream = NULL;
+PFNGLENDQUERYINDEXEDPROC __glewEndQueryIndexed = NULL;
+PFNGLGETQUERYINDEXEDIVPROC __glewGetQueryIndexediv = NULL;
+
 PFNGLLOADTRANSPOSEMATRIXDARBPROC __glewLoadTransposeMatrixdARB = NULL;
 PFNGLLOADTRANSPOSEMATRIXFARBPROC __glewLoadTransposeMatrixfARB = NULL;
 PFNGLMULTTRANSPOSEMATRIXDARBPROC __glewMultTransposeMatrixdARB = NULL;
 PFNGLMULTTRANSPOSEMATRIXFARBPROC __glewMultTransposeMatrixfARB = NULL;
 
+PFNGLBINDBUFFERBASEPROC __glewBindBufferBase = NULL;
+PFNGLBINDBUFFERRANGEPROC __glewBindBufferRange = NULL;
+PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC __glewGetActiveUniformBlockName = NULL;
+PFNGLGETACTIVEUNIFORMBLOCKIVPROC __glewGetActiveUniformBlockiv = NULL;
+PFNGLGETACTIVEUNIFORMNAMEPROC __glewGetActiveUniformName = NULL;
+PFNGLGETACTIVEUNIFORMSIVPROC __glewGetActiveUniformsiv = NULL;
+PFNGLGETINTEGERI_VPROC __glewGetIntegeri_v = NULL;
+PFNGLGETUNIFORMBLOCKINDEXPROC __glewGetUniformBlockIndex = NULL;
+PFNGLGETUNIFORMINDICESPROC __glewGetUniformIndices = NULL;
+PFNGLUNIFORMBLOCKBINDINGPROC __glewUniformBlockBinding = NULL;
+
 PFNGLBINDVERTEXARRAYPROC __glewBindVertexArray = NULL;
 PFNGLDELETEVERTEXARRAYSPROC __glewDeleteVertexArrays = NULL;
 PFNGLGENVERTEXARRAYSPROC __glewGenVertexArrays = NULL;
@@ -809,6 +968,45 @@ PFNGLBINDATTRIBLOCATIONARBPROC __glewBindAttribLocationARB = NULL;
 PFNGLGETACTIVEATTRIBARBPROC __glewGetActiveAttribARB = NULL;
 PFNGLGETATTRIBLOCATIONARBPROC __glewGetAttribLocationARB = NULL;
 
+PFNGLCOLORP3UIPROC __glewColorP3ui = NULL;
+PFNGLCOLORP3UIVPROC __glewColorP3uiv = NULL;
+PFNGLCOLORP4UIPROC __glewColorP4ui = NULL;
+PFNGLCOLORP4UIVPROC __glewColorP4uiv = NULL;
+PFNGLMULTITEXCOORDP1UIPROC __glewMultiTexCoordP1ui = NULL;
+PFNGLMULTITEXCOORDP1UIVPROC __glewMultiTexCoordP1uiv = NULL;
+PFNGLMULTITEXCOORDP2UIPROC __glewMultiTexCoordP2ui = NULL;
+PFNGLMULTITEXCOORDP2UIVPROC __glewMultiTexCoordP2uiv = NULL;
+PFNGLMULTITEXCOORDP3UIPROC __glewMultiTexCoordP3ui = NULL;
+PFNGLMULTITEXCOORDP3UIVPROC __glewMultiTexCoordP3uiv = NULL;
+PFNGLMULTITEXCOORDP4UIPROC __glewMultiTexCoordP4ui = NULL;
+PFNGLMULTITEXCOORDP4UIVPROC __glewMultiTexCoordP4uiv = NULL;
+PFNGLNORMALP3UIPROC __glewNormalP3ui = NULL;
+PFNGLNORMALP3UIVPROC __glewNormalP3uiv = NULL;
+PFNGLSECONDARYCOLORP3UIPROC __glewSecondaryColorP3ui = NULL;
+PFNGLSECONDARYCOLORP3UIVPROC __glewSecondaryColorP3uiv = NULL;
+PFNGLTEXCOORDP1UIPROC __glewTexCoordP1ui = NULL;
+PFNGLTEXCOORDP1UIVPROC __glewTexCoordP1uiv = NULL;
+PFNGLTEXCOORDP2UIPROC __glewTexCoordP2ui = NULL;
+PFNGLTEXCOORDP2UIVPROC __glewTexCoordP2uiv = NULL;
+PFNGLTEXCOORDP3UIPROC __glewTexCoordP3ui = NULL;
+PFNGLTEXCOORDP3UIVPROC __glewTexCoordP3uiv = NULL;
+PFNGLTEXCOORDP4UIPROC __glewTexCoordP4ui = NULL;
+PFNGLTEXCOORDP4UIVPROC __glewTexCoordP4uiv = NULL;
+PFNGLVERTEXATTRIBP1UIPROC __glewVertexAttribP1ui = NULL;
+PFNGLVERTEXATTRIBP1UIVPROC __glewVertexAttribP1uiv = NULL;
+PFNGLVERTEXATTRIBP2UIPROC __glewVertexAttribP2ui = NULL;
+PFNGLVERTEXATTRIBP2UIVPROC __glewVertexAttribP2uiv = NULL;
+PFNGLVERTEXATTRIBP3UIPROC __glewVertexAttribP3ui = NULL;
+PFNGLVERTEXATTRIBP3UIVPROC __glewVertexAttribP3uiv = NULL;
+PFNGLVERTEXATTRIBP4UIPROC __glewVertexAttribP4ui = NULL;
+PFNGLVERTEXATTRIBP4UIVPROC __glewVertexAttribP4uiv = NULL;
+PFNGLVERTEXP2UIPROC __glewVertexP2ui = NULL;
+PFNGLVERTEXP2UIVPROC __glewVertexP2uiv = NULL;
+PFNGLVERTEXP3UIPROC __glewVertexP3ui = NULL;
+PFNGLVERTEXP3UIVPROC __glewVertexP3uiv = NULL;
+PFNGLVERTEXP4UIPROC __glewVertexP4ui = NULL;
+PFNGLVERTEXP4UIVPROC __glewVertexP4uiv = NULL;
+
 PFNGLWINDOWPOS2DARBPROC __glewWindowPos2dARB = NULL;
 PFNGLWINDOWPOS2DVARBPROC __glewWindowPos2dvARB = NULL;
 PFNGLWINDOWPOS2FARBPROC __glewWindowPos2fARB = NULL;
@@ -988,7 +1186,14 @@ PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC __glewCopyTextureSubImage1DEXT = NULL;
 PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC __glewCopyTextureSubImage2DEXT = NULL;
 PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC __glewCopyTextureSubImage3DEXT = NULL;
 PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC __glewDisableClientStateIndexedEXT = NULL;
+PFNGLDISABLECLIENTSTATEIEXTPROC __glewDisableClientStateiEXT = NULL;
+PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC __glewDisableVertexArrayAttribEXT = NULL;
+PFNGLDISABLEVERTEXARRAYEXTPROC __glewDisableVertexArrayEXT = NULL;
 PFNGLENABLECLIENTSTATEINDEXEDEXTPROC __glewEnableClientStateIndexedEXT = NULL;
+PFNGLENABLECLIENTSTATEIEXTPROC __glewEnableClientStateiEXT = NULL;
+PFNGLENABLEVERTEXARRAYATTRIBEXTPROC __glewEnableVertexArrayAttribEXT = NULL;
+PFNGLENABLEVERTEXARRAYEXTPROC __glewEnableVertexArrayEXT = NULL;
+PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC __glewFlushMappedNamedBufferRangeEXT = NULL;
 PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC __glewFramebufferDrawBufferEXT = NULL;
 PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC __glewFramebufferDrawBuffersEXT = NULL;
 PFNGLFRAMEBUFFERREADBUFFEREXTPROC __glewFramebufferReadBufferEXT = NULL;
@@ -997,7 +1202,9 @@ PFNGLGENERATETEXTUREMIPMAPEXTPROC __glewGenerateTextureMipmapEXT = NULL;
 PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC __glewGetCompressedMultiTexImageEXT = NULL;
 PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC __glewGetCompressedTextureImageEXT = NULL;
 PFNGLGETDOUBLEINDEXEDVEXTPROC __glewGetDoubleIndexedvEXT = NULL;
+PFNGLGETDOUBLEI_VEXTPROC __glewGetDoublei_vEXT = NULL;
 PFNGLGETFLOATINDEXEDVEXTPROC __glewGetFloatIndexedvEXT = NULL;
+PFNGLGETFLOATI_VEXTPROC __glewGetFloati_vEXT = NULL;
 PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC __glewGetFramebufferParameterivEXT = NULL;
 PFNGLGETMULTITEXENVFVEXTPROC __glewGetMultiTexEnvfvEXT = NULL;
 PFNGLGETMULTITEXENVIVEXTPROC __glewGetMultiTexEnvivEXT = NULL;
@@ -1023,6 +1230,7 @@ PFNGLGETNAMEDPROGRAMSTRINGEXTPROC __glewGetNamedProgramStringEXT = NULL;
 PFNGLGETNAMEDPROGRAMIVEXTPROC __glewGetNamedProgramivEXT = NULL;
 PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC __glewGetNamedRenderbufferParameterivEXT = NULL;
 PFNGLGETPOINTERINDEXEDVEXTPROC __glewGetPointerIndexedvEXT = NULL;
+PFNGLGETPOINTERI_VEXTPROC __glewGetPointeri_vEXT = NULL;
 PFNGLGETTEXTUREIMAGEEXTPROC __glewGetTextureImageEXT = NULL;
 PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC __glewGetTextureLevelParameterfvEXT = NULL;
 PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC __glewGetTextureLevelParameterivEXT = NULL;
@@ -1030,7 +1238,12 @@ PFNGLGETTEXTUREPARAMETERIIVEXTPROC __glewGetTextureParameterIivEXT = NULL;
 PFNGLGETTEXTUREPARAMETERIUIVEXTPROC __glewGetTextureParameterIuivEXT = NULL;
 PFNGLGETTEXTUREPARAMETERFVEXTPROC __glewGetTextureParameterfvEXT = NULL;
 PFNGLGETTEXTUREPARAMETERIVEXTPROC __glewGetTextureParameterivEXT = NULL;
+PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC __glewGetVertexArrayIntegeri_vEXT = NULL;
+PFNGLGETVERTEXARRAYINTEGERVEXTPROC __glewGetVertexArrayIntegervEXT = NULL;
+PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC __glewGetVertexArrayPointeri_vEXT = NULL;
+PFNGLGETVERTEXARRAYPOINTERVEXTPROC __glewGetVertexArrayPointervEXT = NULL;
 PFNGLMAPNAMEDBUFFEREXTPROC __glewMapNamedBufferEXT = NULL;
+PFNGLMAPNAMEDBUFFERRANGEEXTPROC __glewMapNamedBufferRangeEXT = NULL;
 PFNGLMATRIXFRUSTUMEXTPROC __glewMatrixFrustumEXT = NULL;
 PFNGLMATRIXLOADIDENTITYEXTPROC __glewMatrixLoadIdentityEXT = NULL;
 PFNGLMATRIXLOADTRANSPOSEDEXTPROC __glewMatrixLoadTransposedEXT = NULL;
@@ -1077,6 +1290,7 @@ PFNGLMULTITEXSUBIMAGE2DEXTPROC __glewMultiTexSubImage2DEXT = NULL;
 PFNGLMULTITEXSUBIMAGE3DEXTPROC __glewMultiTexSubImage3DEXT = NULL;
 PFNGLNAMEDBUFFERDATAEXTPROC __glewNamedBufferDataEXT = NULL;
 PFNGLNAMEDBUFFERSUBDATAEXTPROC __glewNamedBufferSubDataEXT = NULL;
+PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC __glewNamedCopyBufferSubDataEXT = NULL;
 PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC __glewNamedFramebufferRenderbufferEXT = NULL;
 PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC __glewNamedFramebufferTexture1DEXT = NULL;
 PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC __glewNamedFramebufferTexture2DEXT = NULL;
@@ -1148,6 +1362,17 @@ PFNGLTEXTURESUBIMAGE1DEXTPROC __glewTextureSubImage1DEXT = NULL;
 PFNGLTEXTURESUBIMAGE2DEXTPROC __glewTextureSubImage2DEXT = NULL;
 PFNGLTEXTURESUBIMAGE3DEXTPROC __glewTextureSubImage3DEXT = NULL;
 PFNGLUNMAPNAMEDBUFFEREXTPROC __glewUnmapNamedBufferEXT = NULL;
+PFNGLVERTEXARRAYCOLOROFFSETEXTPROC __glewVertexArrayColorOffsetEXT = NULL;
+PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC __glewVertexArrayEdgeFlagOffsetEXT = NULL;
+PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC __glewVertexArrayFogCoordOffsetEXT = NULL;
+PFNGLVERTEXARRAYINDEXOFFSETEXTPROC __glewVertexArrayIndexOffsetEXT = NULL;
+PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC __glewVertexArrayMultiTexCoordOffsetEXT = NULL;
+PFNGLVERTEXARRAYNORMALOFFSETEXTPROC __glewVertexArrayNormalOffsetEXT = NULL;
+PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC __glewVertexArraySecondaryColorOffsetEXT = NULL;
+PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC __glewVertexArrayTexCoordOffsetEXT = NULL;
+PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC __glewVertexArrayVertexAttribIOffsetEXT = NULL;
+PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC __glewVertexArrayVertexAttribOffsetEXT = NULL;
+PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC __glewVertexArrayVertexOffsetEXT = NULL;
 
 PFNGLCOLORMASKINDEXEDEXTPROC __glewColorMaskIndexedEXT = NULL;
 PFNGLDISABLEINDEXEDEXTPROC __glewDisableIndexedEXT = NULL;
@@ -1293,6 +1518,8 @@ PFNGLPOINTPARAMETERFVEXTPROC __glewPointParameterfvEXT = NULL;
 
 PFNGLPOLYGONOFFSETEXTPROC __glewPolygonOffsetEXT = NULL;
 
+PFNGLPROVOKINGVERTEXEXTPROC __glewProvokingVertexEXT = NULL;
+
 PFNGLBEGINSCENEEXTPROC __glewBeginSceneEXT = NULL;
 PFNGLENDSCENEEXTPROC __glewEndSceneEXT = NULL;
 
@@ -1314,6 +1541,13 @@ PFNGLSECONDARYCOLOR3USEXTPROC __glewSecondaryColor3usEXT = NULL;
 PFNGLSECONDARYCOLOR3USVEXTPROC __glewSecondaryColor3usvEXT = NULL;
 PFNGLSECONDARYCOLORPOINTEREXTPROC __glewSecondaryColorPointerEXT = NULL;
 
+PFNGLACTIVEPROGRAMEXTPROC __glewActiveProgramEXT = NULL;
+PFNGLCREATESHADERPROGRAMEXTPROC __glewCreateShaderProgramEXT = NULL;
+PFNGLUSESHADERPROGRAMEXTPROC __glewUseShaderProgramEXT = NULL;
+
+PFNGLBINDIMAGETEXTUREEXTPROC __glewBindImageTextureEXT = NULL;
+PFNGLMEMORYBARRIEREXTPROC __glewMemoryBarrierEXT = NULL;
+
 PFNGLACTIVESTENCILFACEEXTPROC __glewActiveStencilFaceEXT = NULL;
 
 PFNGLTEXSUBIMAGE1DEXTPROC __glewTexSubImage1DEXT = NULL;
@@ -1361,6 +1595,18 @@ PFNGLNORMALPOINTEREXTPROC __glewNormalPointerEXT = NULL;
 PFNGLTEXCOORDPOINTEREXTPROC __glewTexCoordPointerEXT = NULL;
 PFNGLVERTEXPOINTEREXTPROC __glewVertexPointerEXT = NULL;
 
+PFNGLGETVERTEXATTRIBLDVEXTPROC __glewGetVertexAttribLdvEXT = NULL;
+PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC __glewVertexArrayVertexAttribLOffsetEXT = NULL;
+PFNGLVERTEXATTRIBL1DEXTPROC __glewVertexAttribL1dEXT = NULL;
+PFNGLVERTEXATTRIBL1DVEXTPROC __glewVertexAttribL1dvEXT = NULL;
+PFNGLVERTEXATTRIBL2DEXTPROC __glewVertexAttribL2dEXT = NULL;
+PFNGLVERTEXATTRIBL2DVEXTPROC __glewVertexAttribL2dvEXT = NULL;
+PFNGLVERTEXATTRIBL3DEXTPROC __glewVertexAttribL3dEXT = NULL;
+PFNGLVERTEXATTRIBL3DVEXTPROC __glewVertexAttribL3dvEXT = NULL;
+PFNGLVERTEXATTRIBL4DEXTPROC __glewVertexAttribL4dEXT = NULL;
+PFNGLVERTEXATTRIBL4DVEXTPROC __glewVertexAttribL4dvEXT = NULL;
+PFNGLVERTEXATTRIBLPOINTEREXTPROC __glewVertexAttribLPointerEXT = NULL;
+
 PFNGLBEGINVERTEXSHADEREXTPROC __glewBeginVertexShaderEXT = NULL;
 PFNGLBINDLIGHTPARAMETEREXTPROC __glewBindLightParameterEXT = NULL;
 PFNGLBINDMATERIALPARAMETEREXTPROC __glewBindMaterialParameterEXT = NULL;
@@ -1475,6 +1721,8 @@ PFNGLWINDOWPOS4SVMESAPROC __glewWindowPos4svMESA = NULL;
 PFNGLBEGINCONDITIONALRENDERNVPROC __glewBeginConditionalRenderNV = NULL;
 PFNGLENDCONDITIONALRENDERNVPROC __glewEndConditionalRenderNV = NULL;
 
+PFNGLCOPYIMAGESUBDATANVPROC __glewCopyImageSubDataNV = NULL;
+
 PFNGLCLEARDEPTHDNVPROC __glewClearDepthdNV = NULL;
 PFNGLDEPTHBOUNDSDNVPROC __glewDepthBoundsdNV = NULL;
 PFNGLDEPTHRANGEDNVPROC __glewDepthRangedNV = NULL;
@@ -1525,6 +1773,41 @@ PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC __glewProgramLocalParameterI4uivNV = NULL;
 PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC __glewProgramLocalParametersI4ivNV = NULL;
 PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC __glewProgramLocalParametersI4uivNV = NULL;
 
+PFNGLGETUNIFORMI64VNVPROC __glewGetUniformi64vNV = NULL;
+PFNGLGETUNIFORMUI64VNVPROC __glewGetUniformui64vNV = NULL;
+PFNGLPROGRAMUNIFORM1I64NVPROC __glewProgramUniform1i64NV = NULL;
+PFNGLPROGRAMUNIFORM1I64VNVPROC __glewProgramUniform1i64vNV = NULL;
+PFNGLPROGRAMUNIFORM1UI64NVPROC __glewProgramUniform1ui64NV = NULL;
+PFNGLPROGRAMUNIFORM1UI64VNVPROC __glewProgramUniform1ui64vNV = NULL;
+PFNGLPROGRAMUNIFORM2I64NVPROC __glewProgramUniform2i64NV = NULL;
+PFNGLPROGRAMUNIFORM2I64VNVPROC __glewProgramUniform2i64vNV = NULL;
+PFNGLPROGRAMUNIFORM2UI64NVPROC __glewProgramUniform2ui64NV = NULL;
+PFNGLPROGRAMUNIFORM2UI64VNVPROC __glewProgramUniform2ui64vNV = NULL;
+PFNGLPROGRAMUNIFORM3I64NVPROC __glewProgramUniform3i64NV = NULL;
+PFNGLPROGRAMUNIFORM3I64VNVPROC __glewProgramUniform3i64vNV = NULL;
+PFNGLPROGRAMUNIFORM3UI64NVPROC __glewProgramUniform3ui64NV = NULL;
+PFNGLPROGRAMUNIFORM3UI64VNVPROC __glewProgramUniform3ui64vNV = NULL;
+PFNGLPROGRAMUNIFORM4I64NVPROC __glewProgramUniform4i64NV = NULL;
+PFNGLPROGRAMUNIFORM4I64VNVPROC __glewProgramUniform4i64vNV = NULL;
+PFNGLPROGRAMUNIFORM4UI64NVPROC __glewProgramUniform4ui64NV = NULL;
+PFNGLPROGRAMUNIFORM4UI64VNVPROC __glewProgramUniform4ui64vNV = NULL;
+PFNGLUNIFORM1I64NVPROC __glewUniform1i64NV = NULL;
+PFNGLUNIFORM1I64VNVPROC __glewUniform1i64vNV = NULL;
+PFNGLUNIFORM1UI64NVPROC __glewUniform1ui64NV = NULL;
+PFNGLUNIFORM1UI64VNVPROC __glewUniform1ui64vNV = NULL;
+PFNGLUNIFORM2I64NVPROC __glewUniform2i64NV = NULL;
+PFNGLUNIFORM2I64VNVPROC __glewUniform2i64vNV = NULL;
+PFNGLUNIFORM2UI64NVPROC __glewUniform2ui64NV = NULL;
+PFNGLUNIFORM2UI64VNVPROC __glewUniform2ui64vNV = NULL;
+PFNGLUNIFORM3I64NVPROC __glewUniform3i64NV = NULL;
+PFNGLUNIFORM3I64VNVPROC __glewUniform3i64vNV = NULL;
+PFNGLUNIFORM3UI64NVPROC __glewUniform3ui64NV = NULL;
+PFNGLUNIFORM3UI64VNVPROC __glewUniform3ui64vNV = NULL;
+PFNGLUNIFORM4I64NVPROC __glewUniform4i64NV = NULL;
+PFNGLUNIFORM4I64VNVPROC __glewUniform4i64vNV = NULL;
+PFNGLUNIFORM4UI64NVPROC __glewUniform4ui64NV = NULL;
+PFNGLUNIFORM4UI64VNVPROC __glewUniform4ui64vNV = NULL;
+
 PFNGLCOLOR3HNVPROC __glewColor3hNV = NULL;
 PFNGLCOLOR3HVNVPROC __glewColor3hvNV = NULL;
 PFNGLCOLOR4HNVPROC __glewColor4hNV = NULL;
@@ -1596,7 +1879,6 @@ PFNGLGETVIDEOUI64VNVPROC __glewGetVideoui64vNV = NULL;
 PFNGLGETVIDEOUIVNVPROC __glewGetVideouivNV = NULL;
 PFNGLPRESENTFRAMEDUALFILLNVPROC __glewPresentFrameDualFillNV = NULL;
 PFNGLPRESENTFRAMEKEYEDNVPROC __glewPresentFrameKeyedNV = NULL;
-PFNGLVIDEOPARAMETERIVNVPROC __glewVideoParameterivNV = NULL;
 
 PFNGLPRIMITIVERESTARTINDEXNVPROC __glewPrimitiveRestartIndexNV = NULL;
 PFNGLPRIMITIVERESTARTNVPROC __glewPrimitiveRestartNV = NULL;
@@ -1618,6 +1900,22 @@ PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC __glewGetFinalCombinerInputParameter
 PFNGLCOMBINERSTAGEPARAMETERFVNVPROC __glewCombinerStageParameterfvNV = NULL;
 PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC __glewGetCombinerStageParameterfvNV = NULL;
 
+PFNGLGETBUFFERPARAMETERUI64VNVPROC __glewGetBufferParameterui64vNV = NULL;
+PFNGLGETINTEGERUI64VNVPROC __glewGetIntegerui64vNV = NULL;
+PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC __glewGetNamedBufferParameterui64vNV = NULL;
+PFNGLISBUFFERRESIDENTNVPROC __glewIsBufferResidentNV = NULL;
+PFNGLISNAMEDBUFFERRESIDENTNVPROC __glewIsNamedBufferResidentNV = NULL;
+PFNGLMAKEBUFFERNONRESIDENTNVPROC __glewMakeBufferNonResidentNV = NULL;
+PFNGLMAKEBUFFERRESIDENTNVPROC __glewMakeBufferResidentNV = NULL;
+PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC __glewMakeNamedBufferNonResidentNV = NULL;
+PFNGLMAKENAMEDBUFFERRESIDENTNVPROC __glewMakeNamedBufferResidentNV = NULL;
+PFNGLPROGRAMUNIFORMUI64NVPROC __glewProgramUniformui64NV = NULL;
+PFNGLPROGRAMUNIFORMUI64VNVPROC __glewProgramUniformui64vNV = NULL;
+PFNGLUNIFORMUI64NVPROC __glewUniformui64NV = NULL;
+PFNGLUNIFORMUI64VNVPROC __glewUniformui64vNV = NULL;
+
+PFNGLTEXTUREBARRIERNVPROC __glewTextureBarrierNV = NULL;
+
 PFNGLACTIVEVARYINGNVPROC __glewActiveVaryingNV = NULL;
 PFNGLBEGINTRANSFORMFEEDBACKNVPROC __glewBeginTransformFeedbackNV = NULL;
 PFNGLBINDBUFFERBASENVPROC __glewBindBufferBaseNV = NULL;
@@ -1630,9 +1928,50 @@ PFNGLGETVARYINGLOCATIONNVPROC __glewGetVaryingLocationNV = NULL;
 PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC __glewTransformFeedbackAttribsNV = NULL;
 PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC __glewTransformFeedbackVaryingsNV = NULL;
 
+PFNGLBINDTRANSFORMFEEDBACKNVPROC __glewBindTransformFeedbackNV = NULL;
+PFNGLDELETETRANSFORMFEEDBACKSNVPROC __glewDeleteTransformFeedbacksNV = NULL;
+PFNGLDRAWTRANSFORMFEEDBACKNVPROC __glewDrawTransformFeedbackNV = NULL;
+PFNGLGENTRANSFORMFEEDBACKSNVPROC __glewGenTransformFeedbacksNV = NULL;
+PFNGLISTRANSFORMFEEDBACKNVPROC __glewIsTransformFeedbackNV = NULL;
+PFNGLPAUSETRANSFORMFEEDBACKNVPROC __glewPauseTransformFeedbackNV = NULL;
+PFNGLRESUMETRANSFORMFEEDBACKNVPROC __glewResumeTransformFeedbackNV = NULL;
+
 PFNGLFLUSHVERTEXARRAYRANGENVPROC __glewFlushVertexArrayRangeNV = NULL;
 PFNGLVERTEXARRAYRANGENVPROC __glewVertexArrayRangeNV = NULL;
 
+PFNGLGETVERTEXATTRIBLI64VNVPROC __glewGetVertexAttribLi64vNV = NULL;
+PFNGLGETVERTEXATTRIBLUI64VNVPROC __glewGetVertexAttribLui64vNV = NULL;
+PFNGLVERTEXATTRIBL1I64NVPROC __glewVertexAttribL1i64NV = NULL;
+PFNGLVERTEXATTRIBL1I64VNVPROC __glewVertexAttribL1i64vNV = NULL;
+PFNGLVERTEXATTRIBL1UI64NVPROC __glewVertexAttribL1ui64NV = NULL;
+PFNGLVERTEXATTRIBL1UI64VNVPROC __glewVertexAttribL1ui64vNV = NULL;
+PFNGLVERTEXATTRIBL2I64NVPROC __glewVertexAttribL2i64NV = NULL;
+PFNGLVERTEXATTRIBL2I64VNVPROC __glewVertexAttribL2i64vNV = NULL;
+PFNGLVERTEXATTRIBL2UI64NVPROC __glewVertexAttribL2ui64NV = NULL;
+PFNGLVERTEXATTRIBL2UI64VNVPROC __glewVertexAttribL2ui64vNV = NULL;
+PFNGLVERTEXATTRIBL3I64NVPROC __glewVertexAttribL3i64NV = NULL;
+PFNGLVERTEXATTRIBL3I64VNVPROC __glewVertexAttribL3i64vNV = NULL;
+PFNGLVERTEXATTRIBL3UI64NVPROC __glewVertexAttribL3ui64NV = NULL;
+PFNGLVERTEXATTRIBL3UI64VNVPROC __glewVertexAttribL3ui64vNV = NULL;
+PFNGLVERTEXATTRIBL4I64NVPROC __glewVertexAttribL4i64NV = NULL;
+PFNGLVERTEXATTRIBL4I64VNVPROC __glewVertexAttribL4i64vNV = NULL;
+PFNGLVERTEXATTRIBL4UI64NVPROC __glewVertexAttribL4ui64NV = NULL;
+PFNGLVERTEXATTRIBL4UI64VNVPROC __glewVertexAttribL4ui64vNV = NULL;
+PFNGLVERTEXATTRIBLFORMATNVPROC __glewVertexAttribLFormatNV = NULL;
+
+PFNGLBUFFERADDRESSRANGENVPROC __glewBufferAddressRangeNV = NULL;
+PFNGLCOLORFORMATNVPROC __glewColorFormatNV = NULL;
+PFNGLEDGEFLAGFORMATNVPROC __glewEdgeFlagFormatNV = NULL;
+PFNGLFOGCOORDFORMATNVPROC __glewFogCoordFormatNV = NULL;
+PFNGLGETINTEGERUI64I_VNVPROC __glewGetIntegerui64i_vNV = NULL;
+PFNGLINDEXFORMATNVPROC __glewIndexFormatNV = NULL;
+PFNGLNORMALFORMATNVPROC __glewNormalFormatNV = NULL;
+PFNGLSECONDARYCOLORFORMATNVPROC __glewSecondaryColorFormatNV = NULL;
+PFNGLTEXCOORDFORMATNVPROC __glewTexCoordFormatNV = NULL;
+PFNGLVERTEXATTRIBFORMATNVPROC __glewVertexAttribFormatNV = NULL;
+PFNGLVERTEXATTRIBIFORMATNVPROC __glewVertexAttribIFormatNV = NULL;
+PFNGLVERTEXFORMATNVPROC __glewVertexFormatNV = NULL;
+
 PFNGLAREPROGRAMSRESIDENTNVPROC __glewAreProgramsResidentNV = NULL;
 PFNGLBINDPROGRAMNVPROC __glewBindProgramNV = NULL;
 PFNGLDELETEPROGRAMSNVPROC __glewDeleteProgramsNV = NULL;
@@ -1849,32 +2188,59 @@ GLboolean __GLEW_VERSION_1_5 = GL_FALSE;
 GLboolean __GLEW_VERSION_2_0 = GL_FALSE;
 GLboolean __GLEW_VERSION_2_1 = GL_FALSE;
 GLboolean __GLEW_VERSION_3_0 = GL_FALSE;
+GLboolean __GLEW_VERSION_3_1 = GL_FALSE;
+GLboolean __GLEW_VERSION_3_2 = GL_FALSE;
+GLboolean __GLEW_VERSION_3_3 = GL_FALSE;
+GLboolean __GLEW_VERSION_4_0 = GL_FALSE;
 GLboolean __GLEW_3DFX_multisample = GL_FALSE;
 GLboolean __GLEW_3DFX_tbuffer = GL_FALSE;
 GLboolean __GLEW_3DFX_texture_compression_FXT1 = GL_FALSE;
+GLboolean __GLEW_AMD_conservative_depth = GL_FALSE;
+GLboolean __GLEW_AMD_draw_buffers_blend = GL_FALSE;
+GLboolean __GLEW_AMD_performance_monitor = GL_FALSE;
+GLboolean __GLEW_AMD_seamless_cubemap_per_texture = GL_FALSE;
+GLboolean __GLEW_AMD_shader_stencil_export = GL_FALSE;
+GLboolean __GLEW_AMD_texture_texture4 = GL_FALSE;
+GLboolean __GLEW_AMD_vertex_shader_tessellator = GL_FALSE;
+GLboolean __GLEW_APPLE_aux_depth_stencil = GL_FALSE;
 GLboolean __GLEW_APPLE_client_storage = GL_FALSE;
 GLboolean __GLEW_APPLE_element_array = GL_FALSE;
 GLboolean __GLEW_APPLE_fence = GL_FALSE;
 GLboolean __GLEW_APPLE_float_pixels = GL_FALSE;
 GLboolean __GLEW_APPLE_flush_buffer_range = GL_FALSE;
+GLboolean __GLEW_APPLE_object_purgeable = GL_FALSE;
 GLboolean __GLEW_APPLE_pixel_buffer = GL_FALSE;
+GLboolean __GLEW_APPLE_rgb_422 = GL_FALSE;
+GLboolean __GLEW_APPLE_row_bytes = GL_FALSE;
 GLboolean __GLEW_APPLE_specular_vector = GL_FALSE;
 GLboolean __GLEW_APPLE_texture_range = GL_FALSE;
 GLboolean __GLEW_APPLE_transform_hint = GL_FALSE;
 GLboolean __GLEW_APPLE_vertex_array_object = GL_FALSE;
 GLboolean __GLEW_APPLE_vertex_array_range = GL_FALSE;
+GLboolean __GLEW_APPLE_vertex_program_evaluators = GL_FALSE;
 GLboolean __GLEW_APPLE_ycbcr_422 = GL_FALSE;
+GLboolean __GLEW_ARB_blend_func_extended = GL_FALSE;
 GLboolean __GLEW_ARB_color_buffer_float = GL_FALSE;
+GLboolean __GLEW_ARB_compatibility = GL_FALSE;
+GLboolean __GLEW_ARB_copy_buffer = GL_FALSE;
 GLboolean __GLEW_ARB_depth_buffer_float = GL_FALSE;
+GLboolean __GLEW_ARB_depth_clamp = GL_FALSE;
 GLboolean __GLEW_ARB_depth_texture = GL_FALSE;
 GLboolean __GLEW_ARB_draw_buffers = GL_FALSE;
+GLboolean __GLEW_ARB_draw_buffers_blend = GL_FALSE;
+GLboolean __GLEW_ARB_draw_elements_base_vertex = GL_FALSE;
+GLboolean __GLEW_ARB_draw_indirect = GL_FALSE;
 GLboolean __GLEW_ARB_draw_instanced = GL_FALSE;
+GLboolean __GLEW_ARB_explicit_attrib_location = GL_FALSE;
+GLboolean __GLEW_ARB_fragment_coord_conventions = GL_FALSE;
 GLboolean __GLEW_ARB_fragment_program = GL_FALSE;
 GLboolean __GLEW_ARB_fragment_program_shadow = GL_FALSE;
 GLboolean __GLEW_ARB_fragment_shader = GL_FALSE;
 GLboolean __GLEW_ARB_framebuffer_object = GL_FALSE;
 GLboolean __GLEW_ARB_framebuffer_sRGB = GL_FALSE;
 GLboolean __GLEW_ARB_geometry_shader4 = GL_FALSE;
+GLboolean __GLEW_ARB_gpu_shader5 = GL_FALSE;
+GLboolean __GLEW_ARB_gpu_shader_fp64 = GL_FALSE;
 GLboolean __GLEW_ARB_half_float_pixel = GL_FALSE;
 GLboolean __GLEW_ARB_half_float_vertex = GL_FALSE;
 GLboolean __GLEW_ARB_imaging = GL_FALSE;
@@ -1884,33 +2250,58 @@ GLboolean __GLEW_ARB_matrix_palette = GL_FALSE;
 GLboolean __GLEW_ARB_multisample = GL_FALSE;
 GLboolean __GLEW_ARB_multitexture = GL_FALSE;
 GLboolean __GLEW_ARB_occlusion_query = GL_FALSE;
+GLboolean __GLEW_ARB_occlusion_query2 = GL_FALSE;
 GLboolean __GLEW_ARB_pixel_buffer_object = GL_FALSE;
 GLboolean __GLEW_ARB_point_parameters = GL_FALSE;
 GLboolean __GLEW_ARB_point_sprite = GL_FALSE;
+GLboolean __GLEW_ARB_provoking_vertex = GL_FALSE;
+GLboolean __GLEW_ARB_sample_shading = GL_FALSE;
+GLboolean __GLEW_ARB_sampler_objects = GL_FALSE;
+GLboolean __GLEW_ARB_seamless_cube_map = GL_FALSE;
+GLboolean __GLEW_ARB_shader_bit_encoding = GL_FALSE;
 GLboolean __GLEW_ARB_shader_objects = GL_FALSE;
+GLboolean __GLEW_ARB_shader_subroutine = GL_FALSE;
+GLboolean __GLEW_ARB_shader_texture_lod = GL_FALSE;
 GLboolean __GLEW_ARB_shading_language_100 = GL_FALSE;
+GLboolean __GLEW_ARB_shading_language_include = GL_FALSE;
 GLboolean __GLEW_ARB_shadow = GL_FALSE;
 GLboolean __GLEW_ARB_shadow_ambient = GL_FALSE;
+GLboolean __GLEW_ARB_sync = GL_FALSE;
+GLboolean __GLEW_ARB_tessellation_shader = GL_FALSE;
 GLboolean __GLEW_ARB_texture_border_clamp = GL_FALSE;
 GLboolean __GLEW_ARB_texture_buffer_object = GL_FALSE;
+GLboolean __GLEW_ARB_texture_buffer_object_rgb32 = GL_FALSE;
 GLboolean __GLEW_ARB_texture_compression = GL_FALSE;
+GLboolean __GLEW_ARB_texture_compression_bptc = GL_FALSE;
 GLboolean __GLEW_ARB_texture_compression_rgtc = GL_FALSE;
 GLboolean __GLEW_ARB_texture_cube_map = GL_FALSE;
+GLboolean __GLEW_ARB_texture_cube_map_array = GL_FALSE;
 GLboolean __GLEW_ARB_texture_env_add = GL_FALSE;
 GLboolean __GLEW_ARB_texture_env_combine = GL_FALSE;
 GLboolean __GLEW_ARB_texture_env_crossbar = GL_FALSE;
 GLboolean __GLEW_ARB_texture_env_dot3 = GL_FALSE;
 GLboolean __GLEW_ARB_texture_float = GL_FALSE;
+GLboolean __GLEW_ARB_texture_gather = GL_FALSE;
 GLboolean __GLEW_ARB_texture_mirrored_repeat = GL_FALSE;
+GLboolean __GLEW_ARB_texture_multisample = GL_FALSE;
 GLboolean __GLEW_ARB_texture_non_power_of_two = GL_FALSE;
+GLboolean __GLEW_ARB_texture_query_lod = GL_FALSE;
 GLboolean __GLEW_ARB_texture_rectangle = GL_FALSE;
 GLboolean __GLEW_ARB_texture_rg = GL_FALSE;
+GLboolean __GLEW_ARB_texture_rgb10_a2ui = GL_FALSE;
+GLboolean __GLEW_ARB_texture_swizzle = GL_FALSE;
+GLboolean __GLEW_ARB_timer_query = GL_FALSE;
+GLboolean __GLEW_ARB_transform_feedback2 = GL_FALSE;
+GLboolean __GLEW_ARB_transform_feedback3 = GL_FALSE;
 GLboolean __GLEW_ARB_transpose_matrix = GL_FALSE;
+GLboolean __GLEW_ARB_uniform_buffer_object = GL_FALSE;
+GLboolean __GLEW_ARB_vertex_array_bgra = GL_FALSE;
 GLboolean __GLEW_ARB_vertex_array_object = GL_FALSE;
 GLboolean __GLEW_ARB_vertex_blend = GL_FALSE;
 GLboolean __GLEW_ARB_vertex_buffer_object = GL_FALSE;
 GLboolean __GLEW_ARB_vertex_program = GL_FALSE;
 GLboolean __GLEW_ARB_vertex_shader = GL_FALSE;
+GLboolean __GLEW_ARB_vertex_type_2_10_10_10_rev = GL_FALSE;
 GLboolean __GLEW_ARB_window_pos = GL_FALSE;
 GLboolean __GLEW_ATIX_point_sprites = GL_FALSE;
 GLboolean __GLEW_ATIX_texture_env_combine3 = GL_FALSE;
@@ -1921,6 +2312,7 @@ GLboolean __GLEW_ATI_element_array = GL_FALSE;
 GLboolean __GLEW_ATI_envmap_bumpmap = GL_FALSE;
 GLboolean __GLEW_ATI_fragment_shader = GL_FALSE;
 GLboolean __GLEW_ATI_map_object_buffer = GL_FALSE;
+GLboolean __GLEW_ATI_meminfo = GL_FALSE;
 GLboolean __GLEW_ATI_pn_triangles = GL_FALSE;
 GLboolean __GLEW_ATI_separate_stencil = GL_FALSE;
 GLboolean __GLEW_ATI_shader_texture_lod = GL_FALSE;
@@ -1983,10 +2375,13 @@ GLboolean __GLEW_EXT_pixel_transform = GL_FALSE;
 GLboolean __GLEW_EXT_pixel_transform_color_table = GL_FALSE;
 GLboolean __GLEW_EXT_point_parameters = GL_FALSE;
 GLboolean __GLEW_EXT_polygon_offset = GL_FALSE;
+GLboolean __GLEW_EXT_provoking_vertex = GL_FALSE;
 GLboolean __GLEW_EXT_rescale_normal = GL_FALSE;
 GLboolean __GLEW_EXT_scene_marker = GL_FALSE;
 GLboolean __GLEW_EXT_secondary_color = GL_FALSE;
+GLboolean __GLEW_EXT_separate_shader_objects = GL_FALSE;
 GLboolean __GLEW_EXT_separate_specular_color = GL_FALSE;
+GLboolean __GLEW_EXT_shader_image_load_store = GL_FALSE;
 GLboolean __GLEW_EXT_shadow_funcs = GL_FALSE;
 GLboolean __GLEW_EXT_shared_texture_palette = GL_FALSE;
 GLboolean __GLEW_EXT_stencil_clear_tag = GL_FALSE;
@@ -2016,11 +2411,13 @@ GLboolean __GLEW_EXT_texture_perturb_normal = GL_FALSE;
 GLboolean __GLEW_EXT_texture_rectangle = GL_FALSE;
 GLboolean __GLEW_EXT_texture_sRGB = GL_FALSE;
 GLboolean __GLEW_EXT_texture_shared_exponent = GL_FALSE;
+GLboolean __GLEW_EXT_texture_snorm = GL_FALSE;
 GLboolean __GLEW_EXT_texture_swizzle = GL_FALSE;
 GLboolean __GLEW_EXT_timer_query = GL_FALSE;
 GLboolean __GLEW_EXT_transform_feedback = GL_FALSE;
 GLboolean __GLEW_EXT_vertex_array = GL_FALSE;
 GLboolean __GLEW_EXT_vertex_array_bgra = GL_FALSE;
+GLboolean __GLEW_EXT_vertex_attrib_64bit = GL_FALSE;
 GLboolean __GLEW_EXT_vertex_shader = GL_FALSE;
 GLboolean __GLEW_EXT_vertex_weighting = GL_FALSE;
 GLboolean __GLEW_GREMEDY_frame_terminator = GL_FALSE;
@@ -2048,6 +2445,7 @@ GLboolean __GLEW_MESA_ycbcr_texture = GL_FALSE;
 GLboolean __GLEW_NV_blend_square = GL_FALSE;
 GLboolean __GLEW_NV_conditional_render = GL_FALSE;
 GLboolean __GLEW_NV_copy_depth_to_color = GL_FALSE;
+GLboolean __GLEW_NV_copy_image = GL_FALSE;
 GLboolean __GLEW_NV_depth_buffer_float = GL_FALSE;
 GLboolean __GLEW_NV_depth_clamp = GL_FALSE;
 GLboolean __GLEW_NV_depth_range_unclamped = GL_FALSE;
@@ -2064,20 +2462,27 @@ GLboolean __GLEW_NV_framebuffer_multisample_coverage = GL_FALSE;
 GLboolean __GLEW_NV_geometry_program4 = GL_FALSE;
 GLboolean __GLEW_NV_geometry_shader4 = GL_FALSE;
 GLboolean __GLEW_NV_gpu_program4 = GL_FALSE;
+GLboolean __GLEW_NV_gpu_program5 = GL_FALSE;
+GLboolean __GLEW_NV_gpu_program_fp64 = GL_FALSE;
+GLboolean __GLEW_NV_gpu_shader5 = GL_FALSE;
 GLboolean __GLEW_NV_half_float = GL_FALSE;
 GLboolean __GLEW_NV_light_max_exponent = GL_FALSE;
 GLboolean __GLEW_NV_multisample_filter_hint = GL_FALSE;
 GLboolean __GLEW_NV_occlusion_query = GL_FALSE;
 GLboolean __GLEW_NV_packed_depth_stencil = GL_FALSE;
 GLboolean __GLEW_NV_parameter_buffer_object = GL_FALSE;
+GLboolean __GLEW_NV_parameter_buffer_object2 = GL_FALSE;
 GLboolean __GLEW_NV_pixel_data_range = GL_FALSE;
 GLboolean __GLEW_NV_point_sprite = GL_FALSE;
 GLboolean __GLEW_NV_present_video = GL_FALSE;
 GLboolean __GLEW_NV_primitive_restart = GL_FALSE;
 GLboolean __GLEW_NV_register_combiners = GL_FALSE;
 GLboolean __GLEW_NV_register_combiners2 = GL_FALSE;
+GLboolean __GLEW_NV_shader_buffer_load = GL_FALSE;
+GLboolean __GLEW_NV_tessellation_program5 = GL_FALSE;
 GLboolean __GLEW_NV_texgen_emboss = GL_FALSE;
 GLboolean __GLEW_NV_texgen_reflection = GL_FALSE;
+GLboolean __GLEW_NV_texture_barrier = GL_FALSE;
 GLboolean __GLEW_NV_texture_compression_vtc = GL_FALSE;
 GLboolean __GLEW_NV_texture_env_combine4 = GL_FALSE;
 GLboolean __GLEW_NV_texture_expand_normal = GL_FALSE;
@@ -2086,8 +2491,11 @@ GLboolean __GLEW_NV_texture_shader = GL_FALSE;
 GLboolean __GLEW_NV_texture_shader2 = GL_FALSE;
 GLboolean __GLEW_NV_texture_shader3 = GL_FALSE;
 GLboolean __GLEW_NV_transform_feedback = GL_FALSE;
+GLboolean __GLEW_NV_transform_feedback2 = GL_FALSE;
 GLboolean __GLEW_NV_vertex_array_range = GL_FALSE;
 GLboolean __GLEW_NV_vertex_array_range2 = GL_FALSE;
+GLboolean __GLEW_NV_vertex_attrib_integer_64bit = GL_FALSE;
+GLboolean __GLEW_NV_vertex_buffer_unified_memory = GL_FALSE;
 GLboolean __GLEW_NV_vertex_program = GL_FALSE;
 GLboolean __GLEW_NV_vertex_program1_1 = GL_FALSE;
 GLboolean __GLEW_NV_vertex_program2 = GL_FALSE;
@@ -2463,8 +2871,6 @@ static GLboolean _glewInit_GL_VERSION_3_0 (GLEW_CONTEXT_ARG_DEF_INIT)
 
   r = ((glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)glewGetProcAddress((const GLubyte*)"glBeginConditionalRender")) == NULL) || r;
   r = ((glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glBeginTransformFeedback")) == NULL) || r;
-  r = ((glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)glewGetProcAddress((const GLubyte*)"glBindBufferBase")) == NULL) || r;
-  r = ((glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)glewGetProcAddress((const GLubyte*)"glBindBufferRange")) == NULL) || r;
   r = ((glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)glewGetProcAddress((const GLubyte*)"glBindFragDataLocation")) == NULL) || r;
   r = ((glClampColor = (PFNGLCLAMPCOLORPROC)glewGetProcAddress((const GLubyte*)"glClampColor")) == NULL) || r;
   r = ((glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)glewGetProcAddress((const GLubyte*)"glClearBufferfi")) == NULL) || r;
@@ -2478,7 +2884,6 @@ static GLboolean _glewInit_GL_VERSION_3_0 (GLEW_CONTEXT_ARG_DEF_INIT)
   r = ((glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glEndTransformFeedback")) == NULL) || r;
   r = ((glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)glewGetProcAddress((const GLubyte*)"glGetBooleani_v")) == NULL) || r;
   r = ((glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)glewGetProcAddress((const GLubyte*)"glGetFragDataLocation")) == NULL) || r;
-  r = ((glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)glewGetProcAddress((const GLubyte*)"glGetIntegeri_v")) == NULL) || r;
   r = ((glGetStringi = (PFNGLGETSTRINGIPROC)glewGetProcAddress((const GLubyte*)"glGetStringi")) == NULL) || r;
   r = ((glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)glewGetProcAddress((const GLubyte*)"glGetTexParameterIiv")) == NULL) || r;
   r = ((glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)glewGetProcAddress((const GLubyte*)"glGetTexParameterIuiv")) == NULL) || r;
@@ -2525,6 +2930,58 @@ static GLboolean _glewInit_GL_VERSION_3_0 (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_VERSION_3_0 */
 
+#ifdef GL_VERSION_3_1
+
+static GLboolean _glewInit_GL_VERSION_3_1 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)glewGetProcAddress((const GLubyte*)"glDrawArraysInstanced")) == NULL) || r;
+  r = ((glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)glewGetProcAddress((const GLubyte*)"glDrawElementsInstanced")) == NULL) || r;
+  r = ((glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)glewGetProcAddress((const GLubyte*)"glPrimitiveRestartIndex")) == NULL) || r;
+  r = ((glTexBuffer = (PFNGLTEXBUFFERPROC)glewGetProcAddress((const GLubyte*)"glTexBuffer")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_VERSION_3_1 */
+
+#ifdef GL_VERSION_3_2
+
+static GLboolean _glewInit_GL_VERSION_3_2 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTexture")) == NULL) || r;
+  r = ((glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)glewGetProcAddress((const GLubyte*)"glGetBufferParameteri64v")) == NULL) || r;
+  r = ((glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)glewGetProcAddress((const GLubyte*)"glGetInteger64i_v")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_VERSION_3_2 */
+
+#ifdef GL_VERSION_3_3
+
+#endif /* GL_VERSION_3_3 */
+
+#ifdef GL_VERSION_4_0
+
+static GLboolean _glewInit_GL_VERSION_4_0 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationSeparatei")) == NULL) || r;
+  r = ((glBlendEquationi = (PFNGLBLENDEQUATIONIPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationi")) == NULL) || r;
+  r = ((glBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)glewGetProcAddress((const GLubyte*)"glBlendFuncSeparatei")) == NULL) || r;
+  r = ((glBlendFunci = (PFNGLBLENDFUNCIPROC)glewGetProcAddress((const GLubyte*)"glBlendFunci")) == NULL) || r;
+  r = ((glMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)glewGetProcAddress((const GLubyte*)"glMinSampleShading")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_VERSION_4_0 */
+
 #ifdef GL_3DFX_multisample
 
 #endif /* GL_3DFX_multisample */
@@ -2546,6 +3003,79 @@ static GLboolean _glewInit_GL_3DFX_tbuffer (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_3DFX_texture_compression_FXT1 */
 
+#ifdef GL_AMD_conservative_depth
+
+#endif /* GL_AMD_conservative_depth */
+
+#ifdef GL_AMD_draw_buffers_blend
+
+static GLboolean _glewInit_GL_AMD_draw_buffers_blend (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBlendEquationIndexedAMD = (PFNGLBLENDEQUATIONINDEXEDAMDPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationIndexedAMD")) == NULL) || r;
+  r = ((glBlendEquationSeparateIndexedAMD = (PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationSeparateIndexedAMD")) == NULL) || r;
+  r = ((glBlendFuncIndexedAMD = (PFNGLBLENDFUNCINDEXEDAMDPROC)glewGetProcAddress((const GLubyte*)"glBlendFuncIndexedAMD")) == NULL) || r;
+  r = ((glBlendFuncSeparateIndexedAMD = (PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC)glewGetProcAddress((const GLubyte*)"glBlendFuncSeparateIndexedAMD")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_AMD_draw_buffers_blend */
+
+#ifdef GL_AMD_performance_monitor
+
+static GLboolean _glewInit_GL_AMD_performance_monitor (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBeginPerfMonitorAMD = (PFNGLBEGINPERFMONITORAMDPROC)glewGetProcAddress((const GLubyte*)"glBeginPerfMonitorAMD")) == NULL) || r;
+  r = ((glDeletePerfMonitorsAMD = (PFNGLDELETEPERFMONITORSAMDPROC)glewGetProcAddress((const GLubyte*)"glDeletePerfMonitorsAMD")) == NULL) || r;
+  r = ((glEndPerfMonitorAMD = (PFNGLENDPERFMONITORAMDPROC)glewGetProcAddress((const GLubyte*)"glEndPerfMonitorAMD")) == NULL) || r;
+  r = ((glGenPerfMonitorsAMD = (PFNGLGENPERFMONITORSAMDPROC)glewGetProcAddress((const GLubyte*)"glGenPerfMonitorsAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorCounterDataAMD = (PFNGLGETPERFMONITORCOUNTERDATAAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorCounterDataAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorCounterInfoAMD = (PFNGLGETPERFMONITORCOUNTERINFOAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorCounterInfoAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorCounterStringAMD = (PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorCounterStringAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorCountersAMD = (PFNGLGETPERFMONITORCOUNTERSAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorCountersAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorGroupStringAMD = (PFNGLGETPERFMONITORGROUPSTRINGAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorGroupStringAMD")) == NULL) || r;
+  r = ((glGetPerfMonitorGroupsAMD = (PFNGLGETPERFMONITORGROUPSAMDPROC)glewGetProcAddress((const GLubyte*)"glGetPerfMonitorGroupsAMD")) == NULL) || r;
+  r = ((glSelectPerfMonitorCountersAMD = (PFNGLSELECTPERFMONITORCOUNTERSAMDPROC)glewGetProcAddress((const GLubyte*)"glSelectPerfMonitorCountersAMD")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_AMD_performance_monitor */
+
+#ifdef GL_AMD_seamless_cubemap_per_texture
+
+#endif /* GL_AMD_seamless_cubemap_per_texture */
+
+#ifdef GL_AMD_shader_stencil_export
+
+#endif /* GL_AMD_shader_stencil_export */
+
+#ifdef GL_AMD_texture_texture4
+
+#endif /* GL_AMD_texture_texture4 */
+
+#ifdef GL_AMD_vertex_shader_tessellator
+
+static GLboolean _glewInit_GL_AMD_vertex_shader_tessellator (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glTessellationFactorAMD = (PFNGLTESSELLATIONFACTORAMDPROC)glewGetProcAddress((const GLubyte*)"glTessellationFactorAMD")) == NULL) || r;
+  r = ((glTessellationModeAMD = (PFNGLTESSELLATIONMODEAMDPROC)glewGetProcAddress((const GLubyte*)"glTessellationModeAMD")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_AMD_vertex_shader_tessellator */
+
+#ifdef GL_APPLE_aux_depth_stencil
+
+#endif /* GL_APPLE_aux_depth_stencil */
+
 #ifdef GL_APPLE_client_storage
 
 #endif /* GL_APPLE_client_storage */
@@ -2605,10 +3135,33 @@ static GLboolean _glewInit_GL_APPLE_flush_buffer_range (GLEW_CONTEXT_ARG_DEF_INI
 
 #endif /* GL_APPLE_flush_buffer_range */
 
+#ifdef GL_APPLE_object_purgeable
+
+static GLboolean _glewInit_GL_APPLE_object_purgeable (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetObjectParameterivAPPLE = (PFNGLGETOBJECTPARAMETERIVAPPLEPROC)glewGetProcAddress((const GLubyte*)"glGetObjectParameterivAPPLE")) == NULL) || r;
+  r = ((glObjectPurgeableAPPLE = (PFNGLOBJECTPURGEABLEAPPLEPROC)glewGetProcAddress((const GLubyte*)"glObjectPurgeableAPPLE")) == NULL) || r;
+  r = ((glObjectUnpurgeableAPPLE = (PFNGLOBJECTUNPURGEABLEAPPLEPROC)glewGetProcAddress((const GLubyte*)"glObjectUnpurgeableAPPLE")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_APPLE_object_purgeable */
+
 #ifdef GL_APPLE_pixel_buffer
 
 #endif /* GL_APPLE_pixel_buffer */
 
+#ifdef GL_APPLE_rgb_422
+
+#endif /* GL_APPLE_rgb_422 */
+
+#ifdef GL_APPLE_row_bytes
+
+#endif /* GL_APPLE_row_bytes */
+
 #ifdef GL_APPLE_specular_vector
 
 #endif /* GL_APPLE_specular_vector */
@@ -2662,10 +3215,43 @@ static GLboolean _glewInit_GL_APPLE_vertex_array_range (GLEW_CONTEXT_ARG_DEF_INI
 
 #endif /* GL_APPLE_vertex_array_range */
 
+#ifdef GL_APPLE_vertex_program_evaluators
+
+static GLboolean _glewInit_GL_APPLE_vertex_program_evaluators (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glDisableVertexAttribAPPLE = (PFNGLDISABLEVERTEXATTRIBAPPLEPROC)glewGetProcAddress((const GLubyte*)"glDisableVertexAttribAPPLE")) == NULL) || r;
+  r = ((glEnableVertexAttribAPPLE = (PFNGLENABLEVERTEXATTRIBAPPLEPROC)glewGetProcAddress((const GLubyte*)"glEnableVertexAttribAPPLE")) == NULL) || r;
+  r = ((glIsVertexAttribEnabledAPPLE = (PFNGLISVERTEXATTRIBENABLEDAPPLEPROC)glewGetProcAddress((const GLubyte*)"glIsVertexAttribEnabledAPPLE")) == NULL) || r;
+  r = ((glMapVertexAttrib1dAPPLE = (PFNGLMAPVERTEXATTRIB1DAPPLEPROC)glewGetProcAddress((const GLubyte*)"glMapVertexAttrib1dAPPLE")) == NULL) || r;
+  r = ((glMapVertexAttrib1fAPPLE = (PFNGLMAPVERTEXATTRIB1FAPPLEPROC)glewGetProcAddress((const GLubyte*)"glMapVertexAttrib1fAPPLE")) == NULL) || r;
+  r = ((glMapVertexAttrib2dAPPLE = (PFNGLMAPVERTEXATTRIB2DAPPLEPROC)glewGetProcAddress((const GLubyte*)"glMapVertexAttrib2dAPPLE")) == NULL) || r;
+  r = ((glMapVertexAttrib2fAPPLE = (PFNGLMAPVERTEXATTRIB2FAPPLEPROC)glewGetProcAddress((const GLubyte*)"glMapVertexAttrib2fAPPLE")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_APPLE_vertex_program_evaluators */
+
 #ifdef GL_APPLE_ycbcr_422
 
 #endif /* GL_APPLE_ycbcr_422 */
 
+#ifdef GL_ARB_blend_func_extended
+
+static GLboolean _glewInit_GL_ARB_blend_func_extended (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)glewGetProcAddress((const GLubyte*)"glBindFragDataLocationIndexed")) == NULL) || r;
+  r = ((glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)glewGetProcAddress((const GLubyte*)"glGetFragDataIndex")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_blend_func_extended */
+
 #ifdef GL_ARB_color_buffer_float
 
 static GLboolean _glewInit_GL_ARB_color_buffer_float (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -2679,10 +3265,31 @@ static GLboolean _glewInit_GL_ARB_color_buffer_float (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_color_buffer_float */
 
+#ifdef GL_ARB_compatibility
+
+#endif /* GL_ARB_compatibility */
+
+#ifdef GL_ARB_copy_buffer
+
+static GLboolean _glewInit_GL_ARB_copy_buffer (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)glewGetProcAddress((const GLubyte*)"glCopyBufferSubData")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_copy_buffer */
+
 #ifdef GL_ARB_depth_buffer_float
 
 #endif /* GL_ARB_depth_buffer_float */
 
+#ifdef GL_ARB_depth_clamp
+
+#endif /* GL_ARB_depth_clamp */
+
 #ifdef GL_ARB_depth_texture
 
 #endif /* GL_ARB_depth_texture */
@@ -2700,6 +3307,52 @@ static GLboolean _glewInit_GL_ARB_draw_buffers (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_draw_buffers */
 
+#ifdef GL_ARB_draw_buffers_blend
+
+static GLboolean _glewInit_GL_ARB_draw_buffers_blend (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBlendEquationSeparateiARB = (PFNGLBLENDEQUATIONSEPARATEIARBPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationSeparateiARB")) == NULL) || r;
+  r = ((glBlendEquationiARB = (PFNGLBLENDEQUATIONIARBPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationiARB")) == NULL) || r;
+  r = ((glBlendFuncSeparateiARB = (PFNGLBLENDFUNCSEPARATEIARBPROC)glewGetProcAddress((const GLubyte*)"glBlendFuncSeparateiARB")) == NULL) || r;
+  r = ((glBlendFunciARB = (PFNGLBLENDFUNCIARBPROC)glewGetProcAddress((const GLubyte*)"glBlendFunciARB")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_draw_buffers_blend */
+
+#ifdef GL_ARB_draw_elements_base_vertex
+
+static GLboolean _glewInit_GL_ARB_draw_elements_base_vertex (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)glewGetProcAddress((const GLubyte*)"glDrawElementsBaseVertex")) == NULL) || r;
+  r = ((glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)glewGetProcAddress((const GLubyte*)"glDrawElementsInstancedBaseVertex")) == NULL) || r;
+  r = ((glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)glewGetProcAddress((const GLubyte*)"glDrawRangeElementsBaseVertex")) == NULL) || r;
+  r = ((glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)glewGetProcAddress((const GLubyte*)"glMultiDrawElementsBaseVertex")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_draw_elements_base_vertex */
+
+#ifdef GL_ARB_draw_indirect
+
+static GLboolean _glewInit_GL_ARB_draw_indirect (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)glewGetProcAddress((const GLubyte*)"glDrawArraysIndirect")) == NULL) || r;
+  r = ((glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)glewGetProcAddress((const GLubyte*)"glDrawElementsIndirect")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_draw_indirect */
+
 #ifdef GL_ARB_draw_instanced
 
 static GLboolean _glewInit_GL_ARB_draw_instanced (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -2714,6 +3367,14 @@ static GLboolean _glewInit_GL_ARB_draw_instanced (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_draw_instanced */
 
+#ifdef GL_ARB_explicit_attrib_location
+
+#endif /* GL_ARB_explicit_attrib_location */
+
+#ifdef GL_ARB_fragment_coord_conventions
+
+#endif /* GL_ARB_fragment_coord_conventions */
+
 #ifdef GL_ARB_fragment_program
 
 #endif /* GL_ARB_fragment_program */
@@ -2739,10 +3400,10 @@ static GLboolean _glewInit_GL_ARB_framebuffer_object (GLEW_CONTEXT_ARG_DEF_INIT)
   r = ((glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)glewGetProcAddress((const GLubyte*)"glDeleteFramebuffers")) == NULL) || r;
   r = ((glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)glewGetProcAddress((const GLubyte*)"glDeleteRenderbuffers")) == NULL) || r;
   r = ((glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)glewGetProcAddress((const GLubyte*)"glFramebufferRenderbuffer")) == NULL) || r;
-  r = ((glFramebufferTexturLayer = (PFNGLFRAMEBUFFERTEXTURLAYERPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTexturLayer")) == NULL) || r;
   r = ((glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTexture1D")) == NULL) || r;
   r = ((glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTexture2D")) == NULL) || r;
   r = ((glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTexture3D")) == NULL) || r;
+  r = ((glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)glewGetProcAddress((const GLubyte*)"glFramebufferTextureLayer")) == NULL) || r;
   r = ((glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)glewGetProcAddress((const GLubyte*)"glGenFramebuffers")) == NULL) || r;
   r = ((glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)glewGetProcAddress((const GLubyte*)"glGenRenderbuffers")) == NULL) || r;
   r = ((glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)glewGetProcAddress((const GLubyte*)"glGenerateMipmap")) == NULL) || r;
@@ -2778,6 +3439,14 @@ static GLboolean _glewInit_GL_ARB_geometry_shader4 (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_geometry_shader4 */
 
+#ifdef GL_ARB_gpu_shader5
+
+#endif /* GL_ARB_gpu_shader5 */
+
+#ifdef GL_ARB_gpu_shader_fp64
+
+#endif /* GL_ARB_gpu_shader_fp64 */
+
 #ifdef GL_ARB_half_float_pixel
 
 #endif /* GL_ARB_half_float_pixel */
@@ -2954,6 +3623,10 @@ static GLboolean _glewInit_GL_ARB_occlusion_query (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_occlusion_query */
 
+#ifdef GL_ARB_occlusion_query2
+
+#endif /* GL_ARB_occlusion_query2 */
+
 #ifdef GL_ARB_pixel_buffer_object
 
 #endif /* GL_ARB_pixel_buffer_object */
@@ -2976,6 +3649,66 @@ static GLboolean _glewInit_GL_ARB_point_parameters (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_point_sprite */
 
+#ifdef GL_ARB_provoking_vertex
+
+static GLboolean _glewInit_GL_ARB_provoking_vertex (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)glewGetProcAddress((const GLubyte*)"glProvokingVertex")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_provoking_vertex */
+
+#ifdef GL_ARB_sample_shading
+
+static GLboolean _glewInit_GL_ARB_sample_shading (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glMinSampleShadingARB = (PFNGLMINSAMPLESHADINGARBPROC)glewGetProcAddress((const GLubyte*)"glMinSampleShadingARB")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_sample_shading */
+
+#ifdef GL_ARB_sampler_objects
+
+static GLboolean _glewInit_GL_ARB_sampler_objects (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindSampler = (PFNGLBINDSAMPLERPROC)glewGetProcAddress((const GLubyte*)"glBindSampler")) == NULL) || r;
+  r = ((glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)glewGetProcAddress((const GLubyte*)"glDeleteSamplers")) == NULL) || r;
+  r = ((glGenSamplers = (PFNGLGENSAMPLERSPROC)glewGetProcAddress((const GLubyte*)"glGenSamplers")) == NULL) || r;
+  r = ((glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)glewGetProcAddress((const GLubyte*)"glGetSamplerParameterIiv")) == NULL) || r;
+  r = ((glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)glewGetProcAddress((const GLubyte*)"glGetSamplerParameterIuiv")) == NULL) || r;
+  r = ((glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)glewGetProcAddress((const GLubyte*)"glGetSamplerParameterfv")) == NULL) || r;
+  r = ((glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)glewGetProcAddress((const GLubyte*)"glGetSamplerParameteriv")) == NULL) || r;
+  r = ((glIsSampler = (PFNGLISSAMPLERPROC)glewGetProcAddress((const GLubyte*)"glIsSampler")) == NULL) || r;
+  r = ((glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameterIiv")) == NULL) || r;
+  r = ((glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameterIuiv")) == NULL) || r;
+  r = ((glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameterf")) == NULL) || r;
+  r = ((glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameterfv")) == NULL) || r;
+  r = ((glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameteri")) == NULL) || r;
+  r = ((glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)glewGetProcAddress((const GLubyte*)"glSamplerParameteriv")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_sampler_objects */
+
+#ifdef GL_ARB_seamless_cube_map
+
+#endif /* GL_ARB_seamless_cube_map */
+
+#ifdef GL_ARB_shader_bit_encoding
+
+#endif /* GL_ARB_shader_bit_encoding */
+
 #ifdef GL_ARB_shader_objects
 
 static GLboolean _glewInit_GL_ARB_shader_objects (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -3027,10 +3760,52 @@ static GLboolean _glewInit_GL_ARB_shader_objects (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_shader_objects */
 
+#ifdef GL_ARB_shader_subroutine
+
+static GLboolean _glewInit_GL_ARB_shader_subroutine (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)glewGetProcAddress((const GLubyte*)"glGetActiveSubroutineName")) == NULL) || r;
+  r = ((glGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)glewGetProcAddress((const GLubyte*)"glGetActiveSubroutineUniformName")) == NULL) || r;
+  r = ((glGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)glewGetProcAddress((const GLubyte*)"glGetActiveSubroutineUniformiv")) == NULL) || r;
+  r = ((glGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)glewGetProcAddress((const GLubyte*)"glGetProgramStageiv")) == NULL) || r;
+  r = ((glGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)glewGetProcAddress((const GLubyte*)"glGetSubroutineIndex")) == NULL) || r;
+  r = ((glGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)glewGetProcAddress((const GLubyte*)"glGetSubroutineUniformLocation")) == NULL) || r;
+  r = ((glGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)glewGetProcAddress((const GLubyte*)"glGetUniformSubroutineuiv")) == NULL) || r;
+  r = ((glUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)glewGetProcAddress((const GLubyte*)"glUniformSubroutinesuiv")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_shader_subroutine */
+
+#ifdef GL_ARB_shader_texture_lod
+
+#endif /* GL_ARB_shader_texture_lod */
+
 #ifdef GL_ARB_shading_language_100
 
 #endif /* GL_ARB_shading_language_100 */
 
+#ifdef GL_ARB_shading_language_include
+
+static GLboolean _glewInit_GL_ARB_shading_language_include (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glCompileShaderIncludeARB = (PFNGLCOMPILESHADERINCLUDEARBPROC)glewGetProcAddress((const GLubyte*)"glCompileShaderIncludeARB")) == NULL) || r;
+  r = ((glDeleteNamedStringARB = (PFNGLDELETENAMEDSTRINGARBPROC)glewGetProcAddress((const GLubyte*)"glDeleteNamedStringARB")) == NULL) || r;
+  r = ((glGetNamedStringARB = (PFNGLGETNAMEDSTRINGARBPROC)glewGetProcAddress((const GLubyte*)"glGetNamedStringARB")) == NULL) || r;
+  r = ((glGetNamedStringivARB = (PFNGLGETNAMEDSTRINGIVARBPROC)glewGetProcAddress((const GLubyte*)"glGetNamedStringivARB")) == NULL) || r;
+  r = ((glIsNamedStringARB = (PFNGLISNAMEDSTRINGARBPROC)glewGetProcAddress((const GLubyte*)"glIsNamedStringARB")) == NULL) || r;
+  r = ((glNamedStringARB = (PFNGLNAMEDSTRINGARBPROC)glewGetProcAddress((const GLubyte*)"glNamedStringARB")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_shading_language_include */
+
 #ifdef GL_ARB_shadow
 
 #endif /* GL_ARB_shadow */
@@ -3039,22 +3814,59 @@ static GLboolean _glewInit_GL_ARB_shader_objects (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_shadow_ambient */
 
-#ifdef GL_ARB_texture_border_clamp
-
-#endif /* GL_ARB_texture_border_clamp */
-
-#ifdef GL_ARB_texture_buffer_object
+#ifdef GL_ARB_sync
 
-static GLboolean _glewInit_GL_ARB_texture_buffer_object (GLEW_CONTEXT_ARG_DEF_INIT)
+static GLboolean _glewInit_GL_ARB_sync (GLEW_CONTEXT_ARG_DEF_INIT)
 {
   GLboolean r = GL_FALSE;
 
-  r = ((glTexBufferARB = (PFNGLTEXBUFFERARBPROC)glewGetProcAddress((const GLubyte*)"glTexBufferARB")) == NULL) || r;
+  r = ((glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)glewGetProcAddress((const GLubyte*)"glClientWaitSync")) == NULL) || r;
+  r = ((glDeleteSync = (PFNGLDELETESYNCPROC)glewGetProcAddress((const GLubyte*)"glDeleteSync")) == NULL) || r;
+  r = ((glFenceSync = (PFNGLFENCESYNCPROC)glewGetProcAddress((const GLubyte*)"glFenceSync")) == NULL) || r;
+  r = ((glGetInteger64v = (PFNGLGETINTEGER64VPROC)glewGetProcAddress((const GLubyte*)"glGetInteger64v")) == NULL) || r;
+  r = ((glGetSynciv = (PFNGLGETSYNCIVPROC)glewGetProcAddress((const GLubyte*)"glGetSynciv")) == NULL) || r;
+  r = ((glIsSync = (PFNGLISSYNCPROC)glewGetProcAddress((const GLubyte*)"glIsSync")) == NULL) || r;
+  r = ((glWaitSync = (PFNGLWAITSYNCPROC)glewGetProcAddress((const GLubyte*)"glWaitSync")) == NULL) || r;
 
   return r;
 }
 
-#endif /* GL_ARB_texture_buffer_object */
+#endif /* GL_ARB_sync */
+
+#ifdef GL_ARB_tessellation_shader
+
+static GLboolean _glewInit_GL_ARB_tessellation_shader (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)glewGetProcAddress((const GLubyte*)"glPatchParameterfv")) == NULL) || r;
+  r = ((glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)glewGetProcAddress((const GLubyte*)"glPatchParameteri")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_tessellation_shader */
+
+#ifdef GL_ARB_texture_border_clamp
+
+#endif /* GL_ARB_texture_border_clamp */
+
+#ifdef GL_ARB_texture_buffer_object
+
+static GLboolean _glewInit_GL_ARB_texture_buffer_object (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glTexBufferARB = (PFNGLTEXBUFFERARBPROC)glewGetProcAddress((const GLubyte*)"glTexBufferARB")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_texture_buffer_object */
+
+#ifdef GL_ARB_texture_buffer_object_rgb32
+
+#endif /* GL_ARB_texture_buffer_object_rgb32 */
 
 #ifdef GL_ARB_texture_compression
 
@@ -3075,6 +3887,10 @@ static GLboolean _glewInit_GL_ARB_texture_compression (GLEW_CONTEXT_ARG_DEF_INIT
 
 #endif /* GL_ARB_texture_compression */
 
+#ifdef GL_ARB_texture_compression_bptc
+
+#endif /* GL_ARB_texture_compression_bptc */
+
 #ifdef GL_ARB_texture_compression_rgtc
 
 #endif /* GL_ARB_texture_compression_rgtc */
@@ -3083,6 +3899,10 @@ static GLboolean _glewInit_GL_ARB_texture_compression (GLEW_CONTEXT_ARG_DEF_INIT
 
 #endif /* GL_ARB_texture_cube_map */
 
+#ifdef GL_ARB_texture_cube_map_array
+
+#endif /* GL_ARB_texture_cube_map_array */
+
 #ifdef GL_ARB_texture_env_add
 
 #endif /* GL_ARB_texture_env_add */
@@ -3103,14 +3923,38 @@ static GLboolean _glewInit_GL_ARB_texture_compression (GLEW_CONTEXT_ARG_DEF_INIT
 
 #endif /* GL_ARB_texture_float */
 
+#ifdef GL_ARB_texture_gather
+
+#endif /* GL_ARB_texture_gather */
+
 #ifdef GL_ARB_texture_mirrored_repeat
 
 #endif /* GL_ARB_texture_mirrored_repeat */
 
+#ifdef GL_ARB_texture_multisample
+
+static GLboolean _glewInit_GL_ARB_texture_multisample (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)glewGetProcAddress((const GLubyte*)"glGetMultisamplefv")) == NULL) || r;
+  r = ((glSampleMaski = (PFNGLSAMPLEMASKIPROC)glewGetProcAddress((const GLubyte*)"glSampleMaski")) == NULL) || r;
+  r = ((glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)glewGetProcAddress((const GLubyte*)"glTexImage2DMultisample")) == NULL) || r;
+  r = ((glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)glewGetProcAddress((const GLubyte*)"glTexImage3DMultisample")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_texture_multisample */
+
 #ifdef GL_ARB_texture_non_power_of_two
 
 #endif /* GL_ARB_texture_non_power_of_two */
 
+#ifdef GL_ARB_texture_query_lod
+
+#endif /* GL_ARB_texture_query_lod */
+
 #ifdef GL_ARB_texture_rectangle
 
 #endif /* GL_ARB_texture_rectangle */
@@ -3119,6 +3963,64 @@ static GLboolean _glewInit_GL_ARB_texture_compression (GLEW_CONTEXT_ARG_DEF_INIT
 
 #endif /* GL_ARB_texture_rg */
 
+#ifdef GL_ARB_texture_rgb10_a2ui
+
+#endif /* GL_ARB_texture_rgb10_a2ui */
+
+#ifdef GL_ARB_texture_swizzle
+
+#endif /* GL_ARB_texture_swizzle */
+
+#ifdef GL_ARB_timer_query
+
+static GLboolean _glewInit_GL_ARB_timer_query (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)glewGetProcAddress((const GLubyte*)"glGetQueryObjecti64v")) == NULL) || r;
+  r = ((glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)glewGetProcAddress((const GLubyte*)"glGetQueryObjectui64v")) == NULL) || r;
+  r = ((glQueryCounter = (PFNGLQUERYCOUNTERPROC)glewGetProcAddress((const GLubyte*)"glQueryCounter")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_timer_query */
+
+#ifdef GL_ARB_transform_feedback2
+
+static GLboolean _glewInit_GL_ARB_transform_feedback2 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glBindTransformFeedback")) == NULL) || r;
+  r = ((glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)glewGetProcAddress((const GLubyte*)"glDeleteTransformFeedbacks")) == NULL) || r;
+  r = ((glDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glDrawTransformFeedback")) == NULL) || r;
+  r = ((glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)glewGetProcAddress((const GLubyte*)"glGenTransformFeedbacks")) == NULL) || r;
+  r = ((glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glIsTransformFeedback")) == NULL) || r;
+  r = ((glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glPauseTransformFeedback")) == NULL) || r;
+  r = ((glResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)glewGetProcAddress((const GLubyte*)"glResumeTransformFeedback")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_transform_feedback2 */
+
+#ifdef GL_ARB_transform_feedback3
+
+static GLboolean _glewInit_GL_ARB_transform_feedback3 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)glewGetProcAddress((const GLubyte*)"glBeginQueryIndexed")) == NULL) || r;
+  r = ((glDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)glewGetProcAddress((const GLubyte*)"glDrawTransformFeedbackStream")) == NULL) || r;
+  r = ((glEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)glewGetProcAddress((const GLubyte*)"glEndQueryIndexed")) == NULL) || r;
+  r = ((glGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)glewGetProcAddress((const GLubyte*)"glGetQueryIndexediv")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_transform_feedback3 */
+
 #ifdef GL_ARB_transpose_matrix
 
 static GLboolean _glewInit_GL_ARB_transpose_matrix (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -3135,6 +4037,32 @@ static GLboolean _glewInit_GL_ARB_transpose_matrix (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_transpose_matrix */
 
+#ifdef GL_ARB_uniform_buffer_object
+
+static GLboolean _glewInit_GL_ARB_uniform_buffer_object (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)glewGetProcAddress((const GLubyte*)"glBindBufferBase")) == NULL) || r;
+  r = ((glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)glewGetProcAddress((const GLubyte*)"glBindBufferRange")) == NULL) || r;
+  r = ((glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)glewGetProcAddress((const GLubyte*)"glGetActiveUniformBlockName")) == NULL) || r;
+  r = ((glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)glewGetProcAddress((const GLubyte*)"glGetActiveUniformBlockiv")) == NULL) || r;
+  r = ((glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)glewGetProcAddress((const GLubyte*)"glGetActiveUniformName")) == NULL) || r;
+  r = ((glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)glewGetProcAddress((const GLubyte*)"glGetActiveUniformsiv")) == NULL) || r;
+  r = ((glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)glewGetProcAddress((const GLubyte*)"glGetIntegeri_v")) == NULL) || r;
+  r = ((glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)glewGetProcAddress((const GLubyte*)"glGetUniformBlockIndex")) == NULL) || r;
+  r = ((glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)glewGetProcAddress((const GLubyte*)"glGetUniformIndices")) == NULL) || r;
+  r = ((glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)glewGetProcAddress((const GLubyte*)"glUniformBlockBinding")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_uniform_buffer_object */
+
+#ifdef GL_ARB_vertex_array_bgra
+
+#endif /* GL_ARB_vertex_array_bgra */
+
 #ifdef GL_ARB_vertex_array_object
 
 static GLboolean _glewInit_GL_ARB_vertex_array_object (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -3285,6 +4213,56 @@ static GLboolean _glewInit_GL_ARB_vertex_shader (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ARB_vertex_shader */
 
+#ifdef GL_ARB_vertex_type_2_10_10_10_rev
+
+static GLboolean _glewInit_GL_ARB_vertex_type_2_10_10_10_rev (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glColorP3ui = (PFNGLCOLORP3UIPROC)glewGetProcAddress((const GLubyte*)"glColorP3ui")) == NULL) || r;
+  r = ((glColorP3uiv = (PFNGLCOLORP3UIVPROC)glewGetProcAddress((const GLubyte*)"glColorP3uiv")) == NULL) || r;
+  r = ((glColorP4ui = (PFNGLCOLORP4UIPROC)glewGetProcAddress((const GLubyte*)"glColorP4ui")) == NULL) || r;
+  r = ((glColorP4uiv = (PFNGLCOLORP4UIVPROC)glewGetProcAddress((const GLubyte*)"glColorP4uiv")) == NULL) || r;
+  r = ((glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP1ui")) == NULL) || r;
+  r = ((glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP1uiv")) == NULL) || r;
+  r = ((glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP2ui")) == NULL) || r;
+  r = ((glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP2uiv")) == NULL) || r;
+  r = ((glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP3ui")) == NULL) || r;
+  r = ((glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP3uiv")) == NULL) || r;
+  r = ((glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP4ui")) == NULL) || r;
+  r = ((glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)glewGetProcAddress((const GLubyte*)"glMultiTexCoordP4uiv")) == NULL) || r;
+  r = ((glNormalP3ui = (PFNGLNORMALP3UIPROC)glewGetProcAddress((const GLubyte*)"glNormalP3ui")) == NULL) || r;
+  r = ((glNormalP3uiv = (PFNGLNORMALP3UIVPROC)glewGetProcAddress((const GLubyte*)"glNormalP3uiv")) == NULL) || r;
+  r = ((glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)glewGetProcAddress((const GLubyte*)"glSecondaryColorP3ui")) == NULL) || r;
+  r = ((glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)glewGetProcAddress((const GLubyte*)"glSecondaryColorP3uiv")) == NULL) || r;
+  r = ((glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP1ui")) == NULL) || r;
+  r = ((glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP1uiv")) == NULL) || r;
+  r = ((glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP2ui")) == NULL) || r;
+  r = ((glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP2uiv")) == NULL) || r;
+  r = ((glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP3ui")) == NULL) || r;
+  r = ((glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP3uiv")) == NULL) || r;
+  r = ((glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP4ui")) == NULL) || r;
+  r = ((glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)glewGetProcAddress((const GLubyte*)"glTexCoordP4uiv")) == NULL) || r;
+  r = ((glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP1ui")) == NULL) || r;
+  r = ((glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP1uiv")) == NULL) || r;
+  r = ((glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP2ui")) == NULL) || r;
+  r = ((glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP2uiv")) == NULL) || r;
+  r = ((glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP3ui")) == NULL) || r;
+  r = ((glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP3uiv")) == NULL) || r;
+  r = ((glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP4ui")) == NULL) || r;
+  r = ((glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribP4uiv")) == NULL) || r;
+  r = ((glVertexP2ui = (PFNGLVERTEXP2UIPROC)glewGetProcAddress((const GLubyte*)"glVertexP2ui")) == NULL) || r;
+  r = ((glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexP2uiv")) == NULL) || r;
+  r = ((glVertexP3ui = (PFNGLVERTEXP3UIPROC)glewGetProcAddress((const GLubyte*)"glVertexP3ui")) == NULL) || r;
+  r = ((glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexP3uiv")) == NULL) || r;
+  r = ((glVertexP4ui = (PFNGLVERTEXP4UIPROC)glewGetProcAddress((const GLubyte*)"glVertexP4ui")) == NULL) || r;
+  r = ((glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexP4uiv")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_ARB_vertex_type_2_10_10_10_rev */
+
 #ifdef GL_ARB_window_pos
 
 static GLboolean _glewInit_GL_ARB_window_pos (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -3413,6 +4391,10 @@ static GLboolean _glewInit_GL_ATI_map_object_buffer (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_ATI_map_object_buffer */
 
+#ifdef GL_ATI_meminfo
+
+#endif /* GL_ATI_meminfo */
+
 #ifdef GL_ATI_pn_triangles
 
 static GLboolean _glewInit_GL_ATI_pn_triangles (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -3795,7 +4777,14 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glCopyTextureSubImage2DEXT = (PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC)glewGetProcAddress((const GLubyte*)"glCopyTextureSubImage2DEXT")) == NULL) || r;
   r = ((glCopyTextureSubImage3DEXT = (PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC)glewGetProcAddress((const GLubyte*)"glCopyTextureSubImage3DEXT")) == NULL) || r;
   r = ((glDisableClientStateIndexedEXT = (PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC)glewGetProcAddress((const GLubyte*)"glDisableClientStateIndexedEXT")) == NULL) || r;
+  r = ((glDisableClientStateiEXT = (PFNGLDISABLECLIENTSTATEIEXTPROC)glewGetProcAddress((const GLubyte*)"glDisableClientStateiEXT")) == NULL) || r;
+  r = ((glDisableVertexArrayAttribEXT = (PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC)glewGetProcAddress((const GLubyte*)"glDisableVertexArrayAttribEXT")) == NULL) || r;
+  r = ((glDisableVertexArrayEXT = (PFNGLDISABLEVERTEXARRAYEXTPROC)glewGetProcAddress((const GLubyte*)"glDisableVertexArrayEXT")) == NULL) || r;
   r = ((glEnableClientStateIndexedEXT = (PFNGLENABLECLIENTSTATEINDEXEDEXTPROC)glewGetProcAddress((const GLubyte*)"glEnableClientStateIndexedEXT")) == NULL) || r;
+  r = ((glEnableClientStateiEXT = (PFNGLENABLECLIENTSTATEIEXTPROC)glewGetProcAddress((const GLubyte*)"glEnableClientStateiEXT")) == NULL) || r;
+  r = ((glEnableVertexArrayAttribEXT = (PFNGLENABLEVERTEXARRAYATTRIBEXTPROC)glewGetProcAddress((const GLubyte*)"glEnableVertexArrayAttribEXT")) == NULL) || r;
+  r = ((glEnableVertexArrayEXT = (PFNGLENABLEVERTEXARRAYEXTPROC)glewGetProcAddress((const GLubyte*)"glEnableVertexArrayEXT")) == NULL) || r;
+  r = ((glFlushMappedNamedBufferRangeEXT = (PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC)glewGetProcAddress((const GLubyte*)"glFlushMappedNamedBufferRangeEXT")) == NULL) || r;
   r = ((glFramebufferDrawBufferEXT = (PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC)glewGetProcAddress((const GLubyte*)"glFramebufferDrawBufferEXT")) == NULL) || r;
   r = ((glFramebufferDrawBuffersEXT = (PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC)glewGetProcAddress((const GLubyte*)"glFramebufferDrawBuffersEXT")) == NULL) || r;
   r = ((glFramebufferReadBufferEXT = (PFNGLFRAMEBUFFERREADBUFFEREXTPROC)glewGetProcAddress((const GLubyte*)"glFramebufferReadBufferEXT")) == NULL) || r;
@@ -3804,7 +4793,9 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glGetCompressedMultiTexImageEXT = (PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC)glewGetProcAddress((const GLubyte*)"glGetCompressedMultiTexImageEXT")) == NULL) || r;
   r = ((glGetCompressedTextureImageEXT = (PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC)glewGetProcAddress((const GLubyte*)"glGetCompressedTextureImageEXT")) == NULL) || r;
   r = ((glGetDoubleIndexedvEXT = (PFNGLGETDOUBLEINDEXEDVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetDoubleIndexedvEXT")) == NULL) || r;
+  r = ((glGetDoublei_vEXT = (PFNGLGETDOUBLEI_VEXTPROC)glewGetProcAddress((const GLubyte*)"glGetDoublei_vEXT")) == NULL) || r;
   r = ((glGetFloatIndexedvEXT = (PFNGLGETFLOATINDEXEDVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetFloatIndexedvEXT")) == NULL) || r;
+  r = ((glGetFloati_vEXT = (PFNGLGETFLOATI_VEXTPROC)glewGetProcAddress((const GLubyte*)"glGetFloati_vEXT")) == NULL) || r;
   r = ((glGetFramebufferParameterivEXT = (PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetFramebufferParameterivEXT")) == NULL) || r;
   r = ((glGetMultiTexEnvfvEXT = (PFNGLGETMULTITEXENVFVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetMultiTexEnvfvEXT")) == NULL) || r;
   r = ((glGetMultiTexEnvivEXT = (PFNGLGETMULTITEXENVIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetMultiTexEnvivEXT")) == NULL) || r;
@@ -3830,6 +4821,7 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glGetNamedProgramivEXT = (PFNGLGETNAMEDPROGRAMIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetNamedProgramivEXT")) == NULL) || r;
   r = ((glGetNamedRenderbufferParameterivEXT = (PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetNamedRenderbufferParameterivEXT")) == NULL) || r;
   r = ((glGetPointerIndexedvEXT = (PFNGLGETPOINTERINDEXEDVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetPointerIndexedvEXT")) == NULL) || r;
+  r = ((glGetPointeri_vEXT = (PFNGLGETPOINTERI_VEXTPROC)glewGetProcAddress((const GLubyte*)"glGetPointeri_vEXT")) == NULL) || r;
   r = ((glGetTextureImageEXT = (PFNGLGETTEXTUREIMAGEEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureImageEXT")) == NULL) || r;
   r = ((glGetTextureLevelParameterfvEXT = (PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureLevelParameterfvEXT")) == NULL) || r;
   r = ((glGetTextureLevelParameterivEXT = (PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureLevelParameterivEXT")) == NULL) || r;
@@ -3837,7 +4829,12 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glGetTextureParameterIuivEXT = (PFNGLGETTEXTUREPARAMETERIUIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureParameterIuivEXT")) == NULL) || r;
   r = ((glGetTextureParameterfvEXT = (PFNGLGETTEXTUREPARAMETERFVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureParameterfvEXT")) == NULL) || r;
   r = ((glGetTextureParameterivEXT = (PFNGLGETTEXTUREPARAMETERIVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetTextureParameterivEXT")) == NULL) || r;
+  r = ((glGetVertexArrayIntegeri_vEXT = (PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC)glewGetProcAddress((const GLubyte*)"glGetVertexArrayIntegeri_vEXT")) == NULL) || r;
+  r = ((glGetVertexArrayIntegervEXT = (PFNGLGETVERTEXARRAYINTEGERVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetVertexArrayIntegervEXT")) == NULL) || r;
+  r = ((glGetVertexArrayPointeri_vEXT = (PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC)glewGetProcAddress((const GLubyte*)"glGetVertexArrayPointeri_vEXT")) == NULL) || r;
+  r = ((glGetVertexArrayPointervEXT = (PFNGLGETVERTEXARRAYPOINTERVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetVertexArrayPointervEXT")) == NULL) || r;
   r = ((glMapNamedBufferEXT = (PFNGLMAPNAMEDBUFFEREXTPROC)glewGetProcAddress((const GLubyte*)"glMapNamedBufferEXT")) == NULL) || r;
+  r = ((glMapNamedBufferRangeEXT = (PFNGLMAPNAMEDBUFFERRANGEEXTPROC)glewGetProcAddress((const GLubyte*)"glMapNamedBufferRangeEXT")) == NULL) || r;
   r = ((glMatrixFrustumEXT = (PFNGLMATRIXFRUSTUMEXTPROC)glewGetProcAddress((const GLubyte*)"glMatrixFrustumEXT")) == NULL) || r;
   r = ((glMatrixLoadIdentityEXT = (PFNGLMATRIXLOADIDENTITYEXTPROC)glewGetProcAddress((const GLubyte*)"glMatrixLoadIdentityEXT")) == NULL) || r;
   r = ((glMatrixLoadTransposedEXT = (PFNGLMATRIXLOADTRANSPOSEDEXTPROC)glewGetProcAddress((const GLubyte*)"glMatrixLoadTransposedEXT")) == NULL) || r;
@@ -3884,6 +4881,7 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glMultiTexSubImage3DEXT = (PFNGLMULTITEXSUBIMAGE3DEXTPROC)glewGetProcAddress((const GLubyte*)"glMultiTexSubImage3DEXT")) == NULL) || r;
   r = ((glNamedBufferDataEXT = (PFNGLNAMEDBUFFERDATAEXTPROC)glewGetProcAddress((const GLubyte*)"glNamedBufferDataEXT")) == NULL) || r;
   r = ((glNamedBufferSubDataEXT = (PFNGLNAMEDBUFFERSUBDATAEXTPROC)glewGetProcAddress((const GLubyte*)"glNamedBufferSubDataEXT")) == NULL) || r;
+  r = ((glNamedCopyBufferSubDataEXT = (PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC)glewGetProcAddress((const GLubyte*)"glNamedCopyBufferSubDataEXT")) == NULL) || r;
   r = ((glNamedFramebufferRenderbufferEXT = (PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC)glewGetProcAddress((const GLubyte*)"glNamedFramebufferRenderbufferEXT")) == NULL) || r;
   r = ((glNamedFramebufferTexture1DEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC)glewGetProcAddress((const GLubyte*)"glNamedFramebufferTexture1DEXT")) == NULL) || r;
   r = ((glNamedFramebufferTexture2DEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC)glewGetProcAddress((const GLubyte*)"glNamedFramebufferTexture2DEXT")) == NULL) || r;
@@ -3955,6 +4953,17 @@ static GLboolean _glewInit_GL_EXT_direct_state_access (GLEW_CONTEXT_ARG_DEF_INIT
   r = ((glTextureSubImage2DEXT = (PFNGLTEXTURESUBIMAGE2DEXTPROC)glewGetProcAddress((const GLubyte*)"glTextureSubImage2DEXT")) == NULL) || r;
   r = ((glTextureSubImage3DEXT = (PFNGLTEXTURESUBIMAGE3DEXTPROC)glewGetProcAddress((const GLubyte*)"glTextureSubImage3DEXT")) == NULL) || r;
   r = ((glUnmapNamedBufferEXT = (PFNGLUNMAPNAMEDBUFFEREXTPROC)glewGetProcAddress((const GLubyte*)"glUnmapNamedBufferEXT")) == NULL) || r;
+  r = ((glVertexArrayColorOffsetEXT = (PFNGLVERTEXARRAYCOLOROFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayColorOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayEdgeFlagOffsetEXT = (PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayEdgeFlagOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayFogCoordOffsetEXT = (PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayFogCoordOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayIndexOffsetEXT = (PFNGLVERTEXARRAYINDEXOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayIndexOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayMultiTexCoordOffsetEXT = (PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayMultiTexCoordOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayNormalOffsetEXT = (PFNGLVERTEXARRAYNORMALOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayNormalOffsetEXT")) == NULL) || r;
+  r = ((glVertexArraySecondaryColorOffsetEXT = (PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArraySecondaryColorOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayTexCoordOffsetEXT = (PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayTexCoordOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayVertexAttribIOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayVertexAttribIOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayVertexAttribOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayVertexAttribOffsetEXT")) == NULL) || r;
+  r = ((glVertexArrayVertexOffsetEXT = (PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayVertexOffsetEXT")) == NULL) || r;
 
   return r;
 }
@@ -4372,6 +5381,19 @@ static GLboolean _glewInit_GL_EXT_polygon_offset (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_EXT_polygon_offset */
 
+#ifdef GL_EXT_provoking_vertex
+
+static GLboolean _glewInit_GL_EXT_provoking_vertex (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glProvokingVertexEXT = (PFNGLPROVOKINGVERTEXEXTPROC)glewGetProcAddress((const GLubyte*)"glProvokingVertexEXT")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_EXT_provoking_vertex */
+
 #ifdef GL_EXT_rescale_normal
 
 #endif /* GL_EXT_rescale_normal */
@@ -4419,10 +5441,39 @@ static GLboolean _glewInit_GL_EXT_secondary_color (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_EXT_secondary_color */
 
+#ifdef GL_EXT_separate_shader_objects
+
+static GLboolean _glewInit_GL_EXT_separate_shader_objects (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glActiveProgramEXT = (PFNGLACTIVEPROGRAMEXTPROC)glewGetProcAddress((const GLubyte*)"glActiveProgramEXT")) == NULL) || r;
+  r = ((glCreateShaderProgramEXT = (PFNGLCREATESHADERPROGRAMEXTPROC)glewGetProcAddress((const GLubyte*)"glCreateShaderProgramEXT")) == NULL) || r;
+  r = ((glUseShaderProgramEXT = (PFNGLUSESHADERPROGRAMEXTPROC)glewGetProcAddress((const GLubyte*)"glUseShaderProgramEXT")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_EXT_separate_shader_objects */
+
 #ifdef GL_EXT_separate_specular_color
 
 #endif /* GL_EXT_separate_specular_color */
 
+#ifdef GL_EXT_shader_image_load_store
+
+static GLboolean _glewInit_GL_EXT_shader_image_load_store (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindImageTextureEXT = (PFNGLBINDIMAGETEXTUREEXTPROC)glewGetProcAddress((const GLubyte*)"glBindImageTextureEXT")) == NULL) || r;
+  r = ((glMemoryBarrierEXT = (PFNGLMEMORYBARRIEREXTPROC)glewGetProcAddress((const GLubyte*)"glMemoryBarrierEXT")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_EXT_shader_image_load_store */
+
 #ifdef GL_EXT_shadow_funcs
 
 #endif /* GL_EXT_shadow_funcs */
@@ -4614,6 +5665,10 @@ static GLboolean _glewInit_GL_EXT_texture_perturb_normal (GLEW_CONTEXT_ARG_DEF_I
 
 #endif /* GL_EXT_texture_shared_exponent */
 
+#ifdef GL_EXT_texture_snorm
+
+#endif /* GL_EXT_texture_snorm */
+
 #ifdef GL_EXT_texture_swizzle
 
 #endif /* GL_EXT_texture_swizzle */
@@ -4676,6 +5731,29 @@ static GLboolean _glewInit_GL_EXT_vertex_array (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_EXT_vertex_array_bgra */
 
+#ifdef GL_EXT_vertex_attrib_64bit
+
+static GLboolean _glewInit_GL_EXT_vertex_attrib_64bit (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetVertexAttribLdvEXT = (PFNGLGETVERTEXATTRIBLDVEXTPROC)glewGetProcAddress((const GLubyte*)"glGetVertexAttribLdvEXT")) == NULL) || r;
+  r = ((glVertexArrayVertexAttribLOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexArrayVertexAttribLOffsetEXT")) == NULL) || r;
+  r = ((glVertexAttribL1dEXT = (PFNGLVERTEXATTRIBL1DEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1dEXT")) == NULL) || r;
+  r = ((glVertexAttribL1dvEXT = (PFNGLVERTEXATTRIBL1DVEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1dvEXT")) == NULL) || r;
+  r = ((glVertexAttribL2dEXT = (PFNGLVERTEXATTRIBL2DEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2dEXT")) == NULL) || r;
+  r = ((glVertexAttribL2dvEXT = (PFNGLVERTEXATTRIBL2DVEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2dvEXT")) == NULL) || r;
+  r = ((glVertexAttribL3dEXT = (PFNGLVERTEXATTRIBL3DEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3dEXT")) == NULL) || r;
+  r = ((glVertexAttribL3dvEXT = (PFNGLVERTEXATTRIBL3DVEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3dvEXT")) == NULL) || r;
+  r = ((glVertexAttribL4dEXT = (PFNGLVERTEXATTRIBL4DEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4dEXT")) == NULL) || r;
+  r = ((glVertexAttribL4dvEXT = (PFNGLVERTEXATTRIBL4DVEXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4dvEXT")) == NULL) || r;
+  r = ((glVertexAttribLPointerEXT = (PFNGLVERTEXATTRIBLPOINTEREXTPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribLPointerEXT")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_EXT_vertex_attrib_64bit */
+
 #ifdef GL_EXT_vertex_shader
 
 static GLboolean _glewInit_GL_EXT_vertex_shader (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -4989,6 +6067,19 @@ static GLboolean _glewInit_GL_NV_conditional_render (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_copy_depth_to_color */
 
+#ifdef GL_NV_copy_image
+
+static GLboolean _glewInit_GL_NV_copy_image (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glCopyImageSubDataNV = (PFNGLCOPYIMAGESUBDATANVPROC)glewGetProcAddress((const GLubyte*)"glCopyImageSubDataNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_copy_image */
+
 #ifdef GL_NV_depth_buffer_float
 
 static GLboolean _glewInit_GL_NV_depth_buffer_float (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -5159,6 +6250,60 @@ static GLboolean _glewInit_GL_NV_gpu_program4 (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_gpu_program4 */
 
+#ifdef GL_NV_gpu_program5
+
+#endif /* GL_NV_gpu_program5 */
+
+#ifdef GL_NV_gpu_program_fp64
+
+#endif /* GL_NV_gpu_program_fp64 */
+
+#ifdef GL_NV_gpu_shader5
+
+static GLboolean _glewInit_GL_NV_gpu_shader5 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetUniformi64vNV = (PFNGLGETUNIFORMI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetUniformi64vNV")) == NULL) || r;
+  r = ((glGetUniformui64vNV = (PFNGLGETUNIFORMUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetUniformui64vNV")) == NULL) || r;
+  r = ((glProgramUniform1i64NV = (PFNGLPROGRAMUNIFORM1I64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform1i64NV")) == NULL) || r;
+  r = ((glProgramUniform1i64vNV = (PFNGLPROGRAMUNIFORM1I64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform1i64vNV")) == NULL) || r;
+  r = ((glProgramUniform1ui64NV = (PFNGLPROGRAMUNIFORM1UI64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform1ui64NV")) == NULL) || r;
+  r = ((glProgramUniform1ui64vNV = (PFNGLPROGRAMUNIFORM1UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform1ui64vNV")) == NULL) || r;
+  r = ((glProgramUniform2i64NV = (PFNGLPROGRAMUNIFORM2I64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform2i64NV")) == NULL) || r;
+  r = ((glProgramUniform2i64vNV = (PFNGLPROGRAMUNIFORM2I64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform2i64vNV")) == NULL) || r;
+  r = ((glProgramUniform2ui64NV = (PFNGLPROGRAMUNIFORM2UI64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform2ui64NV")) == NULL) || r;
+  r = ((glProgramUniform2ui64vNV = (PFNGLPROGRAMUNIFORM2UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform2ui64vNV")) == NULL) || r;
+  r = ((glProgramUniform3i64NV = (PFNGLPROGRAMUNIFORM3I64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform3i64NV")) == NULL) || r;
+  r = ((glProgramUniform3i64vNV = (PFNGLPROGRAMUNIFORM3I64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform3i64vNV")) == NULL) || r;
+  r = ((glProgramUniform3ui64NV = (PFNGLPROGRAMUNIFORM3UI64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform3ui64NV")) == NULL) || r;
+  r = ((glProgramUniform3ui64vNV = (PFNGLPROGRAMUNIFORM3UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform3ui64vNV")) == NULL) || r;
+  r = ((glProgramUniform4i64NV = (PFNGLPROGRAMUNIFORM4I64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform4i64NV")) == NULL) || r;
+  r = ((glProgramUniform4i64vNV = (PFNGLPROGRAMUNIFORM4I64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform4i64vNV")) == NULL) || r;
+  r = ((glProgramUniform4ui64NV = (PFNGLPROGRAMUNIFORM4UI64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform4ui64NV")) == NULL) || r;
+  r = ((glProgramUniform4ui64vNV = (PFNGLPROGRAMUNIFORM4UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniform4ui64vNV")) == NULL) || r;
+  r = ((glUniform1i64NV = (PFNGLUNIFORM1I64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform1i64NV")) == NULL) || r;
+  r = ((glUniform1i64vNV = (PFNGLUNIFORM1I64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform1i64vNV")) == NULL) || r;
+  r = ((glUniform1ui64NV = (PFNGLUNIFORM1UI64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform1ui64NV")) == NULL) || r;
+  r = ((glUniform1ui64vNV = (PFNGLUNIFORM1UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform1ui64vNV")) == NULL) || r;
+  r = ((glUniform2i64NV = (PFNGLUNIFORM2I64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform2i64NV")) == NULL) || r;
+  r = ((glUniform2i64vNV = (PFNGLUNIFORM2I64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform2i64vNV")) == NULL) || r;
+  r = ((glUniform2ui64NV = (PFNGLUNIFORM2UI64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform2ui64NV")) == NULL) || r;
+  r = ((glUniform2ui64vNV = (PFNGLUNIFORM2UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform2ui64vNV")) == NULL) || r;
+  r = ((glUniform3i64NV = (PFNGLUNIFORM3I64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform3i64NV")) == NULL) || r;
+  r = ((glUniform3i64vNV = (PFNGLUNIFORM3I64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform3i64vNV")) == NULL) || r;
+  r = ((glUniform3ui64NV = (PFNGLUNIFORM3UI64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform3ui64NV")) == NULL) || r;
+  r = ((glUniform3ui64vNV = (PFNGLUNIFORM3UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform3ui64vNV")) == NULL) || r;
+  r = ((glUniform4i64NV = (PFNGLUNIFORM4I64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform4i64NV")) == NULL) || r;
+  r = ((glUniform4i64vNV = (PFNGLUNIFORM4I64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform4i64vNV")) == NULL) || r;
+  r = ((glUniform4ui64NV = (PFNGLUNIFORM4UI64NVPROC)glewGetProcAddress((const GLubyte*)"glUniform4ui64NV")) == NULL) || r;
+  r = ((glUniform4ui64vNV = (PFNGLUNIFORM4UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniform4ui64vNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_gpu_shader5 */
+
 #ifdef GL_NV_half_float
 
 static GLboolean _glewInit_GL_NV_half_float (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -5263,6 +6408,10 @@ static GLboolean _glewInit_GL_NV_parameter_buffer_object (GLEW_CONTEXT_ARG_DEF_I
 
 #endif /* GL_NV_parameter_buffer_object */
 
+#ifdef GL_NV_parameter_buffer_object2
+
+#endif /* GL_NV_parameter_buffer_object2 */
+
 #ifdef GL_NV_pixel_data_range
 
 static GLboolean _glewInit_GL_NV_pixel_data_range (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -5303,7 +6452,6 @@ static GLboolean _glewInit_GL_NV_present_video (GLEW_CONTEXT_ARG_DEF_INIT)
   r = ((glGetVideouivNV = (PFNGLGETVIDEOUIVNVPROC)glewGetProcAddress((const GLubyte*)"glGetVideouivNV")) == NULL) || r;
   r = ((glPresentFrameDualFillNV = (PFNGLPRESENTFRAMEDUALFILLNVPROC)glewGetProcAddress((const GLubyte*)"glPresentFrameDualFillNV")) == NULL) || r;
   r = ((glPresentFrameKeyedNV = (PFNGLPRESENTFRAMEKEYEDNVPROC)glewGetProcAddress((const GLubyte*)"glPresentFrameKeyedNV")) == NULL) || r;
-  r = ((glVideoParameterivNV = (PFNGLVIDEOPARAMETERIVNVPROC)glewGetProcAddress((const GLubyte*)"glVideoParameterivNV")) == NULL) || r;
 
   return r;
 }
@@ -5363,6 +6511,35 @@ static GLboolean _glewInit_GL_NV_register_combiners2 (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_register_combiners2 */
 
+#ifdef GL_NV_shader_buffer_load
+
+static GLboolean _glewInit_GL_NV_shader_buffer_load (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetBufferParameterui64vNV = (PFNGLGETBUFFERPARAMETERUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetBufferParameterui64vNV")) == NULL) || r;
+  r = ((glGetIntegerui64vNV = (PFNGLGETINTEGERUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetIntegerui64vNV")) == NULL) || r;
+  r = ((glGetNamedBufferParameterui64vNV = (PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetNamedBufferParameterui64vNV")) == NULL) || r;
+  r = ((glIsBufferResidentNV = (PFNGLISBUFFERRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glIsBufferResidentNV")) == NULL) || r;
+  r = ((glIsNamedBufferResidentNV = (PFNGLISNAMEDBUFFERRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glIsNamedBufferResidentNV")) == NULL) || r;
+  r = ((glMakeBufferNonResidentNV = (PFNGLMAKEBUFFERNONRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glMakeBufferNonResidentNV")) == NULL) || r;
+  r = ((glMakeBufferResidentNV = (PFNGLMAKEBUFFERRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glMakeBufferResidentNV")) == NULL) || r;
+  r = ((glMakeNamedBufferNonResidentNV = (PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glMakeNamedBufferNonResidentNV")) == NULL) || r;
+  r = ((glMakeNamedBufferResidentNV = (PFNGLMAKENAMEDBUFFERRESIDENTNVPROC)glewGetProcAddress((const GLubyte*)"glMakeNamedBufferResidentNV")) == NULL) || r;
+  r = ((glProgramUniformui64NV = (PFNGLPROGRAMUNIFORMUI64NVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniformui64NV")) == NULL) || r;
+  r = ((glProgramUniformui64vNV = (PFNGLPROGRAMUNIFORMUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glProgramUniformui64vNV")) == NULL) || r;
+  r = ((glUniformui64NV = (PFNGLUNIFORMUI64NVPROC)glewGetProcAddress((const GLubyte*)"glUniformui64NV")) == NULL) || r;
+  r = ((glUniformui64vNV = (PFNGLUNIFORMUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glUniformui64vNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_shader_buffer_load */
+
+#ifdef GL_NV_tessellation_program5
+
+#endif /* GL_NV_tessellation_program5 */
+
 #ifdef GL_NV_texgen_emboss
 
 #endif /* GL_NV_texgen_emboss */
@@ -5371,6 +6548,19 @@ static GLboolean _glewInit_GL_NV_register_combiners2 (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_texgen_reflection */
 
+#ifdef GL_NV_texture_barrier
+
+static GLboolean _glewInit_GL_NV_texture_barrier (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glTextureBarrierNV = (PFNGLTEXTUREBARRIERNVPROC)glewGetProcAddress((const GLubyte*)"glTextureBarrierNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_texture_barrier */
+
 #ifdef GL_NV_texture_compression_vtc
 
 #endif /* GL_NV_texture_compression_vtc */
@@ -5422,6 +6612,25 @@ static GLboolean _glewInit_GL_NV_transform_feedback (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_transform_feedback */
 
+#ifdef GL_NV_transform_feedback2
+
+static GLboolean _glewInit_GL_NV_transform_feedback2 (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBindTransformFeedbackNV = (PFNGLBINDTRANSFORMFEEDBACKNVPROC)glewGetProcAddress((const GLubyte*)"glBindTransformFeedbackNV")) == NULL) || r;
+  r = ((glDeleteTransformFeedbacksNV = (PFNGLDELETETRANSFORMFEEDBACKSNVPROC)glewGetProcAddress((const GLubyte*)"glDeleteTransformFeedbacksNV")) == NULL) || r;
+  r = ((glDrawTransformFeedbackNV = (PFNGLDRAWTRANSFORMFEEDBACKNVPROC)glewGetProcAddress((const GLubyte*)"glDrawTransformFeedbackNV")) == NULL) || r;
+  r = ((glGenTransformFeedbacksNV = (PFNGLGENTRANSFORMFEEDBACKSNVPROC)glewGetProcAddress((const GLubyte*)"glGenTransformFeedbacksNV")) == NULL) || r;
+  r = ((glIsTransformFeedbackNV = (PFNGLISTRANSFORMFEEDBACKNVPROC)glewGetProcAddress((const GLubyte*)"glIsTransformFeedbackNV")) == NULL) || r;
+  r = ((glPauseTransformFeedbackNV = (PFNGLPAUSETRANSFORMFEEDBACKNVPROC)glewGetProcAddress((const GLubyte*)"glPauseTransformFeedbackNV")) == NULL) || r;
+  r = ((glResumeTransformFeedbackNV = (PFNGLRESUMETRANSFORMFEEDBACKNVPROC)glewGetProcAddress((const GLubyte*)"glResumeTransformFeedbackNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_transform_feedback2 */
+
 #ifdef GL_NV_vertex_array_range
 
 static GLboolean _glewInit_GL_NV_vertex_array_range (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -5440,6 +6649,61 @@ static GLboolean _glewInit_GL_NV_vertex_array_range (GLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GL_NV_vertex_array_range2 */
 
+#ifdef GL_NV_vertex_attrib_integer_64bit
+
+static GLboolean _glewInit_GL_NV_vertex_attrib_integer_64bit (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glGetVertexAttribLi64vNV = (PFNGLGETVERTEXATTRIBLI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetVertexAttribLi64vNV")) == NULL) || r;
+  r = ((glGetVertexAttribLui64vNV = (PFNGLGETVERTEXATTRIBLUI64VNVPROC)glewGetProcAddress((const GLubyte*)"glGetVertexAttribLui64vNV")) == NULL) || r;
+  r = ((glVertexAttribL1i64NV = (PFNGLVERTEXATTRIBL1I64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1i64NV")) == NULL) || r;
+  r = ((glVertexAttribL1i64vNV = (PFNGLVERTEXATTRIBL1I64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1i64vNV")) == NULL) || r;
+  r = ((glVertexAttribL1ui64NV = (PFNGLVERTEXATTRIBL1UI64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1ui64NV")) == NULL) || r;
+  r = ((glVertexAttribL1ui64vNV = (PFNGLVERTEXATTRIBL1UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL1ui64vNV")) == NULL) || r;
+  r = ((glVertexAttribL2i64NV = (PFNGLVERTEXATTRIBL2I64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2i64NV")) == NULL) || r;
+  r = ((glVertexAttribL2i64vNV = (PFNGLVERTEXATTRIBL2I64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2i64vNV")) == NULL) || r;
+  r = ((glVertexAttribL2ui64NV = (PFNGLVERTEXATTRIBL2UI64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2ui64NV")) == NULL) || r;
+  r = ((glVertexAttribL2ui64vNV = (PFNGLVERTEXATTRIBL2UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL2ui64vNV")) == NULL) || r;
+  r = ((glVertexAttribL3i64NV = (PFNGLVERTEXATTRIBL3I64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3i64NV")) == NULL) || r;
+  r = ((glVertexAttribL3i64vNV = (PFNGLVERTEXATTRIBL3I64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3i64vNV")) == NULL) || r;
+  r = ((glVertexAttribL3ui64NV = (PFNGLVERTEXATTRIBL3UI64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3ui64NV")) == NULL) || r;
+  r = ((glVertexAttribL3ui64vNV = (PFNGLVERTEXATTRIBL3UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL3ui64vNV")) == NULL) || r;
+  r = ((glVertexAttribL4i64NV = (PFNGLVERTEXATTRIBL4I64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4i64NV")) == NULL) || r;
+  r = ((glVertexAttribL4i64vNV = (PFNGLVERTEXATTRIBL4I64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4i64vNV")) == NULL) || r;
+  r = ((glVertexAttribL4ui64NV = (PFNGLVERTEXATTRIBL4UI64NVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4ui64NV")) == NULL) || r;
+  r = ((glVertexAttribL4ui64vNV = (PFNGLVERTEXATTRIBL4UI64VNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribL4ui64vNV")) == NULL) || r;
+  r = ((glVertexAttribLFormatNV = (PFNGLVERTEXATTRIBLFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribLFormatNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_vertex_attrib_integer_64bit */
+
+#ifdef GL_NV_vertex_buffer_unified_memory
+
+static GLboolean _glewInit_GL_NV_vertex_buffer_unified_memory (GLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glBufferAddressRangeNV = (PFNGLBUFFERADDRESSRANGENVPROC)glewGetProcAddress((const GLubyte*)"glBufferAddressRangeNV")) == NULL) || r;
+  r = ((glColorFormatNV = (PFNGLCOLORFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glColorFormatNV")) == NULL) || r;
+  r = ((glEdgeFlagFormatNV = (PFNGLEDGEFLAGFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glEdgeFlagFormatNV")) == NULL) || r;
+  r = ((glFogCoordFormatNV = (PFNGLFOGCOORDFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glFogCoordFormatNV")) == NULL) || r;
+  r = ((glGetIntegerui64i_vNV = (PFNGLGETINTEGERUI64I_VNVPROC)glewGetProcAddress((const GLubyte*)"glGetIntegerui64i_vNV")) == NULL) || r;
+  r = ((glIndexFormatNV = (PFNGLINDEXFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glIndexFormatNV")) == NULL) || r;
+  r = ((glNormalFormatNV = (PFNGLNORMALFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glNormalFormatNV")) == NULL) || r;
+  r = ((glSecondaryColorFormatNV = (PFNGLSECONDARYCOLORFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glSecondaryColorFormatNV")) == NULL) || r;
+  r = ((glTexCoordFormatNV = (PFNGLTEXCOORDFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glTexCoordFormatNV")) == NULL) || r;
+  r = ((glVertexAttribFormatNV = (PFNGLVERTEXATTRIBFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribFormatNV")) == NULL) || r;
+  r = ((glVertexAttribIFormatNV = (PFNGLVERTEXATTRIBIFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribIFormatNV")) == NULL) || r;
+  r = ((glVertexFormatNV = (PFNGLVERTEXFORMATNVPROC)glewGetProcAddress((const GLubyte*)"glVertexFormatNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GL_NV_vertex_buffer_unified_memory */
+
 #ifdef GL_NV_vertex_program
 
 static GLboolean _glewInit_GL_NV_vertex_program (GLEW_CONTEXT_ARG_DEF_INIT)
@@ -6153,81 +7417,41 @@ static
 GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 {
   const GLubyte* s;
-  GLuint dot, major, minor;
+  GLuint dot;
+  GLint major, minor;
   /* query opengl version */
   s = glGetString(GL_VERSION);
   dot = _glewStrCLen(s, '.');
-  major = dot-1;
-  minor = dot+1;
-  if (dot == 0 || s[minor] == '\0')
+  if (dot == 0)
+    return GLEW_ERROR_NO_GL_VERSION;
+  
+  major = s[dot-1]-'0';
+  minor = s[dot+1]-'0';
+
+  if (minor < 0 || minor > 9)
+    minor = 0;
+  if (major<0 || major>9)
     return GLEW_ERROR_NO_GL_VERSION;
-  if (s[major] == '1' && s[minor] == '0')
+  
+
+  if (major == 1 && minor == 0)
   {
-	return GLEW_ERROR_GL_VERSION_10_ONLY;
+    return GLEW_ERROR_GL_VERSION_10_ONLY;
   }
   else
   {
-    CONST_CAST(GLEW_VERSION_1_1) = GL_TRUE;
-	if (s[major] >= '2')
-	{
-      CONST_CAST(GLEW_VERSION_1_2) = GL_TRUE;
-      CONST_CAST(GLEW_VERSION_1_3) = GL_TRUE;
-      CONST_CAST(GLEW_VERSION_1_4) = GL_TRUE;
-	  CONST_CAST(GLEW_VERSION_1_5) = GL_TRUE;
-	  CONST_CAST(GLEW_VERSION_2_0) = GL_TRUE;
-	  if (s[minor] >= '1')
-	  {
-	    CONST_CAST(GLEW_VERSION_2_1) = GL_TRUE;
-      }
-	}
-	else
-	{
-	  if (s[minor] >= '5')
-	  {
-		CONST_CAST(GLEW_VERSION_1_2) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_3) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_4) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_5) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_2_0) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_1) = GL_FALSE;
-	  }
-	  if (s[minor] == '4')
-	  {
-		CONST_CAST(GLEW_VERSION_1_2) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_3) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_4) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_5) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_0) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_1) = GL_FALSE;
-	  }
-	  if (s[minor] == '3')
-	  {
-		CONST_CAST(GLEW_VERSION_1_2) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_3) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_4) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_5) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_0) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_1) = GL_FALSE;
-	  }
-	  if (s[minor] == '2')
-	  {
-		CONST_CAST(GLEW_VERSION_1_2) = GL_TRUE;
-		CONST_CAST(GLEW_VERSION_1_3) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_4) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_5) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_0) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_1) = GL_FALSE;
-	  }
-	  if (s[minor] < '2')
-	  {
-		CONST_CAST(GLEW_VERSION_1_2) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_3) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_4) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_1_5) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_0) = GL_FALSE;
-		CONST_CAST(GLEW_VERSION_2_1) = GL_FALSE;
-	  }
-	}
+    CONST_CAST(GLEW_VERSION_4_0) = ( major > 4 )               || ( major == 4               ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_3_3) = GLEW_VERSION_4_0 == GL_TRUE || ( major == 3 && minor >= 3 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_3_2) = GLEW_VERSION_3_3 == GL_TRUE || ( major == 3 && minor >= 2 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_3_1) = GLEW_VERSION_3_2 == GL_TRUE || ( major == 3 && minor >= 1 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_3_0) = GLEW_VERSION_3_1 == GL_TRUE || ( major == 3               ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_2_1) = GLEW_VERSION_3_0 == GL_TRUE || ( major == 2 && minor >= 1 ) ? GL_TRUE : GL_FALSE;    
+    CONST_CAST(GLEW_VERSION_2_0) = GLEW_VERSION_2_1 == GL_TRUE || ( major == 2               ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_1_5) = GLEW_VERSION_2_0 == GL_TRUE || ( major == 1 && minor >= 5 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_1_4) = GLEW_VERSION_1_5 == GL_TRUE || ( major == 1 && minor >= 4 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_1_3) = GLEW_VERSION_1_4 == GL_TRUE || ( major == 1 && minor >= 3 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_1_2) = GLEW_VERSION_1_3 == GL_TRUE || ( major == 1 && minor >= 2 ) ? GL_TRUE : GL_FALSE;
+    CONST_CAST(GLEW_VERSION_1_1) = GLEW_VERSION_1_2 == GL_TRUE || ( major == 1 && minor >= 1 ) ? GL_TRUE : GL_FALSE;
   }
   /* initialize extensions */
 #ifdef GL_VERSION_1_2
@@ -6251,6 +7475,17 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_VERSION_3_0
   if (glewExperimental || GLEW_VERSION_3_0) CONST_CAST(GLEW_VERSION_3_0) = !_glewInit_GL_VERSION_3_0(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_VERSION_3_0 */
+#ifdef GL_VERSION_3_1
+  if (glewExperimental || GLEW_VERSION_3_1) CONST_CAST(GLEW_VERSION_3_1) = !_glewInit_GL_VERSION_3_1(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_VERSION_3_1 */
+#ifdef GL_VERSION_3_2
+  if (glewExperimental || GLEW_VERSION_3_2) CONST_CAST(GLEW_VERSION_3_2) = !_glewInit_GL_VERSION_3_2(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_VERSION_3_2 */
+#ifdef GL_VERSION_3_3
+#endif /* GL_VERSION_3_3 */
+#ifdef GL_VERSION_4_0
+  if (glewExperimental || GLEW_VERSION_4_0) CONST_CAST(GLEW_VERSION_4_0) = !_glewInit_GL_VERSION_4_0(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_VERSION_4_0 */
 #ifdef GL_3DFX_multisample
   CONST_CAST(GLEW_3DFX_multisample) = glewGetExtension("GL_3DFX_multisample");
 #endif /* GL_3DFX_multisample */
@@ -6261,6 +7496,33 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_3DFX_texture_compression_FXT1
   CONST_CAST(GLEW_3DFX_texture_compression_FXT1) = glewGetExtension("GL_3DFX_texture_compression_FXT1");
 #endif /* GL_3DFX_texture_compression_FXT1 */
+#ifdef GL_AMD_conservative_depth
+  CONST_CAST(GLEW_AMD_conservative_depth) = glewGetExtension("GL_AMD_conservative_depth");
+#endif /* GL_AMD_conservative_depth */
+#ifdef GL_AMD_draw_buffers_blend
+  CONST_CAST(GLEW_AMD_draw_buffers_blend) = glewGetExtension("GL_AMD_draw_buffers_blend");
+  if (glewExperimental || GLEW_AMD_draw_buffers_blend) CONST_CAST(GLEW_AMD_draw_buffers_blend) = !_glewInit_GL_AMD_draw_buffers_blend(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_AMD_draw_buffers_blend */
+#ifdef GL_AMD_performance_monitor
+  CONST_CAST(GLEW_AMD_performance_monitor) = glewGetExtension("GL_AMD_performance_monitor");
+  if (glewExperimental || GLEW_AMD_performance_monitor) CONST_CAST(GLEW_AMD_performance_monitor) = !_glewInit_GL_AMD_performance_monitor(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_AMD_performance_monitor */
+#ifdef GL_AMD_seamless_cubemap_per_texture
+  CONST_CAST(GLEW_AMD_seamless_cubemap_per_texture) = glewGetExtension("GL_AMD_seamless_cubemap_per_texture");
+#endif /* GL_AMD_seamless_cubemap_per_texture */
+#ifdef GL_AMD_shader_stencil_export
+  CONST_CAST(GLEW_AMD_shader_stencil_export) = glewGetExtension("GL_AMD_shader_stencil_export");
+#endif /* GL_AMD_shader_stencil_export */
+#ifdef GL_AMD_texture_texture4
+  CONST_CAST(GLEW_AMD_texture_texture4) = glewGetExtension("GL_AMD_texture_texture4");
+#endif /* GL_AMD_texture_texture4 */
+#ifdef GL_AMD_vertex_shader_tessellator
+  CONST_CAST(GLEW_AMD_vertex_shader_tessellator) = glewGetExtension("GL_AMD_vertex_shader_tessellator");
+  if (glewExperimental || GLEW_AMD_vertex_shader_tessellator) CONST_CAST(GLEW_AMD_vertex_shader_tessellator) = !_glewInit_GL_AMD_vertex_shader_tessellator(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_AMD_vertex_shader_tessellator */
+#ifdef GL_APPLE_aux_depth_stencil
+  CONST_CAST(GLEW_APPLE_aux_depth_stencil) = glewGetExtension("GL_APPLE_aux_depth_stencil");
+#endif /* GL_APPLE_aux_depth_stencil */
 #ifdef GL_APPLE_client_storage
   CONST_CAST(GLEW_APPLE_client_storage) = glewGetExtension("GL_APPLE_client_storage");
 #endif /* GL_APPLE_client_storage */
@@ -6279,9 +7541,19 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_APPLE_flush_buffer_range) = glewGetExtension("GL_APPLE_flush_buffer_range");
   if (glewExperimental || GLEW_APPLE_flush_buffer_range) CONST_CAST(GLEW_APPLE_flush_buffer_range) = !_glewInit_GL_APPLE_flush_buffer_range(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_APPLE_flush_buffer_range */
+#ifdef GL_APPLE_object_purgeable
+  CONST_CAST(GLEW_APPLE_object_purgeable) = glewGetExtension("GL_APPLE_object_purgeable");
+  if (glewExperimental || GLEW_APPLE_object_purgeable) CONST_CAST(GLEW_APPLE_object_purgeable) = !_glewInit_GL_APPLE_object_purgeable(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_APPLE_object_purgeable */
 #ifdef GL_APPLE_pixel_buffer
   CONST_CAST(GLEW_APPLE_pixel_buffer) = glewGetExtension("GL_APPLE_pixel_buffer");
 #endif /* GL_APPLE_pixel_buffer */
+#ifdef GL_APPLE_rgb_422
+  CONST_CAST(GLEW_APPLE_rgb_422) = glewGetExtension("GL_APPLE_rgb_422");
+#endif /* GL_APPLE_rgb_422 */
+#ifdef GL_APPLE_row_bytes
+  CONST_CAST(GLEW_APPLE_row_bytes) = glewGetExtension("GL_APPLE_row_bytes");
+#endif /* GL_APPLE_row_bytes */
 #ifdef GL_APPLE_specular_vector
   CONST_CAST(GLEW_APPLE_specular_vector) = glewGetExtension("GL_APPLE_specular_vector");
 #endif /* GL_APPLE_specular_vector */
@@ -6300,16 +7572,34 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_APPLE_vertex_array_range) = glewGetExtension("GL_APPLE_vertex_array_range");
   if (glewExperimental || GLEW_APPLE_vertex_array_range) CONST_CAST(GLEW_APPLE_vertex_array_range) = !_glewInit_GL_APPLE_vertex_array_range(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_APPLE_vertex_array_range */
+#ifdef GL_APPLE_vertex_program_evaluators
+  CONST_CAST(GLEW_APPLE_vertex_program_evaluators) = glewGetExtension("GL_APPLE_vertex_program_evaluators");
+  if (glewExperimental || GLEW_APPLE_vertex_program_evaluators) CONST_CAST(GLEW_APPLE_vertex_program_evaluators) = !_glewInit_GL_APPLE_vertex_program_evaluators(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_APPLE_vertex_program_evaluators */
 #ifdef GL_APPLE_ycbcr_422
   CONST_CAST(GLEW_APPLE_ycbcr_422) = glewGetExtension("GL_APPLE_ycbcr_422");
 #endif /* GL_APPLE_ycbcr_422 */
+#ifdef GL_ARB_blend_func_extended
+  CONST_CAST(GLEW_ARB_blend_func_extended) = glewGetExtension("GL_ARB_blend_func_extended");
+  if (glewExperimental || GLEW_ARB_blend_func_extended) CONST_CAST(GLEW_ARB_blend_func_extended) = !_glewInit_GL_ARB_blend_func_extended(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_blend_func_extended */
 #ifdef GL_ARB_color_buffer_float
   CONST_CAST(GLEW_ARB_color_buffer_float) = glewGetExtension("GL_ARB_color_buffer_float");
   if (glewExperimental || GLEW_ARB_color_buffer_float) CONST_CAST(GLEW_ARB_color_buffer_float) = !_glewInit_GL_ARB_color_buffer_float(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_color_buffer_float */
+#ifdef GL_ARB_compatibility
+  CONST_CAST(GLEW_ARB_compatibility) = glewGetExtension("GL_ARB_compatibility");
+#endif /* GL_ARB_compatibility */
+#ifdef GL_ARB_copy_buffer
+  CONST_CAST(GLEW_ARB_copy_buffer) = glewGetExtension("GL_ARB_copy_buffer");
+  if (glewExperimental || GLEW_ARB_copy_buffer) CONST_CAST(GLEW_ARB_copy_buffer) = !_glewInit_GL_ARB_copy_buffer(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_copy_buffer */
 #ifdef GL_ARB_depth_buffer_float
   CONST_CAST(GLEW_ARB_depth_buffer_float) = glewGetExtension("GL_ARB_depth_buffer_float");
 #endif /* GL_ARB_depth_buffer_float */
+#ifdef GL_ARB_depth_clamp
+  CONST_CAST(GLEW_ARB_depth_clamp) = glewGetExtension("GL_ARB_depth_clamp");
+#endif /* GL_ARB_depth_clamp */
 #ifdef GL_ARB_depth_texture
   CONST_CAST(GLEW_ARB_depth_texture) = glewGetExtension("GL_ARB_depth_texture");
 #endif /* GL_ARB_depth_texture */
@@ -6317,10 +7607,28 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ARB_draw_buffers) = glewGetExtension("GL_ARB_draw_buffers");
   if (glewExperimental || GLEW_ARB_draw_buffers) CONST_CAST(GLEW_ARB_draw_buffers) = !_glewInit_GL_ARB_draw_buffers(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_draw_buffers */
+#ifdef GL_ARB_draw_buffers_blend
+  CONST_CAST(GLEW_ARB_draw_buffers_blend) = glewGetExtension("GL_ARB_draw_buffers_blend");
+  if (glewExperimental || GLEW_ARB_draw_buffers_blend) CONST_CAST(GLEW_ARB_draw_buffers_blend) = !_glewInit_GL_ARB_draw_buffers_blend(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_draw_buffers_blend */
+#ifdef GL_ARB_draw_elements_base_vertex
+  CONST_CAST(GLEW_ARB_draw_elements_base_vertex) = glewGetExtension("GL_ARB_draw_elements_base_vertex");
+  if (glewExperimental || GLEW_ARB_draw_elements_base_vertex) CONST_CAST(GLEW_ARB_draw_elements_base_vertex) = !_glewInit_GL_ARB_draw_elements_base_vertex(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_draw_elements_base_vertex */
+#ifdef GL_ARB_draw_indirect
+  CONST_CAST(GLEW_ARB_draw_indirect) = glewGetExtension("GL_ARB_draw_indirect");
+  if (glewExperimental || GLEW_ARB_draw_indirect) CONST_CAST(GLEW_ARB_draw_indirect) = !_glewInit_GL_ARB_draw_indirect(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_draw_indirect */
 #ifdef GL_ARB_draw_instanced
   CONST_CAST(GLEW_ARB_draw_instanced) = glewGetExtension("GL_ARB_draw_instanced");
   if (glewExperimental || GLEW_ARB_draw_instanced) CONST_CAST(GLEW_ARB_draw_instanced) = !_glewInit_GL_ARB_draw_instanced(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_draw_instanced */
+#ifdef GL_ARB_explicit_attrib_location
+  CONST_CAST(GLEW_ARB_explicit_attrib_location) = glewGetExtension("GL_ARB_explicit_attrib_location");
+#endif /* GL_ARB_explicit_attrib_location */
+#ifdef GL_ARB_fragment_coord_conventions
+  CONST_CAST(GLEW_ARB_fragment_coord_conventions) = glewGetExtension("GL_ARB_fragment_coord_conventions");
+#endif /* GL_ARB_fragment_coord_conventions */
 #ifdef GL_ARB_fragment_program
   CONST_CAST(GLEW_ARB_fragment_program) = glewGetExtension("GL_ARB_fragment_program");
 #endif /* GL_ARB_fragment_program */
@@ -6341,6 +7649,12 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ARB_geometry_shader4) = glewGetExtension("GL_ARB_geometry_shader4");
   if (glewExperimental || GLEW_ARB_geometry_shader4) CONST_CAST(GLEW_ARB_geometry_shader4) = !_glewInit_GL_ARB_geometry_shader4(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_geometry_shader4 */
+#ifdef GL_ARB_gpu_shader5
+  CONST_CAST(GLEW_ARB_gpu_shader5) = glewGetExtension("GL_ARB_gpu_shader5");
+#endif /* GL_ARB_gpu_shader5 */
+#ifdef GL_ARB_gpu_shader_fp64
+  CONST_CAST(GLEW_ARB_gpu_shader_fp64) = glewGetExtension("GL_ARB_gpu_shader_fp64");
+#endif /* GL_ARB_gpu_shader_fp64 */
 #ifdef GL_ARB_half_float_pixel
   CONST_CAST(GLEW_ARB_half_float_pixel) = glewGetExtension("GL_ARB_half_float_pixel");
 #endif /* GL_ARB_half_float_pixel */
@@ -6375,6 +7689,9 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ARB_occlusion_query) = glewGetExtension("GL_ARB_occlusion_query");
   if (glewExperimental || GLEW_ARB_occlusion_query) CONST_CAST(GLEW_ARB_occlusion_query) = !_glewInit_GL_ARB_occlusion_query(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_occlusion_query */
+#ifdef GL_ARB_occlusion_query2
+  CONST_CAST(GLEW_ARB_occlusion_query2) = glewGetExtension("GL_ARB_occlusion_query2");
+#endif /* GL_ARB_occlusion_query2 */
 #ifdef GL_ARB_pixel_buffer_object
   CONST_CAST(GLEW_ARB_pixel_buffer_object) = glewGetExtension("GL_ARB_pixel_buffer_object");
 #endif /* GL_ARB_pixel_buffer_object */
@@ -6385,19 +7702,56 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_ARB_point_sprite
   CONST_CAST(GLEW_ARB_point_sprite) = glewGetExtension("GL_ARB_point_sprite");
 #endif /* GL_ARB_point_sprite */
+#ifdef GL_ARB_provoking_vertex
+  CONST_CAST(GLEW_ARB_provoking_vertex) = glewGetExtension("GL_ARB_provoking_vertex");
+  if (glewExperimental || GLEW_ARB_provoking_vertex) CONST_CAST(GLEW_ARB_provoking_vertex) = !_glewInit_GL_ARB_provoking_vertex(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_provoking_vertex */
+#ifdef GL_ARB_sample_shading
+  CONST_CAST(GLEW_ARB_sample_shading) = glewGetExtension("GL_ARB_sample_shading");
+  if (glewExperimental || GLEW_ARB_sample_shading) CONST_CAST(GLEW_ARB_sample_shading) = !_glewInit_GL_ARB_sample_shading(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_sample_shading */
+#ifdef GL_ARB_sampler_objects
+  CONST_CAST(GLEW_ARB_sampler_objects) = glewGetExtension("GL_ARB_sampler_objects");
+  if (glewExperimental || GLEW_ARB_sampler_objects) CONST_CAST(GLEW_ARB_sampler_objects) = !_glewInit_GL_ARB_sampler_objects(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_sampler_objects */
+#ifdef GL_ARB_seamless_cube_map
+  CONST_CAST(GLEW_ARB_seamless_cube_map) = glewGetExtension("GL_ARB_seamless_cube_map");
+#endif /* GL_ARB_seamless_cube_map */
+#ifdef GL_ARB_shader_bit_encoding
+  CONST_CAST(GLEW_ARB_shader_bit_encoding) = glewGetExtension("GL_ARB_shader_bit_encoding");
+#endif /* GL_ARB_shader_bit_encoding */
 #ifdef GL_ARB_shader_objects
   CONST_CAST(GLEW_ARB_shader_objects) = glewGetExtension("GL_ARB_shader_objects");
   if (glewExperimental || GLEW_ARB_shader_objects) CONST_CAST(GLEW_ARB_shader_objects) = !_glewInit_GL_ARB_shader_objects(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_shader_objects */
+#ifdef GL_ARB_shader_subroutine
+  CONST_CAST(GLEW_ARB_shader_subroutine) = glewGetExtension("GL_ARB_shader_subroutine");
+  if (glewExperimental || GLEW_ARB_shader_subroutine) CONST_CAST(GLEW_ARB_shader_subroutine) = !_glewInit_GL_ARB_shader_subroutine(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_shader_subroutine */
+#ifdef GL_ARB_shader_texture_lod
+  CONST_CAST(GLEW_ARB_shader_texture_lod) = glewGetExtension("GL_ARB_shader_texture_lod");
+#endif /* GL_ARB_shader_texture_lod */
 #ifdef GL_ARB_shading_language_100
   CONST_CAST(GLEW_ARB_shading_language_100) = glewGetExtension("GL_ARB_shading_language_100");
 #endif /* GL_ARB_shading_language_100 */
+#ifdef GL_ARB_shading_language_include
+  CONST_CAST(GLEW_ARB_shading_language_include) = glewGetExtension("GL_ARB_shading_language_include");
+  if (glewExperimental || GLEW_ARB_shading_language_include) CONST_CAST(GLEW_ARB_shading_language_include) = !_glewInit_GL_ARB_shading_language_include(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_shading_language_include */
 #ifdef GL_ARB_shadow
   CONST_CAST(GLEW_ARB_shadow) = glewGetExtension("GL_ARB_shadow");
 #endif /* GL_ARB_shadow */
 #ifdef GL_ARB_shadow_ambient
   CONST_CAST(GLEW_ARB_shadow_ambient) = glewGetExtension("GL_ARB_shadow_ambient");
 #endif /* GL_ARB_shadow_ambient */
+#ifdef GL_ARB_sync
+  CONST_CAST(GLEW_ARB_sync) = glewGetExtension("GL_ARB_sync");
+  if (glewExperimental || GLEW_ARB_sync) CONST_CAST(GLEW_ARB_sync) = !_glewInit_GL_ARB_sync(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_sync */
+#ifdef GL_ARB_tessellation_shader
+  CONST_CAST(GLEW_ARB_tessellation_shader) = glewGetExtension("GL_ARB_tessellation_shader");
+  if (glewExperimental || GLEW_ARB_tessellation_shader) CONST_CAST(GLEW_ARB_tessellation_shader) = !_glewInit_GL_ARB_tessellation_shader(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_tessellation_shader */
 #ifdef GL_ARB_texture_border_clamp
   CONST_CAST(GLEW_ARB_texture_border_clamp) = glewGetExtension("GL_ARB_texture_border_clamp");
 #endif /* GL_ARB_texture_border_clamp */
@@ -6405,16 +7759,25 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ARB_texture_buffer_object) = glewGetExtension("GL_ARB_texture_buffer_object");
   if (glewExperimental || GLEW_ARB_texture_buffer_object) CONST_CAST(GLEW_ARB_texture_buffer_object) = !_glewInit_GL_ARB_texture_buffer_object(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_texture_buffer_object */
+#ifdef GL_ARB_texture_buffer_object_rgb32
+  CONST_CAST(GLEW_ARB_texture_buffer_object_rgb32) = glewGetExtension("GL_ARB_texture_buffer_object_rgb32");
+#endif /* GL_ARB_texture_buffer_object_rgb32 */
 #ifdef GL_ARB_texture_compression
   CONST_CAST(GLEW_ARB_texture_compression) = glewGetExtension("GL_ARB_texture_compression");
   if (glewExperimental || GLEW_ARB_texture_compression) CONST_CAST(GLEW_ARB_texture_compression) = !_glewInit_GL_ARB_texture_compression(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_texture_compression */
+#ifdef GL_ARB_texture_compression_bptc
+  CONST_CAST(GLEW_ARB_texture_compression_bptc) = glewGetExtension("GL_ARB_texture_compression_bptc");
+#endif /* GL_ARB_texture_compression_bptc */
 #ifdef GL_ARB_texture_compression_rgtc
   CONST_CAST(GLEW_ARB_texture_compression_rgtc) = glewGetExtension("GL_ARB_texture_compression_rgtc");
 #endif /* GL_ARB_texture_compression_rgtc */
 #ifdef GL_ARB_texture_cube_map
   CONST_CAST(GLEW_ARB_texture_cube_map) = glewGetExtension("GL_ARB_texture_cube_map");
 #endif /* GL_ARB_texture_cube_map */
+#ifdef GL_ARB_texture_cube_map_array
+  CONST_CAST(GLEW_ARB_texture_cube_map_array) = glewGetExtension("GL_ARB_texture_cube_map_array");
+#endif /* GL_ARB_texture_cube_map_array */
 #ifdef GL_ARB_texture_env_add
   CONST_CAST(GLEW_ARB_texture_env_add) = glewGetExtension("GL_ARB_texture_env_add");
 #endif /* GL_ARB_texture_env_add */
@@ -6430,22 +7793,57 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_ARB_texture_float
   CONST_CAST(GLEW_ARB_texture_float) = glewGetExtension("GL_ARB_texture_float");
 #endif /* GL_ARB_texture_float */
+#ifdef GL_ARB_texture_gather
+  CONST_CAST(GLEW_ARB_texture_gather) = glewGetExtension("GL_ARB_texture_gather");
+#endif /* GL_ARB_texture_gather */
 #ifdef GL_ARB_texture_mirrored_repeat
   CONST_CAST(GLEW_ARB_texture_mirrored_repeat) = glewGetExtension("GL_ARB_texture_mirrored_repeat");
 #endif /* GL_ARB_texture_mirrored_repeat */
+#ifdef GL_ARB_texture_multisample
+  CONST_CAST(GLEW_ARB_texture_multisample) = glewGetExtension("GL_ARB_texture_multisample");
+  if (glewExperimental || GLEW_ARB_texture_multisample) CONST_CAST(GLEW_ARB_texture_multisample) = !_glewInit_GL_ARB_texture_multisample(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_texture_multisample */
 #ifdef GL_ARB_texture_non_power_of_two
   CONST_CAST(GLEW_ARB_texture_non_power_of_two) = glewGetExtension("GL_ARB_texture_non_power_of_two");
 #endif /* GL_ARB_texture_non_power_of_two */
+#ifdef GL_ARB_texture_query_lod
+  CONST_CAST(GLEW_ARB_texture_query_lod) = glewGetExtension("GL_ARB_texture_query_lod");
+#endif /* GL_ARB_texture_query_lod */
 #ifdef GL_ARB_texture_rectangle
   CONST_CAST(GLEW_ARB_texture_rectangle) = glewGetExtension("GL_ARB_texture_rectangle");
 #endif /* GL_ARB_texture_rectangle */
 #ifdef GL_ARB_texture_rg
   CONST_CAST(GLEW_ARB_texture_rg) = glewGetExtension("GL_ARB_texture_rg");
 #endif /* GL_ARB_texture_rg */
+#ifdef GL_ARB_texture_rgb10_a2ui
+  CONST_CAST(GLEW_ARB_texture_rgb10_a2ui) = glewGetExtension("GL_ARB_texture_rgb10_a2ui");
+#endif /* GL_ARB_texture_rgb10_a2ui */
+#ifdef GL_ARB_texture_swizzle
+  CONST_CAST(GLEW_ARB_texture_swizzle) = glewGetExtension("GL_ARB_texture_swizzle");
+#endif /* GL_ARB_texture_swizzle */
+#ifdef GL_ARB_timer_query
+  CONST_CAST(GLEW_ARB_timer_query) = glewGetExtension("GL_ARB_timer_query");
+  if (glewExperimental || GLEW_ARB_timer_query) CONST_CAST(GLEW_ARB_timer_query) = !_glewInit_GL_ARB_timer_query(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_timer_query */
+#ifdef GL_ARB_transform_feedback2
+  CONST_CAST(GLEW_ARB_transform_feedback2) = glewGetExtension("GL_ARB_transform_feedback2");
+  if (glewExperimental || GLEW_ARB_transform_feedback2) CONST_CAST(GLEW_ARB_transform_feedback2) = !_glewInit_GL_ARB_transform_feedback2(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_transform_feedback2 */
+#ifdef GL_ARB_transform_feedback3
+  CONST_CAST(GLEW_ARB_transform_feedback3) = glewGetExtension("GL_ARB_transform_feedback3");
+  if (glewExperimental || GLEW_ARB_transform_feedback3) CONST_CAST(GLEW_ARB_transform_feedback3) = !_glewInit_GL_ARB_transform_feedback3(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_transform_feedback3 */
 #ifdef GL_ARB_transpose_matrix
   CONST_CAST(GLEW_ARB_transpose_matrix) = glewGetExtension("GL_ARB_transpose_matrix");
   if (glewExperimental || GLEW_ARB_transpose_matrix) CONST_CAST(GLEW_ARB_transpose_matrix) = !_glewInit_GL_ARB_transpose_matrix(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_transpose_matrix */
+#ifdef GL_ARB_uniform_buffer_object
+  CONST_CAST(GLEW_ARB_uniform_buffer_object) = glewGetExtension("GL_ARB_uniform_buffer_object");
+  if (glewExperimental || GLEW_ARB_uniform_buffer_object) CONST_CAST(GLEW_ARB_uniform_buffer_object) = !_glewInit_GL_ARB_uniform_buffer_object(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_uniform_buffer_object */
+#ifdef GL_ARB_vertex_array_bgra
+  CONST_CAST(GLEW_ARB_vertex_array_bgra) = glewGetExtension("GL_ARB_vertex_array_bgra");
+#endif /* GL_ARB_vertex_array_bgra */
 #ifdef GL_ARB_vertex_array_object
   CONST_CAST(GLEW_ARB_vertex_array_object) = glewGetExtension("GL_ARB_vertex_array_object");
   if (glewExperimental || GLEW_ARB_vertex_array_object) CONST_CAST(GLEW_ARB_vertex_array_object) = !_glewInit_GL_ARB_vertex_array_object(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -6466,6 +7864,10 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ARB_vertex_shader) = glewGetExtension("GL_ARB_vertex_shader");
   if (glewExperimental || GLEW_ARB_vertex_shader) CONST_CAST(GLEW_ARB_vertex_shader) = !_glewInit_GL_ARB_vertex_shader(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ARB_vertex_shader */
+#ifdef GL_ARB_vertex_type_2_10_10_10_rev
+  CONST_CAST(GLEW_ARB_vertex_type_2_10_10_10_rev) = glewGetExtension("GL_ARB_vertex_type_2_10_10_10_rev");
+  if (glewExperimental || GLEW_ARB_vertex_type_2_10_10_10_rev) CONST_CAST(GLEW_ARB_vertex_type_2_10_10_10_rev) = !_glewInit_GL_ARB_vertex_type_2_10_10_10_rev(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_ARB_vertex_type_2_10_10_10_rev */
 #ifdef GL_ARB_window_pos
   CONST_CAST(GLEW_ARB_window_pos) = glewGetExtension("GL_ARB_window_pos");
   if (glewExperimental || GLEW_ARB_window_pos) CONST_CAST(GLEW_ARB_window_pos) = !_glewInit_GL_ARB_window_pos(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -6502,6 +7904,9 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_ATI_map_object_buffer) = glewGetExtension("GL_ATI_map_object_buffer");
   if (glewExperimental || GLEW_ATI_map_object_buffer) CONST_CAST(GLEW_ATI_map_object_buffer) = !_glewInit_GL_ATI_map_object_buffer(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_ATI_map_object_buffer */
+#ifdef GL_ATI_meminfo
+  CONST_CAST(GLEW_ATI_meminfo) = glewGetExtension("GL_ATI_meminfo");
+#endif /* GL_ATI_meminfo */
 #ifdef GL_ATI_pn_triangles
   CONST_CAST(GLEW_ATI_pn_triangles) = glewGetExtension("GL_ATI_pn_triangles");
   if (glewExperimental || GLEW_ATI_pn_triangles) CONST_CAST(GLEW_ATI_pn_triangles) = !_glewInit_GL_ATI_pn_triangles(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -6727,6 +8132,10 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_EXT_polygon_offset) = glewGetExtension("GL_EXT_polygon_offset");
   if (glewExperimental || GLEW_EXT_polygon_offset) CONST_CAST(GLEW_EXT_polygon_offset) = !_glewInit_GL_EXT_polygon_offset(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_EXT_polygon_offset */
+#ifdef GL_EXT_provoking_vertex
+  CONST_CAST(GLEW_EXT_provoking_vertex) = glewGetExtension("GL_EXT_provoking_vertex");
+  if (glewExperimental || GLEW_EXT_provoking_vertex) CONST_CAST(GLEW_EXT_provoking_vertex) = !_glewInit_GL_EXT_provoking_vertex(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_EXT_provoking_vertex */
 #ifdef GL_EXT_rescale_normal
   CONST_CAST(GLEW_EXT_rescale_normal) = glewGetExtension("GL_EXT_rescale_normal");
 #endif /* GL_EXT_rescale_normal */
@@ -6738,9 +8147,17 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_EXT_secondary_color) = glewGetExtension("GL_EXT_secondary_color");
   if (glewExperimental || GLEW_EXT_secondary_color) CONST_CAST(GLEW_EXT_secondary_color) = !_glewInit_GL_EXT_secondary_color(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_EXT_secondary_color */
+#ifdef GL_EXT_separate_shader_objects
+  CONST_CAST(GLEW_EXT_separate_shader_objects) = glewGetExtension("GL_EXT_separate_shader_objects");
+  if (glewExperimental || GLEW_EXT_separate_shader_objects) CONST_CAST(GLEW_EXT_separate_shader_objects) = !_glewInit_GL_EXT_separate_shader_objects(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_EXT_separate_shader_objects */
 #ifdef GL_EXT_separate_specular_color
   CONST_CAST(GLEW_EXT_separate_specular_color) = glewGetExtension("GL_EXT_separate_specular_color");
 #endif /* GL_EXT_separate_specular_color */
+#ifdef GL_EXT_shader_image_load_store
+  CONST_CAST(GLEW_EXT_shader_image_load_store) = glewGetExtension("GL_EXT_shader_image_load_store");
+  if (glewExperimental || GLEW_EXT_shader_image_load_store) CONST_CAST(GLEW_EXT_shader_image_load_store) = !_glewInit_GL_EXT_shader_image_load_store(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_EXT_shader_image_load_store */
 #ifdef GL_EXT_shadow_funcs
   CONST_CAST(GLEW_EXT_shadow_funcs) = glewGetExtension("GL_EXT_shadow_funcs");
 #endif /* GL_EXT_shadow_funcs */
@@ -6835,6 +8252,9 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_EXT_texture_shared_exponent
   CONST_CAST(GLEW_EXT_texture_shared_exponent) = glewGetExtension("GL_EXT_texture_shared_exponent");
 #endif /* GL_EXT_texture_shared_exponent */
+#ifdef GL_EXT_texture_snorm
+  CONST_CAST(GLEW_EXT_texture_snorm) = glewGetExtension("GL_EXT_texture_snorm");
+#endif /* GL_EXT_texture_snorm */
 #ifdef GL_EXT_texture_swizzle
   CONST_CAST(GLEW_EXT_texture_swizzle) = glewGetExtension("GL_EXT_texture_swizzle");
 #endif /* GL_EXT_texture_swizzle */
@@ -6853,6 +8273,10 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_EXT_vertex_array_bgra
   CONST_CAST(GLEW_EXT_vertex_array_bgra) = glewGetExtension("GL_EXT_vertex_array_bgra");
 #endif /* GL_EXT_vertex_array_bgra */
+#ifdef GL_EXT_vertex_attrib_64bit
+  CONST_CAST(GLEW_EXT_vertex_attrib_64bit) = glewGetExtension("GL_EXT_vertex_attrib_64bit");
+  if (glewExperimental || GLEW_EXT_vertex_attrib_64bit) CONST_CAST(GLEW_EXT_vertex_attrib_64bit) = !_glewInit_GL_EXT_vertex_attrib_64bit(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_EXT_vertex_attrib_64bit */
 #ifdef GL_EXT_vertex_shader
   CONST_CAST(GLEW_EXT_vertex_shader) = glewGetExtension("GL_EXT_vertex_shader");
   if (glewExperimental || GLEW_EXT_vertex_shader) CONST_CAST(GLEW_EXT_vertex_shader) = !_glewInit_GL_EXT_vertex_shader(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -6947,6 +8371,10 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_NV_copy_depth_to_color
   CONST_CAST(GLEW_NV_copy_depth_to_color) = glewGetExtension("GL_NV_copy_depth_to_color");
 #endif /* GL_NV_copy_depth_to_color */
+#ifdef GL_NV_copy_image
+  CONST_CAST(GLEW_NV_copy_image) = glewGetExtension("GL_NV_copy_image");
+  if (glewExperimental || GLEW_NV_copy_image) CONST_CAST(GLEW_NV_copy_image) = !_glewInit_GL_NV_copy_image(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_copy_image */
 #ifdef GL_NV_depth_buffer_float
   CONST_CAST(GLEW_NV_depth_buffer_float) = glewGetExtension("GL_NV_depth_buffer_float");
   if (glewExperimental || GLEW_NV_depth_buffer_float) CONST_CAST(GLEW_NV_depth_buffer_float) = !_glewInit_GL_NV_depth_buffer_float(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -6983,7 +8411,7 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_fragment_program2) = glewGetExtension("GL_NV_fragment_program2");
 #endif /* GL_NV_fragment_program2 */
 #ifdef GL_NV_fragment_program4
-  CONST_CAST(GLEW_NV_fragment_program4) = glewGetExtension("GL_NV_fragment_program4");
+  CONST_CAST(GLEW_NV_fragment_program4) = glewGetExtension("GL_NV_gpu_program4");
 #endif /* GL_NV_fragment_program4 */
 #ifdef GL_NV_fragment_program_option
   CONST_CAST(GLEW_NV_fragment_program_option) = glewGetExtension("GL_NV_fragment_program_option");
@@ -6993,7 +8421,7 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   if (glewExperimental || GLEW_NV_framebuffer_multisample_coverage) CONST_CAST(GLEW_NV_framebuffer_multisample_coverage) = !_glewInit_GL_NV_framebuffer_multisample_coverage(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_framebuffer_multisample_coverage */
 #ifdef GL_NV_geometry_program4
-  CONST_CAST(GLEW_NV_geometry_program4) = glewGetExtension("GL_NV_geometry_program4");
+  CONST_CAST(GLEW_NV_geometry_program4) = glewGetExtension("GL_NV_gpu_program4");
   if (glewExperimental || GLEW_NV_geometry_program4) CONST_CAST(GLEW_NV_geometry_program4) = !_glewInit_GL_NV_geometry_program4(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_geometry_program4 */
 #ifdef GL_NV_geometry_shader4
@@ -7003,6 +8431,16 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_gpu_program4) = glewGetExtension("GL_NV_gpu_program4");
   if (glewExperimental || GLEW_NV_gpu_program4) CONST_CAST(GLEW_NV_gpu_program4) = !_glewInit_GL_NV_gpu_program4(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_gpu_program4 */
+#ifdef GL_NV_gpu_program5
+  CONST_CAST(GLEW_NV_gpu_program5) = glewGetExtension("GL_NV_gpu_program5");
+#endif /* GL_NV_gpu_program5 */
+#ifdef GL_NV_gpu_program_fp64
+  CONST_CAST(GLEW_NV_gpu_program_fp64) = glewGetExtension("GL_NV_gpu_program_fp64");
+#endif /* GL_NV_gpu_program_fp64 */
+#ifdef GL_NV_gpu_shader5
+  CONST_CAST(GLEW_NV_gpu_shader5) = glewGetExtension("GL_NV_gpu_shader5");
+  if (glewExperimental || GLEW_NV_gpu_shader5) CONST_CAST(GLEW_NV_gpu_shader5) = !_glewInit_GL_NV_gpu_shader5(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_gpu_shader5 */
 #ifdef GL_NV_half_float
   CONST_CAST(GLEW_NV_half_float) = glewGetExtension("GL_NV_half_float");
   if (glewExperimental || GLEW_NV_half_float) CONST_CAST(GLEW_NV_half_float) = !_glewInit_GL_NV_half_float(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -7024,6 +8462,9 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_parameter_buffer_object) = glewGetExtension("GL_NV_parameter_buffer_object");
   if (glewExperimental || GLEW_NV_parameter_buffer_object) CONST_CAST(GLEW_NV_parameter_buffer_object) = !_glewInit_GL_NV_parameter_buffer_object(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_parameter_buffer_object */
+#ifdef GL_NV_parameter_buffer_object2
+  CONST_CAST(GLEW_NV_parameter_buffer_object2) = glewGetExtension("GL_NV_parameter_buffer_object2");
+#endif /* GL_NV_parameter_buffer_object2 */
 #ifdef GL_NV_pixel_data_range
   CONST_CAST(GLEW_NV_pixel_data_range) = glewGetExtension("GL_NV_pixel_data_range");
   if (glewExperimental || GLEW_NV_pixel_data_range) CONST_CAST(GLEW_NV_pixel_data_range) = !_glewInit_GL_NV_pixel_data_range(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -7048,12 +8489,23 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_register_combiners2) = glewGetExtension("GL_NV_register_combiners2");
   if (glewExperimental || GLEW_NV_register_combiners2) CONST_CAST(GLEW_NV_register_combiners2) = !_glewInit_GL_NV_register_combiners2(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_register_combiners2 */
+#ifdef GL_NV_shader_buffer_load
+  CONST_CAST(GLEW_NV_shader_buffer_load) = glewGetExtension("GL_NV_shader_buffer_load");
+  if (glewExperimental || GLEW_NV_shader_buffer_load) CONST_CAST(GLEW_NV_shader_buffer_load) = !_glewInit_GL_NV_shader_buffer_load(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_shader_buffer_load */
+#ifdef GL_NV_tessellation_program5
+  CONST_CAST(GLEW_NV_tessellation_program5) = glewGetExtension("GL_NV_gpu_program5");
+#endif /* GL_NV_tessellation_program5 */
 #ifdef GL_NV_texgen_emboss
   CONST_CAST(GLEW_NV_texgen_emboss) = glewGetExtension("GL_NV_texgen_emboss");
 #endif /* GL_NV_texgen_emboss */
 #ifdef GL_NV_texgen_reflection
   CONST_CAST(GLEW_NV_texgen_reflection) = glewGetExtension("GL_NV_texgen_reflection");
 #endif /* GL_NV_texgen_reflection */
+#ifdef GL_NV_texture_barrier
+  CONST_CAST(GLEW_NV_texture_barrier) = glewGetExtension("GL_NV_texture_barrier");
+  if (glewExperimental || GLEW_NV_texture_barrier) CONST_CAST(GLEW_NV_texture_barrier) = !_glewInit_GL_NV_texture_barrier(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_texture_barrier */
 #ifdef GL_NV_texture_compression_vtc
   CONST_CAST(GLEW_NV_texture_compression_vtc) = glewGetExtension("GL_NV_texture_compression_vtc");
 #endif /* GL_NV_texture_compression_vtc */
@@ -7079,6 +8531,10 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_transform_feedback) = glewGetExtension("GL_NV_transform_feedback");
   if (glewExperimental || GLEW_NV_transform_feedback) CONST_CAST(GLEW_NV_transform_feedback) = !_glewInit_GL_NV_transform_feedback(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GL_NV_transform_feedback */
+#ifdef GL_NV_transform_feedback2
+  CONST_CAST(GLEW_NV_transform_feedback2) = glewGetExtension("GL_NV_transform_feedback2");
+  if (glewExperimental || GLEW_NV_transform_feedback2) CONST_CAST(GLEW_NV_transform_feedback2) = !_glewInit_GL_NV_transform_feedback2(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_transform_feedback2 */
 #ifdef GL_NV_vertex_array_range
   CONST_CAST(GLEW_NV_vertex_array_range) = glewGetExtension("GL_NV_vertex_array_range");
   if (glewExperimental || GLEW_NV_vertex_array_range) CONST_CAST(GLEW_NV_vertex_array_range) = !_glewInit_GL_NV_vertex_array_range(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -7086,6 +8542,14 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GL_NV_vertex_array_range2
   CONST_CAST(GLEW_NV_vertex_array_range2) = glewGetExtension("GL_NV_vertex_array_range2");
 #endif /* GL_NV_vertex_array_range2 */
+#ifdef GL_NV_vertex_attrib_integer_64bit
+  CONST_CAST(GLEW_NV_vertex_attrib_integer_64bit) = glewGetExtension("GL_NV_vertex_attrib_integer_64bit");
+  if (glewExperimental || GLEW_NV_vertex_attrib_integer_64bit) CONST_CAST(GLEW_NV_vertex_attrib_integer_64bit) = !_glewInit_GL_NV_vertex_attrib_integer_64bit(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_vertex_attrib_integer_64bit */
+#ifdef GL_NV_vertex_buffer_unified_memory
+  CONST_CAST(GLEW_NV_vertex_buffer_unified_memory) = glewGetExtension("GL_NV_vertex_buffer_unified_memory");
+  if (glewExperimental || GLEW_NV_vertex_buffer_unified_memory) CONST_CAST(GLEW_NV_vertex_buffer_unified_memory) = !_glewInit_GL_NV_vertex_buffer_unified_memory(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GL_NV_vertex_buffer_unified_memory */
 #ifdef GL_NV_vertex_program
   CONST_CAST(GLEW_NV_vertex_program) = glewGetExtension("GL_NV_vertex_program");
   if (glewExperimental || GLEW_NV_vertex_program) CONST_CAST(GLEW_NV_vertex_program) = !_glewInit_GL_NV_vertex_program(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -7103,7 +8567,7 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLEW_NV_vertex_program3) = glewGetExtension("GL_NV_vertex_program3");
 #endif /* GL_NV_vertex_program3 */
 #ifdef GL_NV_vertex_program4
-  CONST_CAST(GLEW_NV_vertex_program4) = glewGetExtension("GL_NV_vertex_program4");
+  CONST_CAST(GLEW_NV_vertex_program4) = glewGetExtension("GL_NV_gpu_program4");
 #endif /* GL_NV_vertex_program4 */
 #ifdef GL_OES_byte_coordinates
   CONST_CAST(GLEW_OES_byte_coordinates) = glewGetExtension("GL_OES_byte_coordinates");
@@ -7352,6 +8816,16 @@ GLenum glewContextInit (GLEW_CONTEXT_ARG_DEF_LIST)
 
 PFNWGLSETSTEREOEMITTERSTATE3DLPROC __wglewSetStereoEmitterState3DL = NULL;
 
+PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC __wglewBlitContextFramebufferAMD = NULL;
+PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC __wglewCreateAssociatedContextAMD = NULL;
+PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC __wglewCreateAssociatedContextAttribsAMD = NULL;
+PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC __wglewDeleteAssociatedContextAMD = NULL;
+PFNWGLGETCONTEXTGPUIDAMDPROC __wglewGetContextGPUIDAMD = NULL;
+PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC __wglewGetCurrentAssociatedContextAMD = NULL;
+PFNWGLGETGPUIDSAMDPROC __wglewGetGPUIDsAMD = NULL;
+PFNWGLGETGPUINFOAMDPROC __wglewGetGPUInfoAMD = NULL;
+PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC __wglewMakeAssociatedContextCurrentAMD = NULL;
+
 PFNWGLCREATEBUFFERREGIONARBPROC __wglewCreateBufferRegionARB = NULL;
 PFNWGLDELETEBUFFERREGIONARBPROC __wglewDeleteBufferRegionARB = NULL;
 PFNWGLRESTOREBUFFERREGIONARBPROC __wglewRestoreBufferRegionARB = NULL;
@@ -7437,6 +8911,8 @@ PFNWGLENDFRAMETRACKINGI3DPROC __wglewEndFrameTrackingI3D = NULL;
 PFNWGLGETFRAMEUSAGEI3DPROC __wglewGetFrameUsageI3D = NULL;
 PFNWGLQUERYFRAMETRACKINGI3DPROC __wglewQueryFrameTrackingI3D = NULL;
 
+PFNWGLCOPYIMAGESUBDATANVPROC __wglewCopyImageSubDataNV = NULL;
+
 PFNWGLCREATEAFFINITYDCNVPROC __wglewCreateAffinityDCNV = NULL;
 PFNWGLDELETEDCNVPROC __wglewDeleteDCNV = NULL;
 PFNWGLENUMGPUDEVICESNVPROC __wglewEnumGpuDevicesNV = NULL;
@@ -7472,8 +8948,10 @@ PFNWGLWAITFORMSCOMLPROC __wglewWaitForMscOML = NULL;
 PFNWGLWAITFORSBCOMLPROC __wglewWaitForSbcOML = NULL;
 GLboolean __WGLEW_3DFX_multisample = GL_FALSE;
 GLboolean __WGLEW_3DL_stereo_control = GL_FALSE;
+GLboolean __WGLEW_AMD_gpu_association = GL_FALSE;
 GLboolean __WGLEW_ARB_buffer_region = GL_FALSE;
 GLboolean __WGLEW_ARB_create_context = GL_FALSE;
+GLboolean __WGLEW_ARB_create_context_profile = GL_FALSE;
 GLboolean __WGLEW_ARB_extensions_string = GL_FALSE;
 GLboolean __WGLEW_ARB_framebuffer_sRGB = GL_FALSE;
 GLboolean __WGLEW_ARB_make_current_read = GL_FALSE;
@@ -7500,6 +8978,7 @@ GLboolean __WGLEW_I3D_genlock = GL_FALSE;
 GLboolean __WGLEW_I3D_image_buffer = GL_FALSE;
 GLboolean __WGLEW_I3D_swap_frame_lock = GL_FALSE;
 GLboolean __WGLEW_I3D_swap_frame_usage = GL_FALSE;
+GLboolean __WGLEW_NV_copy_image = GL_FALSE;
 GLboolean __WGLEW_NV_float_buffer = GL_FALSE;
 GLboolean __WGLEW_NV_gpu_affinity = GL_FALSE;
 GLboolean __WGLEW_NV_present_video = GL_FALSE;
@@ -7529,6 +9008,27 @@ static GLboolean _glewInit_WGL_3DL_stereo_control (WGLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* WGL_3DL_stereo_control */
 
+#ifdef WGL_AMD_gpu_association
+
+static GLboolean _glewInit_WGL_AMD_gpu_association (WGLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((wglBlitContextFramebufferAMD = (PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC)glewGetProcAddress((const GLubyte*)"wglBlitContextFramebufferAMD")) == NULL) || r;
+  r = ((wglCreateAssociatedContextAMD = (PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC)glewGetProcAddress((const GLubyte*)"wglCreateAssociatedContextAMD")) == NULL) || r;
+  r = ((wglCreateAssociatedContextAttribsAMD = (PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC)glewGetProcAddress((const GLubyte*)"wglCreateAssociatedContextAttribsAMD")) == NULL) || r;
+  r = ((wglDeleteAssociatedContextAMD = (PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC)glewGetProcAddress((const GLubyte*)"wglDeleteAssociatedContextAMD")) == NULL) || r;
+  r = ((wglGetContextGPUIDAMD = (PFNWGLGETCONTEXTGPUIDAMDPROC)glewGetProcAddress((const GLubyte*)"wglGetContextGPUIDAMD")) == NULL) || r;
+  r = ((wglGetCurrentAssociatedContextAMD = (PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC)glewGetProcAddress((const GLubyte*)"wglGetCurrentAssociatedContextAMD")) == NULL) || r;
+  r = ((wglGetGPUIDsAMD = (PFNWGLGETGPUIDSAMDPROC)glewGetProcAddress((const GLubyte*)"wglGetGPUIDsAMD")) == NULL) || r;
+  r = ((wglGetGPUInfoAMD = (PFNWGLGETGPUINFOAMDPROC)glewGetProcAddress((const GLubyte*)"wglGetGPUInfoAMD")) == NULL) || r;
+  r = ((wglMakeAssociatedContextCurrentAMD = (PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC)glewGetProcAddress((const GLubyte*)"wglMakeAssociatedContextCurrentAMD")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* WGL_AMD_gpu_association */
+
 #ifdef WGL_ARB_buffer_region
 
 static GLboolean _glewInit_WGL_ARB_buffer_region (WGLEW_CONTEXT_ARG_DEF_INIT)
@@ -7558,6 +9058,10 @@ static GLboolean _glewInit_WGL_ARB_create_context (WGLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* WGL_ARB_create_context */
 
+#ifdef WGL_ARB_create_context_profile
+
+#endif /* WGL_ARB_create_context_profile */
+
 #ifdef WGL_ARB_extensions_string
 
 static GLboolean _glewInit_WGL_ARB_extensions_string (WGLEW_CONTEXT_ARG_DEF_INIT)
@@ -7859,6 +9363,19 @@ static GLboolean _glewInit_WGL_I3D_swap_frame_usage (WGLEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* WGL_I3D_swap_frame_usage */
 
+#ifdef WGL_NV_copy_image
+
+static GLboolean _glewInit_WGL_NV_copy_image (WGLEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((wglCopyImageSubDataNV = (PFNWGLCOPYIMAGESUBDATANVPROC)glewGetProcAddress((const GLubyte*)"wglCopyImageSubDataNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* WGL_NV_copy_image */
+
 #ifdef WGL_NV_float_buffer
 
 #endif /* WGL_NV_float_buffer */
@@ -8014,6 +9531,10 @@ GLenum wglewContextInit (WGLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(WGLEW_3DL_stereo_control) = wglewGetExtension("WGL_3DL_stereo_control");
   if (glewExperimental || WGLEW_3DL_stereo_control|| crippled) CONST_CAST(WGLEW_3DL_stereo_control)= !_glewInit_WGL_3DL_stereo_control(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* WGL_3DL_stereo_control */
+#ifdef WGL_AMD_gpu_association
+  CONST_CAST(WGLEW_AMD_gpu_association) = wglewGetExtension("WGL_AMD_gpu_association");
+  if (glewExperimental || WGLEW_AMD_gpu_association|| crippled) CONST_CAST(WGLEW_AMD_gpu_association)= !_glewInit_WGL_AMD_gpu_association(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* WGL_AMD_gpu_association */
 #ifdef WGL_ARB_buffer_region
   CONST_CAST(WGLEW_ARB_buffer_region) = wglewGetExtension("WGL_ARB_buffer_region");
   if (glewExperimental || WGLEW_ARB_buffer_region|| crippled) CONST_CAST(WGLEW_ARB_buffer_region)= !_glewInit_WGL_ARB_buffer_region(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -8022,6 +9543,9 @@ GLenum wglewContextInit (WGLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(WGLEW_ARB_create_context) = wglewGetExtension("WGL_ARB_create_context");
   if (glewExperimental || WGLEW_ARB_create_context|| crippled) CONST_CAST(WGLEW_ARB_create_context)= !_glewInit_WGL_ARB_create_context(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* WGL_ARB_create_context */
+#ifdef WGL_ARB_create_context_profile
+  CONST_CAST(WGLEW_ARB_create_context_profile) = wglewGetExtension("WGL_ARB_create_context_profile");
+#endif /* WGL_ARB_create_context_profile */
 #ifdef WGL_ARB_extensions_string
   CONST_CAST(WGLEW_ARB_extensions_string) = wglewGetExtension("WGL_ARB_extensions_string");
   if (glewExperimental || WGLEW_ARB_extensions_string|| crippled) CONST_CAST(WGLEW_ARB_extensions_string)= !_glewInit_WGL_ARB_extensions_string(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -8117,6 +9641,10 @@ GLenum wglewContextInit (WGLEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(WGLEW_I3D_swap_frame_usage) = wglewGetExtension("WGL_I3D_swap_frame_usage");
   if (glewExperimental || WGLEW_I3D_swap_frame_usage|| crippled) CONST_CAST(WGLEW_I3D_swap_frame_usage)= !_glewInit_WGL_I3D_swap_frame_usage(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* WGL_I3D_swap_frame_usage */
+#ifdef WGL_NV_copy_image
+  CONST_CAST(WGLEW_NV_copy_image) = wglewGetExtension("WGL_NV_copy_image");
+  if (glewExperimental || WGLEW_NV_copy_image|| crippled) CONST_CAST(WGLEW_NV_copy_image)= !_glewInit_WGL_NV_copy_image(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* WGL_NV_copy_image */
 #ifdef WGL_NV_float_buffer
   CONST_CAST(WGLEW_NV_float_buffer) = wglewGetExtension("WGL_NV_float_buffer");
 #endif /* WGL_NV_float_buffer */
@@ -8187,6 +9715,8 @@ PFNGLXGETCONTEXTIDEXTPROC __glewXGetContextIDEXT = NULL;
 PFNGLXIMPORTCONTEXTEXTPROC __glewXImportContextEXT = NULL;
 PFNGLXQUERYCONTEXTINFOEXTPROC __glewXQueryContextInfoEXT = NULL;
 
+PFNGLXSWAPINTERVALEXTPROC __glewXSwapIntervalEXT = NULL;
+
 PFNGLXBINDTEXIMAGEEXTPROC __glewXBindTexImageEXT = NULL;
 PFNGLXRELEASETEXIMAGEEXTPROC __glewXReleaseTexImageEXT = NULL;
 
@@ -8200,6 +9730,8 @@ PFNGLXRELEASEBUFFERSMESAPROC __glewXReleaseBuffersMESA = NULL;
 
 PFNGLXSET3DFXMODEMESAPROC __glewXSet3DfxModeMESA = NULL;
 
+PFNGLXCOPYIMAGESUBDATANVPROC __glewXCopyImageSubDataNV = NULL;
+
 PFNGLXBINDVIDEODEVICENVPROC __glewXBindVideoDeviceNV = NULL;
 PFNGLXENUMERATEVIDEODEVICESNVPROC __glewXEnumerateVideoDevicesNV = NULL;
 
@@ -8285,24 +9817,29 @@ GLboolean __GLXEW_VERSION_1_3 = GL_FALSE;
 GLboolean __GLXEW_VERSION_1_4 = GL_FALSE;
 GLboolean __GLXEW_3DFX_multisample = GL_FALSE;
 GLboolean __GLXEW_ARB_create_context = GL_FALSE;
+GLboolean __GLXEW_ARB_create_context_profile = GL_FALSE;
 GLboolean __GLXEW_ARB_fbconfig_float = GL_FALSE;
 GLboolean __GLXEW_ARB_framebuffer_sRGB = GL_FALSE;
 GLboolean __GLXEW_ARB_get_proc_address = GL_FALSE;
 GLboolean __GLXEW_ARB_multisample = GL_FALSE;
+GLboolean __GLXEW_ARB_vertex_buffer_object = GL_FALSE;
 GLboolean __GLXEW_ATI_pixel_format_float = GL_FALSE;
 GLboolean __GLXEW_ATI_render_texture = GL_FALSE;
 GLboolean __GLXEW_EXT_fbconfig_packed_float = GL_FALSE;
 GLboolean __GLXEW_EXT_framebuffer_sRGB = GL_FALSE;
 GLboolean __GLXEW_EXT_import_context = GL_FALSE;
 GLboolean __GLXEW_EXT_scene_marker = GL_FALSE;
+GLboolean __GLXEW_EXT_swap_control = GL_FALSE;
 GLboolean __GLXEW_EXT_texture_from_pixmap = GL_FALSE;
 GLboolean __GLXEW_EXT_visual_info = GL_FALSE;
 GLboolean __GLXEW_EXT_visual_rating = GL_FALSE;
+GLboolean __GLXEW_INTEL_swap_event = GL_FALSE;
 GLboolean __GLXEW_MESA_agp_offset = GL_FALSE;
 GLboolean __GLXEW_MESA_copy_sub_buffer = GL_FALSE;
 GLboolean __GLXEW_MESA_pixmap_colormap = GL_FALSE;
 GLboolean __GLXEW_MESA_release_buffers = GL_FALSE;
 GLboolean __GLXEW_MESA_set_3dfx_mode = GL_FALSE;
+GLboolean __GLXEW_NV_copy_image = GL_FALSE;
 GLboolean __GLXEW_NV_float_buffer = GL_FALSE;
 GLboolean __GLXEW_NV_present_video = GL_FALSE;
 GLboolean __GLXEW_NV_swap_group = GL_FALSE;
@@ -8395,6 +9932,10 @@ static GLboolean _glewInit_GLX_ARB_create_context (GLXEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GLX_ARB_create_context */
 
+#ifdef GLX_ARB_create_context_profile
+
+#endif /* GLX_ARB_create_context_profile */
+
 #ifdef GLX_ARB_fbconfig_float
 
 #endif /* GLX_ARB_fbconfig_float */
@@ -8411,6 +9952,10 @@ static GLboolean _glewInit_GLX_ARB_create_context (GLXEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GLX_ARB_multisample */
 
+#ifdef GLX_ARB_vertex_buffer_object
+
+#endif /* GLX_ARB_vertex_buffer_object */
+
 #ifdef GLX_ATI_pixel_format_float
 
 #endif /* GLX_ATI_pixel_format_float */
@@ -8458,6 +10003,19 @@ static GLboolean _glewInit_GLX_EXT_import_context (GLXEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GLX_EXT_scene_marker */
 
+#ifdef GLX_EXT_swap_control
+
+static GLboolean _glewInit_GLX_EXT_swap_control (GLXEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glewGetProcAddress((const GLubyte*)"glXSwapIntervalEXT")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GLX_EXT_swap_control */
+
 #ifdef GLX_EXT_texture_from_pixmap
 
 static GLboolean _glewInit_GLX_EXT_texture_from_pixmap (GLXEW_CONTEXT_ARG_DEF_INIT)
@@ -8480,6 +10038,10 @@ static GLboolean _glewInit_GLX_EXT_texture_from_pixmap (GLXEW_CONTEXT_ARG_DEF_IN
 
 #endif /* GLX_EXT_visual_rating */
 
+#ifdef GLX_INTEL_swap_event
+
+#endif /* GLX_INTEL_swap_event */
+
 #ifdef GLX_MESA_agp_offset
 
 static GLboolean _glewInit_GLX_MESA_agp_offset (GLXEW_CONTEXT_ARG_DEF_INIT)
@@ -8545,17 +10107,30 @@ static GLboolean _glewInit_GLX_MESA_set_3dfx_mode (GLXEW_CONTEXT_ARG_DEF_INIT)
 
 #endif /* GLX_MESA_set_3dfx_mode */
 
-#ifdef GLX_NV_float_buffer
-
-#endif /* GLX_NV_float_buffer */
-
-#ifdef GLX_NV_present_video
+#ifdef GLX_NV_copy_image
 
-static GLboolean _glewInit_GLX_NV_present_video (GLXEW_CONTEXT_ARG_DEF_INIT)
+static GLboolean _glewInit_GLX_NV_copy_image (GLXEW_CONTEXT_ARG_DEF_INIT)
 {
   GLboolean r = GL_FALSE;
 
-  r = ((glXBindVideoDeviceNV = (PFNGLXBINDVIDEODEVICENVPROC)glewGetProcAddress((const GLubyte*)"glXBindVideoDeviceNV")) == NULL) || r;
+  r = ((glXCopyImageSubDataNV = (PFNGLXCOPYIMAGESUBDATANVPROC)glewGetProcAddress((const GLubyte*)"glXCopyImageSubDataNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GLX_NV_copy_image */
+
+#ifdef GLX_NV_float_buffer
+
+#endif /* GLX_NV_float_buffer */
+
+#ifdef GLX_NV_present_video
+
+static GLboolean _glewInit_GLX_NV_present_video (GLXEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glXBindVideoDeviceNV = (PFNGLXBINDVIDEODEVICENVPROC)glewGetProcAddress((const GLubyte*)"glXBindVideoDeviceNV")) == NULL) || r;
   r = ((glXEnumerateVideoDevicesNV = (PFNGLXENUMERATEVIDEODEVICESNVPROC)glewGetProcAddress((const GLubyte*)"glXEnumerateVideoDevicesNV")) == NULL) || r;
 
   return r;
@@ -8841,10 +10416,10 @@ GLboolean glxewGetExtension (const char* name)
 {    
   GLubyte* p;
   GLubyte* end;
-  GLuint len = _glewStrLen((const GLubyte*)name);
-/*   if (glXQueryExtensionsString == NULL || glXGetCurrentDisplay == NULL) return GL_FALSE; */
-/*   p = (GLubyte*)glXQueryExtensionsString(glXGetCurrentDisplay(), DefaultScreen(glXGetCurrentDisplay())); */
-  if (glXGetClientString == NULL || glXGetCurrentDisplay == NULL) return GL_FALSE;
+  GLuint len;
+
+  if (glXGetCurrentDisplay == NULL) return GL_FALSE;
+  len = _glewStrLen((const GLubyte*)name);
   p = (GLubyte*)glXGetClientString(glXGetCurrentDisplay(), GLX_EXTENSIONS);
   if (0 == p) return GL_FALSE;
   end = p + _glewStrLen(p);
@@ -8897,6 +10472,9 @@ GLenum glxewContextInit (GLXEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLXEW_ARB_create_context) = glxewGetExtension("GLX_ARB_create_context");
   if (glewExperimental || GLXEW_ARB_create_context) CONST_CAST(GLXEW_ARB_create_context) = !_glewInit_GLX_ARB_create_context(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GLX_ARB_create_context */
+#ifdef GLX_ARB_create_context_profile
+  CONST_CAST(GLXEW_ARB_create_context_profile) = glxewGetExtension("GLX_ARB_create_context_profile");
+#endif /* GLX_ARB_create_context_profile */
 #ifdef GLX_ARB_fbconfig_float
   CONST_CAST(GLXEW_ARB_fbconfig_float) = glxewGetExtension("GLX_ARB_fbconfig_float");
 #endif /* GLX_ARB_fbconfig_float */
@@ -8909,6 +10487,9 @@ GLenum glxewContextInit (GLXEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GLX_ARB_multisample
   CONST_CAST(GLXEW_ARB_multisample) = glxewGetExtension("GLX_ARB_multisample");
 #endif /* GLX_ARB_multisample */
+#ifdef GLX_ARB_vertex_buffer_object
+  CONST_CAST(GLXEW_ARB_vertex_buffer_object) = glxewGetExtension("GLX_ARB_vertex_buffer_object");
+#endif /* GLX_ARB_vertex_buffer_object */
 #ifdef GLX_ATI_pixel_format_float
   CONST_CAST(GLXEW_ATI_pixel_format_float) = glxewGetExtension("GLX_ATI_pixel_format_float");
 #endif /* GLX_ATI_pixel_format_float */
@@ -8929,6 +10510,10 @@ GLenum glxewContextInit (GLXEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GLX_EXT_scene_marker
   CONST_CAST(GLXEW_EXT_scene_marker) = glxewGetExtension("GLX_EXT_scene_marker");
 #endif /* GLX_EXT_scene_marker */
+#ifdef GLX_EXT_swap_control
+  CONST_CAST(GLXEW_EXT_swap_control) = glxewGetExtension("GLX_EXT_swap_control");
+  if (glewExperimental || GLXEW_EXT_swap_control) CONST_CAST(GLXEW_EXT_swap_control) = !_glewInit_GLX_EXT_swap_control(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GLX_EXT_swap_control */
 #ifdef GLX_EXT_texture_from_pixmap
   CONST_CAST(GLXEW_EXT_texture_from_pixmap) = glxewGetExtension("GLX_EXT_texture_from_pixmap");
   if (glewExperimental || GLXEW_EXT_texture_from_pixmap) CONST_CAST(GLXEW_EXT_texture_from_pixmap) = !_glewInit_GLX_EXT_texture_from_pixmap(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -8939,6 +10524,9 @@ GLenum glxewContextInit (GLXEW_CONTEXT_ARG_DEF_LIST)
 #ifdef GLX_EXT_visual_rating
   CONST_CAST(GLXEW_EXT_visual_rating) = glxewGetExtension("GLX_EXT_visual_rating");
 #endif /* GLX_EXT_visual_rating */
+#ifdef GLX_INTEL_swap_event
+  CONST_CAST(GLXEW_INTEL_swap_event) = glxewGetExtension("GLX_INTEL_swap_event");
+#endif /* GLX_INTEL_swap_event */
 #ifdef GLX_MESA_agp_offset
   CONST_CAST(GLXEW_MESA_agp_offset) = glxewGetExtension("GLX_MESA_agp_offset");
   if (glewExperimental || GLXEW_MESA_agp_offset) CONST_CAST(GLXEW_MESA_agp_offset) = !_glewInit_GLX_MESA_agp_offset(GLEW_CONTEXT_ARG_VAR_INIT);
@@ -8959,6 +10547,10 @@ GLenum glxewContextInit (GLXEW_CONTEXT_ARG_DEF_LIST)
   CONST_CAST(GLXEW_MESA_set_3dfx_mode) = glxewGetExtension("GLX_MESA_set_3dfx_mode");
   if (glewExperimental || GLXEW_MESA_set_3dfx_mode) CONST_CAST(GLXEW_MESA_set_3dfx_mode) = !_glewInit_GLX_MESA_set_3dfx_mode(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GLX_MESA_set_3dfx_mode */
+#ifdef GLX_NV_copy_image
+  CONST_CAST(GLXEW_NV_copy_image) = glxewGetExtension("GLX_NV_copy_image");
+  if (glewExperimental || GLXEW_NV_copy_image) CONST_CAST(GLXEW_NV_copy_image) = !_glewInit_GLX_NV_copy_image(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GLX_NV_copy_image */
 #ifdef GLX_NV_float_buffer
   CONST_CAST(GLXEW_NV_float_buffer) = glxewGetExtension("GLX_NV_float_buffer");
 #endif /* GLX_NV_float_buffer */
@@ -9076,10 +10668,10 @@ const GLubyte* glewGetString (GLenum name)
   static const GLubyte* _glewString[] =
   {
     (const GLubyte*)NULL,
-    (const GLubyte*)"1.5.1",
+    (const GLubyte*)"1.5.4",
     (const GLubyte*)"1",
     (const GLubyte*)"5",
-    (const GLubyte*)"1"
+    (const GLubyte*)"4"
   };
   const int max_string = sizeof(_glewString)/sizeof(*_glewString) - 1;
   return _glewString[(int)name > max_string ? 0 : (int)name];
@@ -9174,6 +10766,34 @@ GLboolean glewIsSupported (const char* name)
           ret = GLEW_VERSION_3_0;
           continue;
         }
+#endif
+#ifdef GL_VERSION_3_1
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"3_1", 3))
+        {
+          ret = GLEW_VERSION_3_1;
+          continue;
+        }
+#endif
+#ifdef GL_VERSION_3_2
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"3_2", 3))
+        {
+          ret = GLEW_VERSION_3_2;
+          continue;
+        }
+#endif
+#ifdef GL_VERSION_3_3
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"3_3", 3))
+        {
+          ret = GLEW_VERSION_3_3;
+          continue;
+        }
+#endif
+#ifdef GL_VERSION_4_0
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"4_0", 3))
+        {
+          ret = GLEW_VERSION_4_0;
+          continue;
+        }
 #endif
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"3DFX_", 5))
@@ -9198,10 +10818,69 @@ GLboolean glewIsSupported (const char* name)
           ret = GLEW_3DFX_texture_compression_FXT1;
           continue;
         }
+#endif
+      }
+      if (_glewStrSame2(&pos, &len, (const GLubyte*)"AMD_", 4))
+      {
+#ifdef GL_AMD_conservative_depth
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"conservative_depth", 18))
+        {
+          ret = GLEW_AMD_conservative_depth;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_draw_buffers_blend
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"draw_buffers_blend", 18))
+        {
+          ret = GLEW_AMD_draw_buffers_blend;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_performance_monitor
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"performance_monitor", 19))
+        {
+          ret = GLEW_AMD_performance_monitor;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_seamless_cubemap_per_texture
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"seamless_cubemap_per_texture", 28))
+        {
+          ret = GLEW_AMD_seamless_cubemap_per_texture;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_shader_stencil_export
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_stencil_export", 21))
+        {
+          ret = GLEW_AMD_shader_stencil_export;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_texture_texture4
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_texture4", 16))
+        {
+          ret = GLEW_AMD_texture_texture4;
+          continue;
+        }
+#endif
+#ifdef GL_AMD_vertex_shader_tessellator
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_shader_tessellator", 25))
+        {
+          ret = GLEW_AMD_vertex_shader_tessellator;
+          continue;
+        }
 #endif
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"APPLE_", 6))
       {
+#ifdef GL_APPLE_aux_depth_stencil
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"aux_depth_stencil", 17))
+        {
+          ret = GLEW_APPLE_aux_depth_stencil;
+          continue;
+        }
+#endif
 #ifdef GL_APPLE_client_storage
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"client_storage", 14))
         {
@@ -9237,6 +10916,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_APPLE_object_purgeable
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"object_purgeable", 16))
+        {
+          ret = GLEW_APPLE_object_purgeable;
+          continue;
+        }
+#endif
 #ifdef GL_APPLE_pixel_buffer
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"pixel_buffer", 12))
         {
@@ -9244,6 +10930,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_APPLE_rgb_422
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"rgb_422", 7))
+        {
+          ret = GLEW_APPLE_rgb_422;
+          continue;
+        }
+#endif
+#ifdef GL_APPLE_row_bytes
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"row_bytes", 9))
+        {
+          ret = GLEW_APPLE_row_bytes;
+          continue;
+        }
+#endif
 #ifdef GL_APPLE_specular_vector
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"specular_vector", 15))
         {
@@ -9279,6 +10979,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_APPLE_vertex_program_evaluators
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_program_evaluators", 25))
+        {
+          ret = GLEW_APPLE_vertex_program_evaluators;
+          continue;
+        }
+#endif
 #ifdef GL_APPLE_ycbcr_422
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"ycbcr_422", 9))
         {
@@ -9289,6 +10996,13 @@ GLboolean glewIsSupported (const char* name)
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"ARB_", 4))
       {
+#ifdef GL_ARB_blend_func_extended
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"blend_func_extended", 19))
+        {
+          ret = GLEW_ARB_blend_func_extended;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_color_buffer_float
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"color_buffer_float", 18))
         {
@@ -9296,6 +11010,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_compatibility
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"compatibility", 13))
+        {
+          ret = GLEW_ARB_compatibility;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_copy_buffer
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"copy_buffer", 11))
+        {
+          ret = GLEW_ARB_copy_buffer;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_depth_buffer_float
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"depth_buffer_float", 18))
         {
@@ -9303,6 +11031,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_depth_clamp
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"depth_clamp", 11))
+        {
+          ret = GLEW_ARB_depth_clamp;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_depth_texture
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"depth_texture", 13))
         {
@@ -9317,6 +11052,27 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_draw_buffers_blend
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"draw_buffers_blend", 18))
+        {
+          ret = GLEW_ARB_draw_buffers_blend;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_draw_elements_base_vertex
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"draw_elements_base_vertex", 25))
+        {
+          ret = GLEW_ARB_draw_elements_base_vertex;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_draw_indirect
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"draw_indirect", 13))
+        {
+          ret = GLEW_ARB_draw_indirect;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_draw_instanced
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"draw_instanced", 14))
         {
@@ -9324,6 +11080,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_explicit_attrib_location
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"explicit_attrib_location", 24))
+        {
+          ret = GLEW_ARB_explicit_attrib_location;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_fragment_coord_conventions
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"fragment_coord_conventions", 26))
+        {
+          ret = GLEW_ARB_fragment_coord_conventions;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_fragment_program
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"fragment_program", 16))
         {
@@ -9366,6 +11136,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_gpu_shader5
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_shader5", 11))
+        {
+          ret = GLEW_ARB_gpu_shader5;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_gpu_shader_fp64
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_shader_fp64", 15))
+        {
+          ret = GLEW_ARB_gpu_shader_fp64;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_half_float_pixel
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"half_float_pixel", 16))
         {
@@ -9429,6 +11213,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_occlusion_query2
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"occlusion_query2", 16))
+        {
+          ret = GLEW_ARB_occlusion_query2;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_pixel_buffer_object
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"pixel_buffer_object", 19))
         {
@@ -9450,6 +11241,41 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_provoking_vertex
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"provoking_vertex", 16))
+        {
+          ret = GLEW_ARB_provoking_vertex;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_sample_shading
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"sample_shading", 14))
+        {
+          ret = GLEW_ARB_sample_shading;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_sampler_objects
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"sampler_objects", 15))
+        {
+          ret = GLEW_ARB_sampler_objects;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_seamless_cube_map
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"seamless_cube_map", 17))
+        {
+          ret = GLEW_ARB_seamless_cube_map;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_shader_bit_encoding
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_bit_encoding", 19))
+        {
+          ret = GLEW_ARB_shader_bit_encoding;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_shader_objects
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_objects", 14))
         {
@@ -9457,6 +11283,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_shader_subroutine
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_subroutine", 17))
+        {
+          ret = GLEW_ARB_shader_subroutine;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_shader_texture_lod
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_texture_lod", 18))
+        {
+          ret = GLEW_ARB_shader_texture_lod;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_shading_language_100
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"shading_language_100", 20))
         {
@@ -9464,6 +11304,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_shading_language_include
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shading_language_include", 24))
+        {
+          ret = GLEW_ARB_shading_language_include;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_shadow
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"shadow", 6))
         {
@@ -9478,6 +11325,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_sync
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"sync", 4))
+        {
+          ret = GLEW_ARB_sync;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_tessellation_shader
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"tessellation_shader", 19))
+        {
+          ret = GLEW_ARB_tessellation_shader;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_border_clamp
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_border_clamp", 20))
         {
@@ -9492,6 +11353,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_buffer_object_rgb32
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_buffer_object_rgb32", 27))
+        {
+          ret = GLEW_ARB_texture_buffer_object_rgb32;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_compression
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_compression", 19))
         {
@@ -9499,6 +11367,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_compression_bptc
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_compression_bptc", 24))
+        {
+          ret = GLEW_ARB_texture_compression_bptc;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_compression_rgtc
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_compression_rgtc", 24))
         {
@@ -9513,6 +11388,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_cube_map_array
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_cube_map_array", 22))
+        {
+          ret = GLEW_ARB_texture_cube_map_array;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_env_add
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_env_add", 15))
         {
@@ -9548,6 +11430,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_gather
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_gather", 14))
+        {
+          ret = GLEW_ARB_texture_gather;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_mirrored_repeat
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_mirrored_repeat", 23))
         {
@@ -9555,6 +11444,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_multisample
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_multisample", 19))
+        {
+          ret = GLEW_ARB_texture_multisample;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_non_power_of_two
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_non_power_of_two", 24))
         {
@@ -9562,6 +11458,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_query_lod
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_query_lod", 17))
+        {
+          ret = GLEW_ARB_texture_query_lod;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_texture_rectangle
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_rectangle", 17))
         {
@@ -9576,6 +11479,41 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_texture_rgb10_a2ui
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_rgb10_a2ui", 18))
+        {
+          ret = GLEW_ARB_texture_rgb10_a2ui;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_texture_swizzle
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_swizzle", 15))
+        {
+          ret = GLEW_ARB_texture_swizzle;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_timer_query
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"timer_query", 11))
+        {
+          ret = GLEW_ARB_timer_query;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_transform_feedback2
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"transform_feedback2", 19))
+        {
+          ret = GLEW_ARB_transform_feedback2;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_transform_feedback3
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"transform_feedback3", 19))
+        {
+          ret = GLEW_ARB_transform_feedback3;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_transpose_matrix
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"transpose_matrix", 16))
         {
@@ -9583,6 +11521,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_uniform_buffer_object
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"uniform_buffer_object", 21))
+        {
+          ret = GLEW_ARB_uniform_buffer_object;
+          continue;
+        }
+#endif
+#ifdef GL_ARB_vertex_array_bgra
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_array_bgra", 17))
+        {
+          ret = GLEW_ARB_vertex_array_bgra;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_vertex_array_object
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_array_object", 19))
         {
@@ -9618,6 +11570,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ARB_vertex_type_2_10_10_10_rev
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_type_2_10_10_10_rev", 26))
+        {
+          ret = GLEW_ARB_vertex_type_2_10_10_10_rev;
+          continue;
+        }
+#endif
 #ifdef GL_ARB_window_pos
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"window_pos", 10))
         {
@@ -9694,6 +11653,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_ATI_meminfo
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"meminfo", 7))
+        {
+          ret = GLEW_ATI_meminfo;
+          continue;
+        }
+#endif
 #ifdef GL_ATI_pn_triangles
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"pn_triangles", 12))
         {
@@ -10131,6 +12097,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_EXT_provoking_vertex
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"provoking_vertex", 16))
+        {
+          ret = GLEW_EXT_provoking_vertex;
+          continue;
+        }
+#endif
 #ifdef GL_EXT_rescale_normal
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"rescale_normal", 14))
         {
@@ -10152,6 +12125,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_EXT_separate_shader_objects
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"separate_shader_objects", 23))
+        {
+          ret = GLEW_EXT_separate_shader_objects;
+          continue;
+        }
+#endif
 #ifdef GL_EXT_separate_specular_color
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"separate_specular_color", 23))
         {
@@ -10159,6 +12139,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_EXT_shader_image_load_store
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_image_load_store", 23))
+        {
+          ret = GLEW_EXT_shader_image_load_store;
+          continue;
+        }
+#endif
 #ifdef GL_EXT_shadow_funcs
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"shadow_funcs", 12))
         {
@@ -10362,6 +12349,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_EXT_texture_snorm
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_snorm", 13))
+        {
+          ret = GLEW_EXT_texture_snorm;
+          continue;
+        }
+#endif
 #ifdef GL_EXT_texture_swizzle
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_swizzle", 15))
         {
@@ -10397,6 +12391,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_EXT_vertex_attrib_64bit
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_attrib_64bit", 19))
+        {
+          ret = GLEW_EXT_vertex_attrib_64bit;
+          continue;
+        }
+#endif
 #ifdef GL_EXT_vertex_shader
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_shader", 13))
         {
@@ -10613,6 +12614,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_copy_image
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"copy_image", 10))
+        {
+          ret = GLEW_NV_copy_image;
+          continue;
+        }
+#endif
 #ifdef GL_NV_depth_buffer_float
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"depth_buffer_float", 18))
         {
@@ -10725,6 +12733,27 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_gpu_program5
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_program5", 12))
+        {
+          ret = GLEW_NV_gpu_program5;
+          continue;
+        }
+#endif
+#ifdef GL_NV_gpu_program_fp64
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_program_fp64", 16))
+        {
+          ret = GLEW_NV_gpu_program_fp64;
+          continue;
+        }
+#endif
+#ifdef GL_NV_gpu_shader5
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_shader5", 11))
+        {
+          ret = GLEW_NV_gpu_shader5;
+          continue;
+        }
+#endif
 #ifdef GL_NV_half_float
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"half_float", 10))
         {
@@ -10767,6 +12796,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_parameter_buffer_object2
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"parameter_buffer_object2", 24))
+        {
+          ret = GLEW_NV_parameter_buffer_object2;
+          continue;
+        }
+#endif
 #ifdef GL_NV_pixel_data_range
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"pixel_data_range", 16))
         {
@@ -10809,6 +12845,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_shader_buffer_load
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"shader_buffer_load", 18))
+        {
+          ret = GLEW_NV_shader_buffer_load;
+          continue;
+        }
+#endif
+#ifdef GL_NV_tessellation_program5
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"tessellation_program5", 21))
+        {
+          ret = GLEW_NV_tessellation_program5;
+          continue;
+        }
+#endif
 #ifdef GL_NV_texgen_emboss
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texgen_emboss", 13))
         {
@@ -10823,6 +12873,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_texture_barrier
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_barrier", 15))
+        {
+          ret = GLEW_NV_texture_barrier;
+          continue;
+        }
+#endif
 #ifdef GL_NV_texture_compression_vtc
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_compression_vtc", 23))
         {
@@ -10879,6 +12936,13 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_transform_feedback2
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"transform_feedback2", 19))
+        {
+          ret = GLEW_NV_transform_feedback2;
+          continue;
+        }
+#endif
 #ifdef GL_NV_vertex_array_range
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_array_range", 18))
         {
@@ -10893,6 +12957,20 @@ GLboolean glewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GL_NV_vertex_attrib_integer_64bit
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_attrib_integer_64bit", 27))
+        {
+          ret = GLEW_NV_vertex_attrib_integer_64bit;
+          continue;
+        }
+#endif
+#ifdef GL_NV_vertex_buffer_unified_memory
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_buffer_unified_memory", 28))
+        {
+          ret = GLEW_NV_vertex_buffer_unified_memory;
+          continue;
+        }
+#endif
 #ifdef GL_NV_vertex_program
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_program", 14))
         {
@@ -11505,6 +13583,16 @@ GLboolean wglewIsSupported (const char* name)
           ret = WGLEW_3DL_stereo_control;
           continue;
         }
+#endif
+      }
+      if (_glewStrSame2(&pos, &len, (const GLubyte*)"AMD_", 4))
+      {
+#ifdef WGL_AMD_gpu_association
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"gpu_association", 15))
+        {
+          ret = WGLEW_AMD_gpu_association;
+          continue;
+        }
 #endif
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"ARB_", 4))
@@ -11523,6 +13611,13 @@ GLboolean wglewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef WGL_ARB_create_context_profile
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"create_context_profile", 22))
+        {
+          ret = WGLEW_ARB_create_context_profile;
+          continue;
+        }
+#endif
 #ifdef WGL_ARB_extensions_string
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"extensions_string", 17))
         {
@@ -11717,6 +13812,13 @@ GLboolean wglewIsSupported (const char* name)
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"NV_", 3))
       {
+#ifdef WGL_NV_copy_image
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"copy_image", 10))
+        {
+          ret = WGLEW_NV_copy_image;
+          continue;
+        }
+#endif
 #ifdef WGL_NV_float_buffer
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"float_buffer", 12))
         {
@@ -11848,6 +13950,13 @@ GLboolean glxewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GLX_ARB_create_context_profile
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"create_context_profile", 22))
+        {
+          ret = GLXEW_ARB_create_context_profile;
+          continue;
+        }
+#endif
 #ifdef GLX_ARB_fbconfig_float
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"fbconfig_float", 14))
         {
@@ -11875,6 +13984,13 @@ GLboolean glxewIsSupported (const char* name)
           ret = GLXEW_ARB_multisample;
           continue;
         }
+#endif
+#ifdef GLX_ARB_vertex_buffer_object
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"vertex_buffer_object", 20))
+        {
+          ret = GLXEW_ARB_vertex_buffer_object;
+          continue;
+        }
 #endif
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"ATI_", 4))
@@ -11924,6 +14040,13 @@ GLboolean glxewIsSupported (const char* name)
           continue;
         }
 #endif
+#ifdef GLX_EXT_swap_control
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"swap_control", 12))
+        {
+          ret = GLXEW_EXT_swap_control;
+          continue;
+        }
+#endif
 #ifdef GLX_EXT_texture_from_pixmap
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"texture_from_pixmap", 19))
         {
@@ -11944,6 +14067,16 @@ GLboolean glxewIsSupported (const char* name)
           ret = GLXEW_EXT_visual_rating;
           continue;
         }
+#endif
+      }
+      if (_glewStrSame2(&pos, &len, (const GLubyte*)"INTEL_", 6))
+      {
+#ifdef GLX_INTEL_swap_event
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"swap_event", 10))
+        {
+          ret = GLXEW_INTEL_swap_event;
+          continue;
+        }
 #endif
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"MESA_", 5))
@@ -11986,6 +14119,13 @@ GLboolean glxewIsSupported (const char* name)
       }
       if (_glewStrSame2(&pos, &len, (const GLubyte*)"NV_", 3))
       {
+#ifdef GLX_NV_copy_image
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"copy_image", 10))
+        {
+          ret = GLXEW_NV_copy_image;
+          continue;
+        }
+#endif
 #ifdef GLX_NV_float_buffer
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"float_buffer", 12))
         {
diff --git a/modules/gfx/src/GL/glew.h b/modules/gfx/src/GL/glew.h
index 2014092e8771498ba8bf6ad47d61c94c2e3cab97..189270e64d866719604ce57f0eabd89162d21626 100644
--- a/modules/gfx/src/GL/glew.h
+++ b/modules/gfx/src/GL/glew.h
@@ -80,7 +80,7 @@
 #define __glew_h__
 #define __GLEW_H__
 
-#if defined(__gl_h_) || defined(__GL_H__)
+#if defined(__gl_h_) || defined(__GL_H__) || defined(__X_GL_H)
 #error gl.h included before glew.h
 #endif
 #if defined(__glext_h_) || defined(__GLEXT_H_)
@@ -92,6 +92,7 @@
 
 #define __gl_h_
 #define __GL_H__
+#define __X_GL_H
 #define __glext_h_
 #define __GLEXT_H_
 #define __gl_ATI_h_
@@ -106,7 +107,7 @@
 /* <windef.h> */
 #ifndef APIENTRY
 #define GLEW_APIENTRY_DEFINED
-#  if defined(__MINGW32__)
+#  if defined(__MINGW32__) || defined(__CYGWIN__)
 #    define APIENTRY __stdcall
 #  elif (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__)
 #    define APIENTRY __stdcall
@@ -115,14 +116,14 @@
 #  endif
 #endif
 #ifndef GLAPI
-#  if defined(__MINGW32__)
+#  if defined(__MINGW32__) || defined(__CYGWIN__)
 #    define GLAPI extern
 #  endif
 #endif
 /* <winnt.h> */
 #ifndef CALLBACK
 #define GLEW_CALLBACK_DEFINED
-#  if defined(__MINGW32__)
+#  if defined(__MINGW32__) || defined(__CYGWIN__)
 #    define CALLBACK __attribute__ ((__stdcall__))
 #  elif (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS)
 #    define CALLBACK __stdcall
@@ -159,7 +160,7 @@ typedef _W64 int ptrdiff_t;
 #endif
 
 #ifndef GLAPI
-#  if defined(__MINGW32__)
+#  if defined(__MINGW32__) || defined(__CYGWIN__)
 #    define GLAPI extern
 #  else
 #    define GLAPI WINGDIAPI
@@ -196,7 +197,14 @@ typedef _W64 int ptrdiff_t;
  */
 
 #include <stddef.h>
+
+/* SGI MIPSPro doesn't like stdint.h in C++ mode */
+
+#if defined(__sgi) && !defined(__GNUC__)
+#include <inttypes.h>
+#else
 #include <stdint.h>
+#endif
 
 #define GLEW_APIENTRY_DEFINED
 #define APIENTRY
@@ -246,12 +254,15 @@ typedef signed long long GLint64EXT;
 typedef unsigned long long GLuint64EXT;
 #  endif
 #else
-#  if defined(__MINGW32__)
+#  if defined(__MINGW32__) || defined(__CYGWIN__)
 #include <inttypes.h>
 #  endif
 typedef int64_t GLint64EXT;
 typedef uint64_t GLuint64EXT;
 #endif
+typedef GLint64EXT  GLint64;
+typedef GLuint64EXT GLuint64;
+typedef struct __GLsync *GLsync;
 
 #define GL_ACCUM 0x0100
 #define GL_LOAD 0x0101
@@ -1455,9 +1466,9 @@ typedef void (GLAPIENTRY * PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
 typedef void (GLAPIENTRY * PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
 typedef void (GLAPIENTRY * PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount);
 typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
-typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERFVPROC) (GLenum pname, GLfloat *params);
+typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
 typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
-typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERIVPROC) (GLenum pname, GLint *params);
+typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
 typedef void (GLAPIENTRY * PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
 typedef void (GLAPIENTRY * PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
 typedef void (GLAPIENTRY * PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
@@ -2094,8 +2105,6 @@ typedef void (GLAPIENTRY * PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei
 
 typedef void (GLAPIENTRY * PFNGLBEGINCONDITIONALRENDERPROC) (GLuint, GLenum);
 typedef void (GLAPIENTRY * PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum);
-typedef void (GLAPIENTRY * PFNGLBINDBUFFERBASEPROC) (GLenum, GLuint, GLuint);
-typedef void (GLAPIENTRY * PFNGLBINDBUFFERRANGEPROC) (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr);
 typedef void (GLAPIENTRY * PFNGLBINDFRAGDATALOCATIONPROC) (GLuint, GLuint, const GLchar*);
 typedef void (GLAPIENTRY * PFNGLCLAMPCOLORPROC) (GLenum, GLenum);
 typedef void (GLAPIENTRY * PFNGLCLEARBUFFERFIPROC) (GLenum, GLint, GLfloat, GLint);
@@ -2109,7 +2118,6 @@ typedef void (GLAPIENTRY * PFNGLENDCONDITIONALRENDERPROC) (void);
 typedef void (GLAPIENTRY * PFNGLENDTRANSFORMFEEDBACKPROC) (void);
 typedef void (GLAPIENTRY * PFNGLGETBOOLEANI_VPROC) (GLenum, GLuint, GLboolean*);
 typedef GLint (GLAPIENTRY * PFNGLGETFRAGDATALOCATIONPROC) (GLuint, const GLchar*);
-typedef void (GLAPIENTRY * PFNGLGETINTEGERI_VPROC) (GLenum, GLuint, GLint*);
 typedef const GLubyte* (GLAPIENTRY * PFNGLGETSTRINGIPROC) (GLenum, GLuint);
 typedef void (GLAPIENTRY * PFNGLGETTEXPARAMETERIIVPROC) (GLenum, GLenum, GLint*);
 typedef void (GLAPIENTRY * PFNGLGETTEXPARAMETERIUIVPROC) (GLenum, GLenum, GLuint*);
@@ -2120,7 +2128,7 @@ typedef void (GLAPIENTRY * PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint, GLenum, GLuint
 typedef GLboolean (GLAPIENTRY * PFNGLISENABLEDIPROC) (GLenum, GLuint);
 typedef void (GLAPIENTRY * PFNGLTEXPARAMETERIIVPROC) (GLenum, GLenum, const GLint*);
 typedef void (GLAPIENTRY * PFNGLTEXPARAMETERIUIVPROC) (GLenum, GLenum, const GLuint*);
-typedef void (GLAPIENTRY * PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint, GLsizei, const GLint*, GLenum);
+typedef void (GLAPIENTRY * PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint, GLsizei, const GLchar **, GLenum);
 typedef void (GLAPIENTRY * PFNGLUNIFORM1UIPROC) (GLint, GLuint);
 typedef void (GLAPIENTRY * PFNGLUNIFORM1UIVPROC) (GLint, GLsizei, const GLuint*);
 typedef void (GLAPIENTRY * PFNGLUNIFORM2UIPROC) (GLint, GLuint, GLuint);
@@ -2153,8 +2161,6 @@ typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint, GLint, GLenum
 
 #define glBeginConditionalRender GLEW_GET_FUN(__glewBeginConditionalRender)
 #define glBeginTransformFeedback GLEW_GET_FUN(__glewBeginTransformFeedback)
-#define glBindBufferBase GLEW_GET_FUN(__glewBindBufferBase)
-#define glBindBufferRange GLEW_GET_FUN(__glewBindBufferRange)
 #define glBindFragDataLocation GLEW_GET_FUN(__glewBindFragDataLocation)
 #define glClampColor GLEW_GET_FUN(__glewClampColor)
 #define glClearBufferfi GLEW_GET_FUN(__glewClearBufferfi)
@@ -2168,7 +2174,6 @@ typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint, GLint, GLenum
 #define glEndTransformFeedback GLEW_GET_FUN(__glewEndTransformFeedback)
 #define glGetBooleani_v GLEW_GET_FUN(__glewGetBooleani_v)
 #define glGetFragDataLocation GLEW_GET_FUN(__glewGetFragDataLocation)
-#define glGetIntegeri_v GLEW_GET_FUN(__glewGetIntegeri_v)
 #define glGetStringi GLEW_GET_FUN(__glewGetStringi)
 #define glGetTexParameterIiv GLEW_GET_FUN(__glewGetTexParameterIiv)
 #define glGetTexParameterIuiv GLEW_GET_FUN(__glewGetTexParameterIuiv)
@@ -2214,6 +2219,157 @@ typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint, GLint, GLenum
 
 #endif /* GL_VERSION_3_0 */
 
+/* ----------------------------- GL_VERSION_3_1 ---------------------------- */
+
+#ifndef GL_VERSION_3_1
+#define GL_VERSION_3_1 1
+
+#define GL_TEXTURE_RECTANGLE 0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8
+#define GL_SAMPLER_2D_RECT 0x8B63
+#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64
+#define GL_TEXTURE_BUFFER 0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER 0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D
+#define GL_TEXTURE_BUFFER_FORMAT 0x8C2E
+#define GL_SAMPLER_BUFFER 0x8DC2
+#define GL_INT_SAMPLER_2D_RECT 0x8DCD
+#define GL_INT_SAMPLER_BUFFER 0x8DD0
+#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8
+#define GL_RED_SNORM 0x8F90
+#define GL_RG_SNORM 0x8F91
+#define GL_RGB_SNORM 0x8F92
+#define GL_RGBA_SNORM 0x8F93
+#define GL_R8_SNORM 0x8F94
+#define GL_RG8_SNORM 0x8F95
+#define GL_RGB8_SNORM 0x8F96
+#define GL_RGBA8_SNORM 0x8F97
+#define GL_R16_SNORM 0x8F98
+#define GL_RG16_SNORM 0x8F99
+#define GL_RGB16_SNORM 0x8F9A
+#define GL_RGBA16_SNORM 0x8F9B
+#define GL_SIGNED_NORMALIZED 0x8F9C
+#define GL_PRIMITIVE_RESTART 0x8F9D
+#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E
+#define GL_BUFFER_ACCESS_FLAGS 0x911F
+#define GL_BUFFER_MAP_LENGTH 0x9120
+#define GL_BUFFER_MAP_OFFSET 0x9121
+
+typedef void (GLAPIENTRY * PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum, GLint, GLsizei, GLsizei);
+typedef void (GLAPIENTRY * PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum, GLsizei, GLenum, const GLvoid*, GLsizei);
+typedef void (GLAPIENTRY * PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint);
+typedef void (GLAPIENTRY * PFNGLTEXBUFFERPROC) (GLenum, GLenum, GLuint);
+
+#define glDrawArraysInstanced GLEW_GET_FUN(__glewDrawArraysInstanced)
+#define glDrawElementsInstanced GLEW_GET_FUN(__glewDrawElementsInstanced)
+#define glPrimitiveRestartIndex GLEW_GET_FUN(__glewPrimitiveRestartIndex)
+#define glTexBuffer GLEW_GET_FUN(__glewTexBuffer)
+
+#define GLEW_VERSION_3_1 GLEW_GET_VAR(__GLEW_VERSION_3_1)
+
+#endif /* GL_VERSION_3_1 */
+
+/* ----------------------------- GL_VERSION_3_2 ---------------------------- */
+
+#ifndef GL_VERSION_3_2
+#define GL_VERSION_3_2 1
+
+#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001
+#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
+#define GL_LINES_ADJACENCY 0x000A
+#define GL_LINE_STRIP_ADJACENCY 0x000B
+#define GL_TRIANGLES_ADJACENCY 0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D
+#define GL_PROGRAM_POINT_SIZE 0x8642
+#define GL_GEOMETRY_VERTICES_OUT 0x8916
+#define GL_GEOMETRY_INPUT_TYPE 0x8917
+#define GL_GEOMETRY_OUTPUT_TYPE 0x8918
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8
+#define GL_GEOMETRY_SHADER 0x8DD9
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1
+#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122
+#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123
+#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124
+#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125
+#define GL_CONTEXT_PROFILE_MASK 0x9126
+
+typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum, GLenum, GLuint, GLint);
+typedef void (GLAPIENTRY * PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum, GLenum, GLint64 *);
+typedef void (GLAPIENTRY * PFNGLGETINTEGER64I_VPROC) (GLenum, GLuint, GLint64 *);
+
+#define glFramebufferTexture GLEW_GET_FUN(__glewFramebufferTexture)
+#define glGetBufferParameteri64v GLEW_GET_FUN(__glewGetBufferParameteri64v)
+#define glGetInteger64i_v GLEW_GET_FUN(__glewGetInteger64i_v)
+
+#define GLEW_VERSION_3_2 GLEW_GET_VAR(__GLEW_VERSION_3_2)
+
+#endif /* GL_VERSION_3_2 */
+
+/* ----------------------------- GL_VERSION_3_3 ---------------------------- */
+
+#ifndef GL_VERSION_3_3
+#define GL_VERSION_3_3 1
+
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE
+#define GL_ANY_SAMPLES_PASSED 0x8C2F
+#define GL_TEXTURE_SWIZZLE_R 0x8E42
+#define GL_TEXTURE_SWIZZLE_G 0x8E43
+#define GL_TEXTURE_SWIZZLE_B 0x8E44
+#define GL_TEXTURE_SWIZZLE_A 0x8E45
+#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46
+#define GL_RGB10_A2UI 0x906F
+
+#define GLEW_VERSION_3_3 GLEW_GET_VAR(__GLEW_VERSION_3_3)
+
+#endif /* GL_VERSION_3_3 */
+
+/* ----------------------------- GL_VERSION_4_0 ---------------------------- */
+
+#ifndef GL_VERSION_4_0
+#define GL_VERSION_4_0 1
+
+#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F
+#define GL_SAMPLE_SHADING 0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37
+#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A
+#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B
+#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C
+#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D
+#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E
+#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F
+#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS 0x8F9F
+#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B
+#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F
+
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (GLAPIENTRY * PFNGLMINSAMPLESHADINGPROC) (GLclampf value);
+
+#define glBlendEquationSeparatei GLEW_GET_FUN(__glewBlendEquationSeparatei)
+#define glBlendEquationi GLEW_GET_FUN(__glewBlendEquationi)
+#define glBlendFuncSeparatei GLEW_GET_FUN(__glewBlendFuncSeparatei)
+#define glBlendFunci GLEW_GET_FUN(__glewBlendFunci)
+#define glMinSampleShading GLEW_GET_FUN(__glewMinSampleShading)
+
+#define GLEW_VERSION_4_0 GLEW_GET_VAR(__GLEW_VERSION_4_0)
+
+#endif /* GL_VERSION_4_0 */
+
 /* -------------------------- GL_3DFX_multisample -------------------------- */
 
 #ifndef GL_3DFX_multisample
@@ -2253,6 +2409,140 @@ typedef void (GLAPIENTRY * PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
 
 #endif /* GL_3DFX_texture_compression_FXT1 */
 
+/* ----------------------- GL_AMD_conservative_depth ----------------------- */
+
+#ifndef GL_AMD_conservative_depth
+#define GL_AMD_conservative_depth 1
+
+#define GLEW_AMD_conservative_depth GLEW_GET_VAR(__GLEW_AMD_conservative_depth)
+
+#endif /* GL_AMD_conservative_depth */
+
+/* ----------------------- GL_AMD_draw_buffers_blend ----------------------- */
+
+#ifndef GL_AMD_draw_buffers_blend
+#define GL_AMD_draw_buffers_blend 1
+
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode);
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+
+#define glBlendEquationIndexedAMD GLEW_GET_FUN(__glewBlendEquationIndexedAMD)
+#define glBlendEquationSeparateIndexedAMD GLEW_GET_FUN(__glewBlendEquationSeparateIndexedAMD)
+#define glBlendFuncIndexedAMD GLEW_GET_FUN(__glewBlendFuncIndexedAMD)
+#define glBlendFuncSeparateIndexedAMD GLEW_GET_FUN(__glewBlendFuncSeparateIndexedAMD)
+
+#define GLEW_AMD_draw_buffers_blend GLEW_GET_VAR(__GLEW_AMD_draw_buffers_blend)
+
+#endif /* GL_AMD_draw_buffers_blend */
+
+/* ----------------------- GL_AMD_performance_monitor ---------------------- */
+
+#ifndef GL_AMD_performance_monitor
+#define GL_AMD_performance_monitor 1
+
+#define GL_UNSIGNED_INT 0x1405
+#define GL_FLOAT 0x1406
+#define GL_COUNTER_TYPE_AMD 0x8BC0
+#define GL_COUNTER_RANGE_AMD 0x8BC1
+#define GL_UNSIGNED_INT64_AMD 0x8BC2
+#define GL_PERCENTAGE_AMD 0x8BC3
+#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4
+#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5
+#define GL_PERFMON_RESULT_AMD 0x8BC6
+
+typedef void (GLAPIENTRY * PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GLAPIENTRY * PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint* monitors);
+typedef void (GLAPIENTRY * PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GLAPIENTRY * PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint* monitors);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint* data, GLint *bytesWritten);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void* data);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei* length, char *counterString);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint* numCounters, GLint *maxActiveCounters, GLsizei countersSize, GLuint *counters);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei* length, char *groupString);
+typedef void (GLAPIENTRY * PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint* numGroups, GLsizei groupsSize, GLuint *groups);
+typedef void (GLAPIENTRY * PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint* counterList);
+
+#define glBeginPerfMonitorAMD GLEW_GET_FUN(__glewBeginPerfMonitorAMD)
+#define glDeletePerfMonitorsAMD GLEW_GET_FUN(__glewDeletePerfMonitorsAMD)
+#define glEndPerfMonitorAMD GLEW_GET_FUN(__glewEndPerfMonitorAMD)
+#define glGenPerfMonitorsAMD GLEW_GET_FUN(__glewGenPerfMonitorsAMD)
+#define glGetPerfMonitorCounterDataAMD GLEW_GET_FUN(__glewGetPerfMonitorCounterDataAMD)
+#define glGetPerfMonitorCounterInfoAMD GLEW_GET_FUN(__glewGetPerfMonitorCounterInfoAMD)
+#define glGetPerfMonitorCounterStringAMD GLEW_GET_FUN(__glewGetPerfMonitorCounterStringAMD)
+#define glGetPerfMonitorCountersAMD GLEW_GET_FUN(__glewGetPerfMonitorCountersAMD)
+#define glGetPerfMonitorGroupStringAMD GLEW_GET_FUN(__glewGetPerfMonitorGroupStringAMD)
+#define glGetPerfMonitorGroupsAMD GLEW_GET_FUN(__glewGetPerfMonitorGroupsAMD)
+#define glSelectPerfMonitorCountersAMD GLEW_GET_FUN(__glewSelectPerfMonitorCountersAMD)
+
+#define GLEW_AMD_performance_monitor GLEW_GET_VAR(__GLEW_AMD_performance_monitor)
+
+#endif /* GL_AMD_performance_monitor */
+
+/* ------------------ GL_AMD_seamless_cubemap_per_texture ------------------ */
+
+#ifndef GL_AMD_seamless_cubemap_per_texture
+#define GL_AMD_seamless_cubemap_per_texture 1
+
+#define GL_TEXTURE_CUBE_MAP_SEAMLESS_ARB 0x884F
+
+#define GLEW_AMD_seamless_cubemap_per_texture GLEW_GET_VAR(__GLEW_AMD_seamless_cubemap_per_texture)
+
+#endif /* GL_AMD_seamless_cubemap_per_texture */
+
+/* ---------------------- GL_AMD_shader_stencil_export --------------------- */
+
+#ifndef GL_AMD_shader_stencil_export
+#define GL_AMD_shader_stencil_export 1
+
+#define GLEW_AMD_shader_stencil_export GLEW_GET_VAR(__GLEW_AMD_shader_stencil_export)
+
+#endif /* GL_AMD_shader_stencil_export */
+
+/* ------------------------ GL_AMD_texture_texture4 ------------------------ */
+
+#ifndef GL_AMD_texture_texture4
+#define GL_AMD_texture_texture4 1
+
+#define GLEW_AMD_texture_texture4 GLEW_GET_VAR(__GLEW_AMD_texture_texture4)
+
+#endif /* GL_AMD_texture_texture4 */
+
+/* -------------------- GL_AMD_vertex_shader_tessellator ------------------- */
+
+#ifndef GL_AMD_vertex_shader_tessellator
+#define GL_AMD_vertex_shader_tessellator 1
+
+#define GL_SAMPLER_BUFFER_AMD 0x9001
+#define GL_INT_SAMPLER_BUFFER_AMD 0x9002
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003
+#define GL_TESSELLATION_MODE_AMD 0x9004
+#define GL_TESSELLATION_FACTOR_AMD 0x9005
+#define GL_DISCRETE_AMD 0x9006
+#define GL_CONTINUOUS_AMD 0x9007
+
+typedef void (GLAPIENTRY * PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor);
+typedef void (GLAPIENTRY * PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode);
+
+#define glTessellationFactorAMD GLEW_GET_FUN(__glewTessellationFactorAMD)
+#define glTessellationModeAMD GLEW_GET_FUN(__glewTessellationModeAMD)
+
+#define GLEW_AMD_vertex_shader_tessellator GLEW_GET_VAR(__GLEW_AMD_vertex_shader_tessellator)
+
+#endif /* GL_AMD_vertex_shader_tessellator */
+
+/* ----------------------- GL_APPLE_aux_depth_stencil ---------------------- */
+
+#ifndef GL_APPLE_aux_depth_stencil
+#define GL_APPLE_aux_depth_stencil 1
+
+#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14
+
+#define GLEW_APPLE_aux_depth_stencil GLEW_GET_VAR(__GLEW_APPLE_aux_depth_stencil)
+
+#endif /* GL_APPLE_aux_depth_stencil */
+
 /* ------------------------ GL_APPLE_client_storage ------------------------ */
 
 #ifndef GL_APPLE_client_storage
@@ -2269,9 +2559,9 @@ typedef void (GLAPIENTRY * PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
 #ifndef GL_APPLE_element_array
 #define GL_APPLE_element_array 1
 
-#define GL_ELEMENT_ARRAY_APPLE 0x8768
-#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8769
-#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x876A
+#define GL_ELEMENT_ARRAY_APPLE 0x8A0C
+#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D
+#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E
 
 typedef void (GLAPIENTRY * PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
 typedef void (GLAPIENTRY * PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
@@ -2361,6 +2651,30 @@ typedef void (GLAPIENTRY * PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target,
 
 #endif /* GL_APPLE_flush_buffer_range */
 
+/* ----------------------- GL_APPLE_object_purgeable ----------------------- */
+
+#ifndef GL_APPLE_object_purgeable
+#define GL_APPLE_object_purgeable 1
+
+#define GL_BUFFER_OBJECT_APPLE 0x85B3
+#define GL_RELEASED_APPLE 0x8A19
+#define GL_VOLATILE_APPLE 0x8A1A
+#define GL_RETAINED_APPLE 0x8A1B
+#define GL_UNDEFINED_APPLE 0x8A1C
+#define GL_PURGEABLE_APPLE 0x8A1D
+
+typedef void (GLAPIENTRY * PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint* params);
+typedef GLenum (GLAPIENTRY * PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);
+typedef GLenum (GLAPIENTRY * PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);
+
+#define glGetObjectParameterivAPPLE GLEW_GET_FUN(__glewGetObjectParameterivAPPLE)
+#define glObjectPurgeableAPPLE GLEW_GET_FUN(__glewObjectPurgeableAPPLE)
+#define glObjectUnpurgeableAPPLE GLEW_GET_FUN(__glewObjectUnpurgeableAPPLE)
+
+#define GLEW_APPLE_object_purgeable GLEW_GET_VAR(__GLEW_APPLE_object_purgeable)
+
+#endif /* GL_APPLE_object_purgeable */
+
 /* ------------------------- GL_APPLE_pixel_buffer ------------------------- */
 
 #ifndef GL_APPLE_pixel_buffer
@@ -2372,6 +2686,31 @@ typedef void (GLAPIENTRY * PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target,
 
 #endif /* GL_APPLE_pixel_buffer */
 
+/* ---------------------------- GL_APPLE_rgb_422 --------------------------- */
+
+#ifndef GL_APPLE_rgb_422
+#define GL_APPLE_rgb_422 1
+
+#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB
+#define GL_RGB_422_APPLE 0x8A1F
+
+#define GLEW_APPLE_rgb_422 GLEW_GET_VAR(__GLEW_APPLE_rgb_422)
+
+#endif /* GL_APPLE_rgb_422 */
+
+/* --------------------------- GL_APPLE_row_bytes -------------------------- */
+
+#ifndef GL_APPLE_row_bytes
+#define GL_APPLE_row_bytes 1
+
+#define GL_PACK_ROW_BYTES_APPLE 0x8A15
+#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16
+
+#define GLEW_APPLE_row_bytes GLEW_GET_VAR(__GLEW_APPLE_row_bytes)
+
+#endif /* GL_APPLE_row_bytes */
+
 /* ------------------------ GL_APPLE_specular_vector ----------------------- */
 
 #ifndef GL_APPLE_specular_vector
@@ -2447,6 +2786,7 @@ typedef GLboolean (GLAPIENTRY * PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
 #define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
 #define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_APPLE 0x8520
 #define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
+#define GL_STORAGE_CLIENT_APPLE 0x85B4
 #define GL_STORAGE_CACHED_APPLE 0x85BE
 #define GL_STORAGE_SHARED_APPLE 0x85BF
 
@@ -2462,6 +2802,42 @@ typedef void (GLAPIENTRY * PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void
 
 #endif /* GL_APPLE_vertex_array_range */
 
+/* ------------------- GL_APPLE_vertex_program_evaluators ------------------ */
+
+#ifndef GL_APPLE_vertex_program_evaluators
+#define GL_APPLE_vertex_program_evaluators 1
+
+#define GL_VERTEX_ATTRIB_MAP1_APPLE 0x8A00
+#define GL_VERTEX_ATTRIB_MAP2_APPLE 0x8A01
+#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE 0x8A02
+#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03
+#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04
+#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05
+#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE 0x8A06
+#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07
+#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08
+#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09
+
+typedef void (GLAPIENTRY * PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);
+typedef void (GLAPIENTRY * PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);
+typedef GLboolean (GLAPIENTRY * PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname);
+typedef void (GLAPIENTRY * PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble* points);
+typedef void (GLAPIENTRY * PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat* points);
+typedef void (GLAPIENTRY * PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble* points);
+typedef void (GLAPIENTRY * PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat* points);
+
+#define glDisableVertexAttribAPPLE GLEW_GET_FUN(__glewDisableVertexAttribAPPLE)
+#define glEnableVertexAttribAPPLE GLEW_GET_FUN(__glewEnableVertexAttribAPPLE)
+#define glIsVertexAttribEnabledAPPLE GLEW_GET_FUN(__glewIsVertexAttribEnabledAPPLE)
+#define glMapVertexAttrib1dAPPLE GLEW_GET_FUN(__glewMapVertexAttrib1dAPPLE)
+#define glMapVertexAttrib1fAPPLE GLEW_GET_FUN(__glewMapVertexAttrib1fAPPLE)
+#define glMapVertexAttrib2dAPPLE GLEW_GET_FUN(__glewMapVertexAttrib2dAPPLE)
+#define glMapVertexAttrib2fAPPLE GLEW_GET_FUN(__glewMapVertexAttrib2fAPPLE)
+
+#define GLEW_APPLE_vertex_program_evaluators GLEW_GET_VAR(__GLEW_APPLE_vertex_program_evaluators)
+
+#endif /* GL_APPLE_vertex_program_evaluators */
+
 /* --------------------------- GL_APPLE_ycbcr_422 -------------------------- */
 
 #ifndef GL_APPLE_ycbcr_422
@@ -2475,6 +2851,26 @@ typedef void (GLAPIENTRY * PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void
 
 #endif /* GL_APPLE_ycbcr_422 */
 
+/* ----------------------- GL_ARB_blend_func_extended ---------------------- */
+
+#ifndef GL_ARB_blend_func_extended
+#define GL_ARB_blend_func_extended 1
+
+#define GL_SRC1_COLOR 0x88F9
+#define GL_ONE_MINUS_SRC1_COLOR 0x88FA
+#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB
+#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC
+
+typedef void (GLAPIENTRY * PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const char * name);
+typedef GLint (GLAPIENTRY * PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const char * name);
+
+#define glBindFragDataLocationIndexed GLEW_GET_FUN(__glewBindFragDataLocationIndexed)
+#define glGetFragDataIndex GLEW_GET_FUN(__glewGetFragDataIndex)
+
+#define GLEW_ARB_blend_func_extended GLEW_GET_VAR(__GLEW_ARB_blend_func_extended)
+
+#endif /* GL_ARB_blend_func_extended */
+
 /* ----------------------- GL_ARB_color_buffer_float ----------------------- */
 
 #ifndef GL_ARB_color_buffer_float
@@ -2494,6 +2890,31 @@ typedef void (GLAPIENTRY * PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp)
 
 #endif /* GL_ARB_color_buffer_float */
 
+/* -------------------------- GL_ARB_compatibility ------------------------- */
+
+#ifndef GL_ARB_compatibility
+#define GL_ARB_compatibility 1
+
+#define GLEW_ARB_compatibility GLEW_GET_VAR(__GLEW_ARB_compatibility)
+
+#endif /* GL_ARB_compatibility */
+
+/* --------------------------- GL_ARB_copy_buffer -------------------------- */
+
+#ifndef GL_ARB_copy_buffer
+#define GL_ARB_copy_buffer 1
+
+#define GL_COPY_READ_BUFFER 0x8F36
+#define GL_COPY_WRITE_BUFFER 0x8F37
+
+typedef void (GLAPIENTRY * PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readtarget, GLenum writetarget, GLintptr readoffset, GLintptr writeoffset, GLsizeiptr size);
+
+#define glCopyBufferSubData GLEW_GET_FUN(__glewCopyBufferSubData)
+
+#define GLEW_ARB_copy_buffer GLEW_GET_VAR(__GLEW_ARB_copy_buffer)
+
+#endif /* GL_ARB_copy_buffer */
+
 /* ----------------------- GL_ARB_depth_buffer_float ----------------------- */
 
 #ifndef GL_ARB_depth_buffer_float
@@ -2507,6 +2928,17 @@ typedef void (GLAPIENTRY * PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp)
 
 #endif /* GL_ARB_depth_buffer_float */
 
+/* --------------------------- GL_ARB_depth_clamp -------------------------- */
+
+#ifndef GL_ARB_depth_clamp
+#define GL_ARB_depth_clamp 1
+
+#define GL_DEPTH_CLAMP 0x864F
+
+#define GLEW_ARB_depth_clamp GLEW_GET_VAR(__GLEW_ARB_depth_clamp)
+
+#endif /* GL_ARB_depth_clamp */
+
 /* -------------------------- GL_ARB_depth_texture ------------------------- */
 
 #ifndef GL_ARB_depth_texture
@@ -2553,6 +2985,62 @@ typedef void (GLAPIENTRY * PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum* bu
 
 #endif /* GL_ARB_draw_buffers */
 
+/* ----------------------- GL_ARB_draw_buffers_blend ----------------------- */
+
+#ifndef GL_ARB_draw_buffers_blend
+#define GL_ARB_draw_buffers_blend 1
+
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (GLAPIENTRY * PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+typedef void (GLAPIENTRY * PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst);
+
+#define glBlendEquationSeparateiARB GLEW_GET_FUN(__glewBlendEquationSeparateiARB)
+#define glBlendEquationiARB GLEW_GET_FUN(__glewBlendEquationiARB)
+#define glBlendFuncSeparateiARB GLEW_GET_FUN(__glewBlendFuncSeparateiARB)
+#define glBlendFunciARB GLEW_GET_FUN(__glewBlendFunciARB)
+
+#define GLEW_ARB_draw_buffers_blend GLEW_GET_VAR(__GLEW_ARB_draw_buffers_blend)
+
+#endif /* GL_ARB_draw_buffers_blend */
+
+/* -------------------- GL_ARB_draw_elements_base_vertex ------------------- */
+
+#ifndef GL_ARB_draw_elements_base_vertex
+#define GL_ARB_draw_elements_base_vertex 1
+
+typedef void (GLAPIENTRY * PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, void* indices, GLint basevertex);
+typedef void (GLAPIENTRY * PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void* indices, GLsizei primcount, GLint basevertex);
+typedef void (GLAPIENTRY * PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, void* indices, GLint basevertex);
+typedef void (GLAPIENTRY * PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei* count, GLenum type, GLvoid**indices, GLsizei primcount, GLint *basevertex);
+
+#define glDrawElementsBaseVertex GLEW_GET_FUN(__glewDrawElementsBaseVertex)
+#define glDrawElementsInstancedBaseVertex GLEW_GET_FUN(__glewDrawElementsInstancedBaseVertex)
+#define glDrawRangeElementsBaseVertex GLEW_GET_FUN(__glewDrawRangeElementsBaseVertex)
+#define glMultiDrawElementsBaseVertex GLEW_GET_FUN(__glewMultiDrawElementsBaseVertex)
+
+#define GLEW_ARB_draw_elements_base_vertex GLEW_GET_VAR(__GLEW_ARB_draw_elements_base_vertex)
+
+#endif /* GL_ARB_draw_elements_base_vertex */
+
+/* -------------------------- GL_ARB_draw_indirect ------------------------- */
+
+#ifndef GL_ARB_draw_indirect
+#define GL_ARB_draw_indirect 1
+
+#define GL_DRAW_INDIRECT_BUFFER 0x8F3F
+#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43
+
+typedef void (GLAPIENTRY * PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void* indirect);
+typedef void (GLAPIENTRY * PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void* indirect);
+
+#define glDrawArraysIndirect GLEW_GET_FUN(__glewDrawArraysIndirect)
+#define glDrawElementsIndirect GLEW_GET_FUN(__glewDrawElementsIndirect)
+
+#define GLEW_ARB_draw_indirect GLEW_GET_VAR(__GLEW_ARB_draw_indirect)
+
+#endif /* GL_ARB_draw_indirect */
+
 /* ------------------------- GL_ARB_draw_instanced ------------------------- */
 
 #ifndef GL_ARB_draw_instanced
@@ -2568,6 +3056,24 @@ typedef void (GLAPIENTRY * PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsi
 
 #endif /* GL_ARB_draw_instanced */
 
+/* -------------------- GL_ARB_explicit_attrib_location -------------------- */
+
+#ifndef GL_ARB_explicit_attrib_location
+#define GL_ARB_explicit_attrib_location 1
+
+#define GLEW_ARB_explicit_attrib_location GLEW_GET_VAR(__GLEW_ARB_explicit_attrib_location)
+
+#endif /* GL_ARB_explicit_attrib_location */
+
+/* ------------------- GL_ARB_fragment_coord_conventions ------------------- */
+
+#ifndef GL_ARB_fragment_coord_conventions
+#define GL_ARB_fragment_coord_conventions 1
+
+#define GLEW_ARB_fragment_coord_conventions GLEW_GET_VAR(__GLEW_ARB_fragment_coord_conventions)
+
+#endif /* GL_ARB_fragment_coord_conventions */
+
 /* ------------------------ GL_ARB_fragment_program ------------------------ */
 
 #ifndef GL_ARB_fragment_program
@@ -2702,10 +3208,10 @@ typedef GLenum (GLAPIENTRY * PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target);
 typedef void (GLAPIENTRY * PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint* framebuffers);
 typedef void (GLAPIENTRY * PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint* renderbuffers);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
-typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTURLAYERPROC) (GLenum target,GLenum attachment, GLuint texture,GLint level,GLint layer);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint layer);
+typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target,GLenum attachment, GLuint texture,GLint level,GLint layer);
 typedef void (GLAPIENTRY * PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint* framebuffers);
 typedef void (GLAPIENTRY * PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint* renderbuffers);
 typedef void (GLAPIENTRY * PFNGLGENERATEMIPMAPPROC) (GLenum target);
@@ -2723,10 +3229,10 @@ typedef void (GLAPIENTRY * PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum targ
 #define glDeleteFramebuffers GLEW_GET_FUN(__glewDeleteFramebuffers)
 #define glDeleteRenderbuffers GLEW_GET_FUN(__glewDeleteRenderbuffers)
 #define glFramebufferRenderbuffer GLEW_GET_FUN(__glewFramebufferRenderbuffer)
-#define glFramebufferTexturLayer GLEW_GET_FUN(__glewFramebufferTexturLayer)
 #define glFramebufferTexture1D GLEW_GET_FUN(__glewFramebufferTexture1D)
 #define glFramebufferTexture2D GLEW_GET_FUN(__glewFramebufferTexture2D)
 #define glFramebufferTexture3D GLEW_GET_FUN(__glewFramebufferTexture3D)
+#define glFramebufferTextureLayer GLEW_GET_FUN(__glewFramebufferTextureLayer)
 #define glGenFramebuffers GLEW_GET_FUN(__glewGenFramebuffers)
 #define glGenRenderbuffers GLEW_GET_FUN(__glewGenRenderbuffers)
 #define glGenerateMipmap GLEW_GET_FUN(__glewGenerateMipmap)
@@ -2791,6 +3297,31 @@ typedef void (GLAPIENTRY * PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenu
 
 #endif /* GL_ARB_geometry_shader4 */
 
+/* --------------------------- GL_ARB_gpu_shader5 -------------------------- */
+
+#ifndef GL_ARB_gpu_shader5
+#define GL_ARB_gpu_shader5 1
+
+#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F
+#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A
+#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B
+#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C
+#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D
+#define GL_MAX_VERTEX_STREAMS 0x8E71
+
+#define GLEW_ARB_gpu_shader5 GLEW_GET_VAR(__GLEW_ARB_gpu_shader5)
+
+#endif /* GL_ARB_gpu_shader5 */
+
+/* ------------------------- GL_ARB_gpu_shader_fp64 ------------------------ */
+
+#ifndef GL_ARB_gpu_shader_fp64
+#define GL_ARB_gpu_shader_fp64 1
+
+#define GLEW_ARB_gpu_shader_fp64 GLEW_GET_VAR(__GLEW_ARB_gpu_shader_fp64)
+
+#endif /* GL_ARB_gpu_shader_fp64 */
+
 /* ------------------------ GL_ARB_half_float_pixel ------------------------ */
 
 #ifndef GL_ARB_half_float_pixel
@@ -3206,6 +3737,17 @@ typedef GLboolean (GLAPIENTRY * PFNGLISQUERYARBPROC) (GLuint id);
 
 #endif /* GL_ARB_occlusion_query */
 
+/* ------------------------ GL_ARB_occlusion_query2 ------------------------ */
+
+#ifndef GL_ARB_occlusion_query2
+#define GL_ARB_occlusion_query2 1
+
+#define GL_ANY_SAMPLES_PASSED 0x8C2F
+
+#define GLEW_ARB_occlusion_query2 GLEW_GET_VAR(__GLEW_ARB_occlusion_query2)
+
+#endif /* GL_ARB_occlusion_query2 */
+
 /* ----------------------- GL_ARB_pixel_buffer_object ---------------------- */
 
 #ifndef GL_ARB_pixel_buffer_object
@@ -3252,6 +3794,101 @@ typedef void (GLAPIENTRY * PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, GLfloat*
 
 #endif /* GL_ARB_point_sprite */
 
+/* ------------------------ GL_ARB_provoking_vertex ------------------------ */
+
+#ifndef GL_ARB_provoking_vertex
+#define GL_ARB_provoking_vertex 1
+
+#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C
+#define GL_FIRST_VERTEX_CONVENTION 0x8E4D
+#define GL_LAST_VERTEX_CONVENTION 0x8E4E
+#define GL_PROVOKING_VERTEX 0x8E4F
+
+typedef void (GLAPIENTRY * PFNGLPROVOKINGVERTEXPROC) (GLenum mode);
+
+#define glProvokingVertex GLEW_GET_FUN(__glewProvokingVertex)
+
+#define GLEW_ARB_provoking_vertex GLEW_GET_VAR(__GLEW_ARB_provoking_vertex)
+
+#endif /* GL_ARB_provoking_vertex */
+
+/* ------------------------- GL_ARB_sample_shading ------------------------- */
+
+#ifndef GL_ARB_sample_shading
+#define GL_ARB_sample_shading 1
+
+#define GL_SAMPLE_SHADING_ARB 0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37
+
+typedef void (GLAPIENTRY * PFNGLMINSAMPLESHADINGARBPROC) (GLclampf value);
+
+#define glMinSampleShadingARB GLEW_GET_FUN(__glewMinSampleShadingARB)
+
+#define GLEW_ARB_sample_shading GLEW_GET_VAR(__GLEW_ARB_sample_shading)
+
+#endif /* GL_ARB_sample_shading */
+
+/* ------------------------- GL_ARB_sampler_objects ------------------------ */
+
+#ifndef GL_ARB_sampler_objects
+#define GL_ARB_sampler_objects 1
+
+#define GL_SAMPLER_BINDING 0x8919
+
+typedef void (GLAPIENTRY * PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
+typedef void (GLAPIENTRY * PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint * samplers);
+typedef void (GLAPIENTRY * PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint* samplers);
+typedef void (GLAPIENTRY * PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint* params);
+typedef void (GLAPIENTRY * PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint* params);
+typedef void (GLAPIENTRY * PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat* params);
+typedef void (GLAPIENTRY * PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint* params);
+typedef GLboolean (GLAPIENTRY * PFNGLISSAMPLERPROC) (GLuint sampler);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint* params);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint* params);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat* params);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param);
+typedef void (GLAPIENTRY * PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint* params);
+
+#define glBindSampler GLEW_GET_FUN(__glewBindSampler)
+#define glDeleteSamplers GLEW_GET_FUN(__glewDeleteSamplers)
+#define glGenSamplers GLEW_GET_FUN(__glewGenSamplers)
+#define glGetSamplerParameterIiv GLEW_GET_FUN(__glewGetSamplerParameterIiv)
+#define glGetSamplerParameterIuiv GLEW_GET_FUN(__glewGetSamplerParameterIuiv)
+#define glGetSamplerParameterfv GLEW_GET_FUN(__glewGetSamplerParameterfv)
+#define glGetSamplerParameteriv GLEW_GET_FUN(__glewGetSamplerParameteriv)
+#define glIsSampler GLEW_GET_FUN(__glewIsSampler)
+#define glSamplerParameterIiv GLEW_GET_FUN(__glewSamplerParameterIiv)
+#define glSamplerParameterIuiv GLEW_GET_FUN(__glewSamplerParameterIuiv)
+#define glSamplerParameterf GLEW_GET_FUN(__glewSamplerParameterf)
+#define glSamplerParameterfv GLEW_GET_FUN(__glewSamplerParameterfv)
+#define glSamplerParameteri GLEW_GET_FUN(__glewSamplerParameteri)
+#define glSamplerParameteriv GLEW_GET_FUN(__glewSamplerParameteriv)
+
+#define GLEW_ARB_sampler_objects GLEW_GET_VAR(__GLEW_ARB_sampler_objects)
+
+#endif /* GL_ARB_sampler_objects */
+
+/* ------------------------ GL_ARB_seamless_cube_map ----------------------- */
+
+#ifndef GL_ARB_seamless_cube_map
+#define GL_ARB_seamless_cube_map 1
+
+#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
+
+#define GLEW_ARB_seamless_cube_map GLEW_GET_VAR(__GLEW_ARB_seamless_cube_map)
+
+#endif /* GL_ARB_seamless_cube_map */
+
+/* ----------------------- GL_ARB_shader_bit_encoding ---------------------- */
+
+#ifndef GL_ARB_shader_bit_encoding
+#define GL_ARB_shader_bit_encoding 1
+
+#define GLEW_ARB_shader_bit_encoding GLEW_GET_VAR(__GLEW_ARB_shader_bit_encoding)
+
+#endif /* GL_ARB_shader_bit_encoding */
+
 /* ------------------------- GL_ARB_shader_objects ------------------------- */
 
 #ifndef GL_ARB_shader_objects
@@ -3379,6 +4016,52 @@ typedef void (GLAPIENTRY * PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj)
 
 #endif /* GL_ARB_shader_objects */
 
+/* ------------------------ GL_ARB_shader_subroutine ----------------------- */
+
+#ifndef GL_ARB_shader_subroutine
+#define GL_ARB_shader_subroutine 1
+
+#define GL_ACTIVE_SUBROUTINES 0x8DE5
+#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6
+#define GL_MAX_SUBROUTINES 0x8DE7
+#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8
+#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47
+#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48
+#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49
+#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A
+#define GL_COMPATIBLE_SUBROUTINES 0x8E4B
+
+typedef void (GLAPIENTRY * PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, char *name);
+typedef void (GLAPIENTRY * PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei* length, char *name);
+typedef void (GLAPIENTRY * PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint* values);
+typedef void (GLAPIENTRY * PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint* values);
+typedef GLuint (GLAPIENTRY * PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const char* name);
+typedef GLint (GLAPIENTRY * PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const char* name);
+typedef void (GLAPIENTRY * PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint* params);
+typedef void (GLAPIENTRY * PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint* indices);
+
+#define glGetActiveSubroutineName GLEW_GET_FUN(__glewGetActiveSubroutineName)
+#define glGetActiveSubroutineUniformName GLEW_GET_FUN(__glewGetActiveSubroutineUniformName)
+#define glGetActiveSubroutineUniformiv GLEW_GET_FUN(__glewGetActiveSubroutineUniformiv)
+#define glGetProgramStageiv GLEW_GET_FUN(__glewGetProgramStageiv)
+#define glGetSubroutineIndex GLEW_GET_FUN(__glewGetSubroutineIndex)
+#define glGetSubroutineUniformLocation GLEW_GET_FUN(__glewGetSubroutineUniformLocation)
+#define glGetUniformSubroutineuiv GLEW_GET_FUN(__glewGetUniformSubroutineuiv)
+#define glUniformSubroutinesuiv GLEW_GET_FUN(__glewUniformSubroutinesuiv)
+
+#define GLEW_ARB_shader_subroutine GLEW_GET_VAR(__GLEW_ARB_shader_subroutine)
+
+#endif /* GL_ARB_shader_subroutine */
+
+/* ----------------------- GL_ARB_shader_texture_lod ----------------------- */
+
+#ifndef GL_ARB_shader_texture_lod
+#define GL_ARB_shader_texture_lod 1
+
+#define GLEW_ARB_shader_texture_lod GLEW_GET_VAR(__GLEW_ARB_shader_texture_lod)
+
+#endif /* GL_ARB_shader_texture_lod */
+
 /* ---------------------- GL_ARB_shading_language_100 ---------------------- */
 
 #ifndef GL_ARB_shading_language_100
@@ -3390,6 +4073,33 @@ typedef void (GLAPIENTRY * PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj)
 
 #endif /* GL_ARB_shading_language_100 */
 
+/* -------------------- GL_ARB_shading_language_include -------------------- */
+
+#ifndef GL_ARB_shading_language_include
+#define GL_ARB_shading_language_include 1
+
+#define GL_SHADER_INCLUDE_ARB 0x8DAE
+#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9
+#define GL_NAMED_STRING_TYPE_ARB 0x8DEA
+
+typedef void (GLAPIENTRY * PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const char ** path, const GLint *length);
+typedef void (GLAPIENTRY * PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const char* name);
+typedef void (GLAPIENTRY * PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const char* name, GLsizei bufSize, GLint *stringlen, char *string);
+typedef void (GLAPIENTRY * PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const char* name, GLenum pname, GLint *params);
+typedef GLboolean (GLAPIENTRY * PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const char* name);
+typedef void (GLAPIENTRY * PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const char* name, GLint stringlen, const char *string);
+
+#define glCompileShaderIncludeARB GLEW_GET_FUN(__glewCompileShaderIncludeARB)
+#define glDeleteNamedStringARB GLEW_GET_FUN(__glewDeleteNamedStringARB)
+#define glGetNamedStringARB GLEW_GET_FUN(__glewGetNamedStringARB)
+#define glGetNamedStringivARB GLEW_GET_FUN(__glewGetNamedStringivARB)
+#define glIsNamedStringARB GLEW_GET_FUN(__glewIsNamedStringARB)
+#define glNamedStringARB GLEW_GET_FUN(__glewNamedStringARB)
+
+#define GLEW_ARB_shading_language_include GLEW_GET_VAR(__GLEW_ARB_shading_language_include)
+
+#endif /* GL_ARB_shading_language_include */
+
 /* ----------------------------- GL_ARB_shadow ----------------------------- */
 
 #ifndef GL_ARB_shadow
@@ -3414,6 +4124,95 @@ typedef void (GLAPIENTRY * PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj)
 
 #endif /* GL_ARB_shadow_ambient */
 
+/* ------------------------------ GL_ARB_sync ------------------------------ */
+
+#ifndef GL_ARB_sync
+#define GL_ARB_sync 1
+
+#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001
+#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111
+#define GL_OBJECT_TYPE 0x9112
+#define GL_SYNC_CONDITION 0x9113
+#define GL_SYNC_STATUS 0x9114
+#define GL_SYNC_FLAGS 0x9115
+#define GL_SYNC_FENCE 0x9116
+#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
+#define GL_UNSIGNALED 0x9118
+#define GL_SIGNALED 0x9119
+#define GL_ALREADY_SIGNALED 0x911A
+#define GL_TIMEOUT_EXPIRED 0x911B
+#define GL_CONDITION_SATISFIED 0x911C
+#define GL_WAIT_FAILED 0x911D
+#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF
+
+typedef GLenum (GLAPIENTRY * PFNGLCLIENTWAITSYNCPROC) (GLsync GLsync,GLbitfield flags,GLuint64 timeout);
+typedef void (GLAPIENTRY * PFNGLDELETESYNCPROC) (GLsync GLsync);
+typedef GLsync (GLAPIENTRY * PFNGLFENCESYNCPROC) (GLenum condition,GLbitfield flags);
+typedef void (GLAPIENTRY * PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64* params);
+typedef void (GLAPIENTRY * PFNGLGETSYNCIVPROC) (GLsync GLsync,GLenum pname,GLsizei bufSize,GLsizei* length, GLint *values);
+typedef GLboolean (GLAPIENTRY * PFNGLISSYNCPROC) (GLsync GLsync);
+typedef void (GLAPIENTRY * PFNGLWAITSYNCPROC) (GLsync GLsync,GLbitfield flags,GLuint64 timeout);
+
+#define glClientWaitSync GLEW_GET_FUN(__glewClientWaitSync)
+#define glDeleteSync GLEW_GET_FUN(__glewDeleteSync)
+#define glFenceSync GLEW_GET_FUN(__glewFenceSync)
+#define glGetInteger64v GLEW_GET_FUN(__glewGetInteger64v)
+#define glGetSynciv GLEW_GET_FUN(__glewGetSynciv)
+#define glIsSync GLEW_GET_FUN(__glewIsSync)
+#define glWaitSync GLEW_GET_FUN(__glewWaitSync)
+
+#define GLEW_ARB_sync GLEW_GET_VAR(__GLEW_ARB_sync)
+
+#endif /* GL_ARB_sync */
+
+/* ----------------------- GL_ARB_tessellation_shader ---------------------- */
+
+#ifndef GL_ARB_tessellation_shader
+#define GL_ARB_tessellation_shader 1
+
+#define GL_PATCHES 0xE
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1
+#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C
+#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D
+#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E
+#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F
+#define GL_PATCH_VERTICES 0x8E72
+#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73
+#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74
+#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75
+#define GL_TESS_GEN_MODE 0x8E76
+#define GL_TESS_GEN_SPACING 0x8E77
+#define GL_TESS_GEN_VERTEX_ORDER 0x8E78
+#define GL_TESS_GEN_POINT_MODE 0x8E79
+#define GL_ISOLINES 0x8E7A
+#define GL_FRACTIONAL_ODD 0x8E7B
+#define GL_FRACTIONAL_EVEN 0x8E7C
+#define GL_MAX_PATCH_VERTICES 0x8E7D
+#define GL_MAX_TESS_GEN_LEVEL 0x8E7E
+#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F
+#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80
+#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81
+#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82
+#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83
+#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84
+#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85
+#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86
+#define GL_TESS_EVALUATION_SHADER 0x8E87
+#define GL_TESS_CONTROL_SHADER 0x8E88
+#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89
+#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A
+
+typedef void (GLAPIENTRY * PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat* values);
+typedef void (GLAPIENTRY * PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value);
+
+#define glPatchParameterfv GLEW_GET_FUN(__glewPatchParameterfv)
+#define glPatchParameteri GLEW_GET_FUN(__glewPatchParameteri)
+
+#define GLEW_ARB_tessellation_shader GLEW_GET_VAR(__GLEW_ARB_tessellation_shader)
+
+#endif /* GL_ARB_tessellation_shader */
+
 /* ---------------------- GL_ARB_texture_border_clamp ---------------------- */
 
 #ifndef GL_ARB_texture_border_clamp
@@ -3444,6 +4243,15 @@ typedef void (GLAPIENTRY * PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum interna
 
 #endif /* GL_ARB_texture_buffer_object */
 
+/* ------------------- GL_ARB_texture_buffer_object_rgb32 ------------------ */
+
+#ifndef GL_ARB_texture_buffer_object_rgb32
+#define GL_ARB_texture_buffer_object_rgb32 1
+
+#define GLEW_ARB_texture_buffer_object_rgb32 GLEW_GET_VAR(__GLEW_ARB_texture_buffer_object_rgb32)
+
+#endif /* GL_ARB_texture_buffer_object_rgb32 */
+
 /* ----------------------- GL_ARB_texture_compression ---------------------- */
 
 #ifndef GL_ARB_texture_compression
@@ -3481,6 +4289,20 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_compression */
 
+/* -------------------- GL_ARB_texture_compression_bptc -------------------- */
+
+#ifndef GL_ARB_texture_compression_bptc
+#define GL_ARB_texture_compression_bptc 1
+
+#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C
+#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D
+#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E
+#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F
+
+#define GLEW_ARB_texture_compression_bptc GLEW_GET_VAR(__GLEW_ARB_texture_compression_bptc)
+
+#endif /* GL_ARB_texture_compression_bptc */
+
 /* -------------------- GL_ARB_texture_compression_rgtc -------------------- */
 
 #ifndef GL_ARB_texture_compression_rgtc
@@ -3517,6 +4339,23 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_cube_map */
 
+/* --------------------- GL_ARB_texture_cube_map_array --------------------- */
+
+#ifndef GL_ARB_texture_cube_map_array
+#define GL_ARB_texture_cube_map_array 1
+
+#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B
+#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F
+
+#define GLEW_ARB_texture_cube_map_array GLEW_GET_VAR(__GLEW_ARB_texture_cube_map_array)
+
+#endif /* GL_ARB_texture_cube_map_array */
+
 /* ------------------------- GL_ARB_texture_env_add ------------------------ */
 
 #ifndef GL_ARB_texture_env_add
@@ -3609,6 +4448,19 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_float */
 
+/* ------------------------- GL_ARB_texture_gather ------------------------- */
+
+#ifndef GL_ARB_texture_gather
+#define GL_ARB_texture_gather 1
+
+#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
+
+#define GLEW_ARB_texture_gather GLEW_GET_VAR(__GLEW_ARB_texture_gather)
+
+#endif /* GL_ARB_texture_gather */
+
 /* --------------------- GL_ARB_texture_mirrored_repeat -------------------- */
 
 #ifndef GL_ARB_texture_mirrored_repeat
@@ -3620,6 +4472,47 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_mirrored_repeat */
 
+/* ----------------------- GL_ARB_texture_multisample ---------------------- */
+
+#ifndef GL_ARB_texture_multisample
+#define GL_ARB_texture_multisample 1
+
+#define GL_SAMPLE_POSITION 0x8E50
+#define GL_SAMPLE_MASK 0x8E51
+#define GL_SAMPLE_MASK_VALUE 0x8E52
+#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59
+#define GL_TEXTURE_2D_MULTISAMPLE 0x9100
+#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101
+#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
+#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103
+#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104
+#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105
+#define GL_TEXTURE_SAMPLES 0x9106
+#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107
+#define GL_SAMPLER_2D_MULTISAMPLE 0x9108
+#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109
+#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A
+#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B
+#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C
+#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D
+#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E
+#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F
+#define GL_MAX_INTEGER_SAMPLES 0x9110
+
+typedef void (GLAPIENTRY * PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat* val);
+typedef void (GLAPIENTRY * PFNGLSAMPLEMASKIPROC) (GLuint index, GLbitfield mask);
+typedef void (GLAPIENTRY * PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+typedef void (GLAPIENTRY * PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
+
+#define glGetMultisamplefv GLEW_GET_FUN(__glewGetMultisamplefv)
+#define glSampleMaski GLEW_GET_FUN(__glewSampleMaski)
+#define glTexImage2DMultisample GLEW_GET_FUN(__glewTexImage2DMultisample)
+#define glTexImage3DMultisample GLEW_GET_FUN(__glewTexImage3DMultisample)
+
+#define GLEW_ARB_texture_multisample GLEW_GET_VAR(__GLEW_ARB_texture_multisample)
+
+#endif /* GL_ARB_texture_multisample */
+
 /* -------------------- GL_ARB_texture_non_power_of_two -------------------- */
 
 #ifndef GL_ARB_texture_non_power_of_two
@@ -3629,6 +4522,15 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_non_power_of_two */
 
+/* ------------------------ GL_ARB_texture_query_lod ----------------------- */
+
+#ifndef GL_ARB_texture_query_lod
+#define GL_ARB_texture_query_lod 1
+
+#define GLEW_ARB_texture_query_lod GLEW_GET_VAR(__GLEW_ARB_texture_query_lod)
+
+#endif /* GL_ARB_texture_query_lod */
+
 /* ------------------------ GL_ARB_texture_rectangle ----------------------- */
 
 #ifndef GL_ARB_texture_rectangle
@@ -3651,6 +4553,8 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 #define GL_ARB_texture_rg 1
 
 #define GL_RED 0x1903
+#define GL_COMPRESSED_RED 0x8225
+#define GL_COMPRESSED_RG 0x8226
 #define GL_RG 0x8227
 #define GL_RG_INTEGER 0x8228
 #define GL_R8 0x8229
@@ -3678,6 +4582,104 @@ typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GL
 
 #endif /* GL_ARB_texture_rg */
 
+/* ----------------------- GL_ARB_texture_rgb10_a2ui ----------------------- */
+
+#ifndef GL_ARB_texture_rgb10_a2ui
+#define GL_ARB_texture_rgb10_a2ui 1
+
+#define GL_RGB10_A2UI 0x906F
+
+#define GLEW_ARB_texture_rgb10_a2ui GLEW_GET_VAR(__GLEW_ARB_texture_rgb10_a2ui)
+
+#endif /* GL_ARB_texture_rgb10_a2ui */
+
+/* ------------------------- GL_ARB_texture_swizzle ------------------------ */
+
+#ifndef GL_ARB_texture_swizzle
+#define GL_ARB_texture_swizzle 1
+
+#define GL_TEXTURE_SWIZZLE_R 0x8E42
+#define GL_TEXTURE_SWIZZLE_G 0x8E43
+#define GL_TEXTURE_SWIZZLE_B 0x8E44
+#define GL_TEXTURE_SWIZZLE_A 0x8E45
+#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46
+
+#define GLEW_ARB_texture_swizzle GLEW_GET_VAR(__GLEW_ARB_texture_swizzle)
+
+#endif /* GL_ARB_texture_swizzle */
+
+/* --------------------------- GL_ARB_timer_query -------------------------- */
+
+#ifndef GL_ARB_timer_query
+#define GL_ARB_timer_query 1
+
+#define GL_TIME_ELAPSED 0x88BF
+#define GL_TIMESTAMP 0x8E28
+
+typedef void (GLAPIENTRY * PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64* params);
+typedef void (GLAPIENTRY * PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64* params);
+typedef void (GLAPIENTRY * PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target);
+
+#define glGetQueryObjecti64v GLEW_GET_FUN(__glewGetQueryObjecti64v)
+#define glGetQueryObjectui64v GLEW_GET_FUN(__glewGetQueryObjectui64v)
+#define glQueryCounter GLEW_GET_FUN(__glewQueryCounter)
+
+#define GLEW_ARB_timer_query GLEW_GET_VAR(__GLEW_ARB_timer_query)
+
+#endif /* GL_ARB_timer_query */
+
+/* ----------------------- GL_ARB_transform_feedback2 ---------------------- */
+
+#ifndef GL_ARB_transform_feedback2
+#define GL_ARB_transform_feedback2 1
+
+#define GL_TRANSFORM_FEEDBACK 0x8E22
+#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23
+#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24
+#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25
+
+typedef void (GLAPIENTRY * PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id);
+typedef void (GLAPIENTRY * PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint* ids);
+typedef void (GLAPIENTRY * PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id);
+typedef void (GLAPIENTRY * PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint* ids);
+typedef GLboolean (GLAPIENTRY * PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id);
+typedef void (GLAPIENTRY * PFNGLPAUSETRANSFORMFEEDBACKPROC) (void);
+typedef void (GLAPIENTRY * PFNGLRESUMETRANSFORMFEEDBACKPROC) (void);
+
+#define glBindTransformFeedback GLEW_GET_FUN(__glewBindTransformFeedback)
+#define glDeleteTransformFeedbacks GLEW_GET_FUN(__glewDeleteTransformFeedbacks)
+#define glDrawTransformFeedback GLEW_GET_FUN(__glewDrawTransformFeedback)
+#define glGenTransformFeedbacks GLEW_GET_FUN(__glewGenTransformFeedbacks)
+#define glIsTransformFeedback GLEW_GET_FUN(__glewIsTransformFeedback)
+#define glPauseTransformFeedback GLEW_GET_FUN(__glewPauseTransformFeedback)
+#define glResumeTransformFeedback GLEW_GET_FUN(__glewResumeTransformFeedback)
+
+#define GLEW_ARB_transform_feedback2 GLEW_GET_VAR(__GLEW_ARB_transform_feedback2)
+
+#endif /* GL_ARB_transform_feedback2 */
+
+/* ----------------------- GL_ARB_transform_feedback3 ---------------------- */
+
+#ifndef GL_ARB_transform_feedback3
+#define GL_ARB_transform_feedback3 1
+
+#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70
+#define GL_MAX_VERTEX_STREAMS 0x8E71
+
+typedef void (GLAPIENTRY * PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id);
+typedef void (GLAPIENTRY * PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream);
+typedef void (GLAPIENTRY * PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index);
+typedef void (GLAPIENTRY * PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint* params);
+
+#define glBeginQueryIndexed GLEW_GET_FUN(__glewBeginQueryIndexed)
+#define glDrawTransformFeedbackStream GLEW_GET_FUN(__glewDrawTransformFeedbackStream)
+#define glEndQueryIndexed GLEW_GET_FUN(__glewEndQueryIndexed)
+#define glGetQueryIndexediv GLEW_GET_FUN(__glewGetQueryIndexediv)
+
+#define GLEW_ARB_transform_feedback3 GLEW_GET_VAR(__GLEW_ARB_transform_feedback3)
+
+#endif /* GL_ARB_transform_feedback3 */
+
 /* ------------------------ GL_ARB_transpose_matrix ------------------------ */
 
 #ifndef GL_ARB_transpose_matrix
@@ -3702,6 +4704,82 @@ typedef void (GLAPIENTRY * PFNGLMULTTRANSPOSEMATRIXFARBPROC) (GLfloat m[16]);
 
 #endif /* GL_ARB_transpose_matrix */
 
+/* ---------------------- GL_ARB_uniform_buffer_object --------------------- */
+
+#ifndef GL_ARB_uniform_buffer_object
+#define GL_ARB_uniform_buffer_object 1
+
+#define GL_UNIFORM_BUFFER 0x8A11
+#define GL_UNIFORM_BUFFER_BINDING 0x8A28
+#define GL_UNIFORM_BUFFER_START 0x8A29
+#define GL_UNIFORM_BUFFER_SIZE 0x8A2A
+#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B
+#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C
+#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D
+#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E
+#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F
+#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30
+#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31
+#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32
+#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33
+#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34
+#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35
+#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36
+#define GL_UNIFORM_TYPE 0x8A37
+#define GL_UNIFORM_SIZE 0x8A38
+#define GL_UNIFORM_NAME_LENGTH 0x8A39
+#define GL_UNIFORM_BLOCK_INDEX 0x8A3A
+#define GL_UNIFORM_OFFSET 0x8A3B
+#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C
+#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D
+#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E
+#define GL_UNIFORM_BLOCK_BINDING 0x8A3F
+#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40
+#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41
+#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42
+#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43
+#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 0xFFFFFFFF
+
+typedef void (GLAPIENTRY * PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer);
+typedef void (GLAPIENTRY * PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+typedef void (GLAPIENTRY * PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, char* uniformBlockName);
+typedef void (GLAPIENTRY * PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params);
+typedef void (GLAPIENTRY * PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei* length, char* uniformName);
+typedef void (GLAPIENTRY * PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params);
+typedef void (GLAPIENTRY * PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint* data);
+typedef GLuint (GLAPIENTRY * PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const char* uniformBlockName);
+typedef void (GLAPIENTRY * PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const char** uniformNames, GLuint* uniformIndices);
+typedef void (GLAPIENTRY * PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+
+#define glBindBufferBase GLEW_GET_FUN(__glewBindBufferBase)
+#define glBindBufferRange GLEW_GET_FUN(__glewBindBufferRange)
+#define glGetActiveUniformBlockName GLEW_GET_FUN(__glewGetActiveUniformBlockName)
+#define glGetActiveUniformBlockiv GLEW_GET_FUN(__glewGetActiveUniformBlockiv)
+#define glGetActiveUniformName GLEW_GET_FUN(__glewGetActiveUniformName)
+#define glGetActiveUniformsiv GLEW_GET_FUN(__glewGetActiveUniformsiv)
+#define glGetIntegeri_v GLEW_GET_FUN(__glewGetIntegeri_v)
+#define glGetUniformBlockIndex GLEW_GET_FUN(__glewGetUniformBlockIndex)
+#define glGetUniformIndices GLEW_GET_FUN(__glewGetUniformIndices)
+#define glUniformBlockBinding GLEW_GET_FUN(__glewUniformBlockBinding)
+
+#define GLEW_ARB_uniform_buffer_object GLEW_GET_VAR(__GLEW_ARB_uniform_buffer_object)
+
+#endif /* GL_ARB_uniform_buffer_object */
+
+/* ------------------------ GL_ARB_vertex_array_bgra ----------------------- */
+
+#ifndef GL_ARB_vertex_array_bgra
+#define GL_ARB_vertex_array_bgra 1
+
+#define GL_BGRA 0x80E1
+
+#define GLEW_ARB_vertex_array_bgra GLEW_GET_VAR(__GLEW_ARB_vertex_array_bgra)
+
+#endif /* GL_ARB_vertex_array_bgra */
+
 /* ----------------------- GL_ARB_vertex_array_object ---------------------- */
 
 #ifndef GL_ARB_vertex_array_object
@@ -4105,6 +5183,96 @@ typedef GLint (GLAPIENTRY * PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programO
 
 #endif /* GL_ARB_vertex_shader */
 
+/* ------------------- GL_ARB_vertex_type_2_10_10_10_rev ------------------- */
+
+#ifndef GL_ARB_vertex_type_2_10_10_10_rev
+#define GL_ARB_vertex_type_2_10_10_10_rev 1
+
+#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
+#define GL_INT_2_10_10_10_REV 0x8D9F
+
+typedef void (GLAPIENTRY * PFNGLCOLORP3UIPROC) (GLenum type, GLuint color);
+typedef void (GLAPIENTRY * PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint* color);
+typedef void (GLAPIENTRY * PFNGLCOLORP4UIPROC) (GLenum type, GLuint color);
+typedef void (GLAPIENTRY * PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint* color);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color);
+typedef void (GLAPIENTRY * PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint* color);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint* coords);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint* value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value);
+typedef void (GLAPIENTRY * PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint* value);
+
+#define glColorP3ui GLEW_GET_FUN(__glewColorP3ui)
+#define glColorP3uiv GLEW_GET_FUN(__glewColorP3uiv)
+#define glColorP4ui GLEW_GET_FUN(__glewColorP4ui)
+#define glColorP4uiv GLEW_GET_FUN(__glewColorP4uiv)
+#define glMultiTexCoordP1ui GLEW_GET_FUN(__glewMultiTexCoordP1ui)
+#define glMultiTexCoordP1uiv GLEW_GET_FUN(__glewMultiTexCoordP1uiv)
+#define glMultiTexCoordP2ui GLEW_GET_FUN(__glewMultiTexCoordP2ui)
+#define glMultiTexCoordP2uiv GLEW_GET_FUN(__glewMultiTexCoordP2uiv)
+#define glMultiTexCoordP3ui GLEW_GET_FUN(__glewMultiTexCoordP3ui)
+#define glMultiTexCoordP3uiv GLEW_GET_FUN(__glewMultiTexCoordP3uiv)
+#define glMultiTexCoordP4ui GLEW_GET_FUN(__glewMultiTexCoordP4ui)
+#define glMultiTexCoordP4uiv GLEW_GET_FUN(__glewMultiTexCoordP4uiv)
+#define glNormalP3ui GLEW_GET_FUN(__glewNormalP3ui)
+#define glNormalP3uiv GLEW_GET_FUN(__glewNormalP3uiv)
+#define glSecondaryColorP3ui GLEW_GET_FUN(__glewSecondaryColorP3ui)
+#define glSecondaryColorP3uiv GLEW_GET_FUN(__glewSecondaryColorP3uiv)
+#define glTexCoordP1ui GLEW_GET_FUN(__glewTexCoordP1ui)
+#define glTexCoordP1uiv GLEW_GET_FUN(__glewTexCoordP1uiv)
+#define glTexCoordP2ui GLEW_GET_FUN(__glewTexCoordP2ui)
+#define glTexCoordP2uiv GLEW_GET_FUN(__glewTexCoordP2uiv)
+#define glTexCoordP3ui GLEW_GET_FUN(__glewTexCoordP3ui)
+#define glTexCoordP3uiv GLEW_GET_FUN(__glewTexCoordP3uiv)
+#define glTexCoordP4ui GLEW_GET_FUN(__glewTexCoordP4ui)
+#define glTexCoordP4uiv GLEW_GET_FUN(__glewTexCoordP4uiv)
+#define glVertexAttribP1ui GLEW_GET_FUN(__glewVertexAttribP1ui)
+#define glVertexAttribP1uiv GLEW_GET_FUN(__glewVertexAttribP1uiv)
+#define glVertexAttribP2ui GLEW_GET_FUN(__glewVertexAttribP2ui)
+#define glVertexAttribP2uiv GLEW_GET_FUN(__glewVertexAttribP2uiv)
+#define glVertexAttribP3ui GLEW_GET_FUN(__glewVertexAttribP3ui)
+#define glVertexAttribP3uiv GLEW_GET_FUN(__glewVertexAttribP3uiv)
+#define glVertexAttribP4ui GLEW_GET_FUN(__glewVertexAttribP4ui)
+#define glVertexAttribP4uiv GLEW_GET_FUN(__glewVertexAttribP4uiv)
+#define glVertexP2ui GLEW_GET_FUN(__glewVertexP2ui)
+#define glVertexP2uiv GLEW_GET_FUN(__glewVertexP2uiv)
+#define glVertexP3ui GLEW_GET_FUN(__glewVertexP3ui)
+#define glVertexP3uiv GLEW_GET_FUN(__glewVertexP3uiv)
+#define glVertexP4ui GLEW_GET_FUN(__glewVertexP4ui)
+#define glVertexP4uiv GLEW_GET_FUN(__glewVertexP4uiv)
+
+#define GLEW_ARB_vertex_type_2_10_10_10_rev GLEW_GET_VAR(__GLEW_ARB_vertex_type_2_10_10_10_rev)
+
+#endif /* GL_ARB_vertex_type_2_10_10_10_rev */
+
 /* --------------------------- GL_ARB_window_pos --------------------------- */
 
 #ifndef GL_ARB_window_pos
@@ -4390,6 +5558,19 @@ typedef void (GLAPIENTRY * PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
 
 #endif /* GL_ATI_map_object_buffer */
 
+/* ----------------------------- GL_ATI_meminfo ---------------------------- */
+
+#ifndef GL_ATI_meminfo
+#define GL_ATI_meminfo 1
+
+#define GL_VBO_FREE_MEMORY_ATI 0x87FB
+#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC
+#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD
+
+#define GLEW_ATI_meminfo GLEW_GET_VAR(__GLEW_ATI_meminfo)
+
+#endif /* GL_ATI_meminfo */
+
 /* -------------------------- GL_ATI_pn_triangles -------------------------- */
 
 #ifndef GL_ATI_pn_triangles
@@ -5007,6 +6188,10 @@ typedef void (GLAPIENTRY * PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint
 #ifndef GL_EXT_cull_vertex
 #define GL_EXT_cull_vertex 1
 
+#define GL_CULL_VERTEX_EXT 0x81AA
+#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB
+#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
+
 typedef void (GLAPIENTRY * PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble* params);
 typedef void (GLAPIENTRY * PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat* params);
 
@@ -5068,7 +6253,14 @@ typedef void (GLAPIENTRY * PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, G
 typedef void (GLAPIENTRY * PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
 typedef void (GLAPIENTRY * PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
 typedef void (GLAPIENTRY * PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);
+typedef void (GLAPIENTRY * PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index);
+typedef void (GLAPIENTRY * PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index);
+typedef void (GLAPIENTRY * PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array);
 typedef void (GLAPIENTRY * PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);
+typedef void (GLAPIENTRY * PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index);
+typedef void (GLAPIENTRY * PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index);
+typedef void (GLAPIENTRY * PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array);
+typedef void (GLAPIENTRY * PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum* bufs);
 typedef void (GLAPIENTRY * PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);
@@ -5076,8 +6268,10 @@ typedef void (GLAPIENTRY * PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit,
 typedef void (GLAPIENTRY * PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target);
 typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, void* img);
 typedef void (GLAPIENTRY * PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, void* img);
-typedef void (GLAPIENTRY * PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum pname, GLuint index, GLdouble* params);
-typedef void (GLAPIENTRY * PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum pname, GLuint index, GLfloat* params);
+typedef void (GLAPIENTRY * PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble* params);
+typedef void (GLAPIENTRY * PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble* params);
+typedef void (GLAPIENTRY * PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat* params);
+typedef void (GLAPIENTRY * PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat* params);
 typedef void (GLAPIENTRY * PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint* param);
 typedef void (GLAPIENTRY * PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat* params);
 typedef void (GLAPIENTRY * PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint* params);
@@ -5102,7 +6296,8 @@ typedef void (GLAPIENTRY * PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint
 typedef void (GLAPIENTRY * PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void* string);
 typedef void (GLAPIENTRY * PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint* params);
 typedef void (GLAPIENTRY * PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint* params);
-typedef void (GLAPIENTRY * PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum pname, GLuint index, GLvoid** params);
+typedef void (GLAPIENTRY * PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLvoid** params);
+typedef void (GLAPIENTRY * PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, GLvoid** params);
 typedef void (GLAPIENTRY * PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void* pixels);
 typedef void (GLAPIENTRY * PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat* params);
 typedef void (GLAPIENTRY * PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint* params);
@@ -5110,7 +6305,12 @@ typedef void (GLAPIENTRY * PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture,
 typedef void (GLAPIENTRY * PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint* params);
 typedef void (GLAPIENTRY * PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat* params);
 typedef void (GLAPIENTRY * PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint* params);
+typedef void (GLAPIENTRY * PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint* param);
+typedef void (GLAPIENTRY * PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint* param);
+typedef void (GLAPIENTRY * PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLvoid** param);
+typedef void (GLAPIENTRY * PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, GLvoid** param);
 typedef GLvoid * (GLAPIENTRY * PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access);
+typedef GLvoid * (GLAPIENTRY * PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);
 typedef void (GLAPIENTRY * PFNGLMATRIXFRUSTUMEXTPROC) (GLenum matrixMode, GLdouble l, GLdouble r, GLdouble b, GLdouble t, GLdouble n, GLdouble f);
 typedef void (GLAPIENTRY * PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum matrixMode);
 typedef void (GLAPIENTRY * PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum matrixMode, const GLdouble* m);
@@ -5157,6 +6357,7 @@ typedef void (GLAPIENTRY * PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLen
 typedef void (GLAPIENTRY * PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
 typedef void (GLAPIENTRY * PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void* data, GLenum usage);
 typedef void (GLAPIENTRY * PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void* data);
+typedef void (GLAPIENTRY * PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
 typedef void (GLAPIENTRY * PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
 typedef void (GLAPIENTRY * PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
 typedef void (GLAPIENTRY * PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
@@ -5228,6 +6429,17 @@ typedef void (GLAPIENTRY * PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenu
 typedef void (GLAPIENTRY * PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels);
 typedef void (GLAPIENTRY * PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
 typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset);
 
 #define glBindMultiTextureEXT GLEW_GET_FUN(__glewBindMultiTextureEXT)
 #define glCheckNamedFramebufferStatusEXT GLEW_GET_FUN(__glewCheckNamedFramebufferStatusEXT)
@@ -5255,7 +6467,14 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glCopyTextureSubImage2DEXT GLEW_GET_FUN(__glewCopyTextureSubImage2DEXT)
 #define glCopyTextureSubImage3DEXT GLEW_GET_FUN(__glewCopyTextureSubImage3DEXT)
 #define glDisableClientStateIndexedEXT GLEW_GET_FUN(__glewDisableClientStateIndexedEXT)
+#define glDisableClientStateiEXT GLEW_GET_FUN(__glewDisableClientStateiEXT)
+#define glDisableVertexArrayAttribEXT GLEW_GET_FUN(__glewDisableVertexArrayAttribEXT)
+#define glDisableVertexArrayEXT GLEW_GET_FUN(__glewDisableVertexArrayEXT)
 #define glEnableClientStateIndexedEXT GLEW_GET_FUN(__glewEnableClientStateIndexedEXT)
+#define glEnableClientStateiEXT GLEW_GET_FUN(__glewEnableClientStateiEXT)
+#define glEnableVertexArrayAttribEXT GLEW_GET_FUN(__glewEnableVertexArrayAttribEXT)
+#define glEnableVertexArrayEXT GLEW_GET_FUN(__glewEnableVertexArrayEXT)
+#define glFlushMappedNamedBufferRangeEXT GLEW_GET_FUN(__glewFlushMappedNamedBufferRangeEXT)
 #define glFramebufferDrawBufferEXT GLEW_GET_FUN(__glewFramebufferDrawBufferEXT)
 #define glFramebufferDrawBuffersEXT GLEW_GET_FUN(__glewFramebufferDrawBuffersEXT)
 #define glFramebufferReadBufferEXT GLEW_GET_FUN(__glewFramebufferReadBufferEXT)
@@ -5264,7 +6483,9 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glGetCompressedMultiTexImageEXT GLEW_GET_FUN(__glewGetCompressedMultiTexImageEXT)
 #define glGetCompressedTextureImageEXT GLEW_GET_FUN(__glewGetCompressedTextureImageEXT)
 #define glGetDoubleIndexedvEXT GLEW_GET_FUN(__glewGetDoubleIndexedvEXT)
+#define glGetDoublei_vEXT GLEW_GET_FUN(__glewGetDoublei_vEXT)
 #define glGetFloatIndexedvEXT GLEW_GET_FUN(__glewGetFloatIndexedvEXT)
+#define glGetFloati_vEXT GLEW_GET_FUN(__glewGetFloati_vEXT)
 #define glGetFramebufferParameterivEXT GLEW_GET_FUN(__glewGetFramebufferParameterivEXT)
 #define glGetMultiTexEnvfvEXT GLEW_GET_FUN(__glewGetMultiTexEnvfvEXT)
 #define glGetMultiTexEnvivEXT GLEW_GET_FUN(__glewGetMultiTexEnvivEXT)
@@ -5290,6 +6511,7 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glGetNamedProgramivEXT GLEW_GET_FUN(__glewGetNamedProgramivEXT)
 #define glGetNamedRenderbufferParameterivEXT GLEW_GET_FUN(__glewGetNamedRenderbufferParameterivEXT)
 #define glGetPointerIndexedvEXT GLEW_GET_FUN(__glewGetPointerIndexedvEXT)
+#define glGetPointeri_vEXT GLEW_GET_FUN(__glewGetPointeri_vEXT)
 #define glGetTextureImageEXT GLEW_GET_FUN(__glewGetTextureImageEXT)
 #define glGetTextureLevelParameterfvEXT GLEW_GET_FUN(__glewGetTextureLevelParameterfvEXT)
 #define glGetTextureLevelParameterivEXT GLEW_GET_FUN(__glewGetTextureLevelParameterivEXT)
@@ -5297,7 +6519,12 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glGetTextureParameterIuivEXT GLEW_GET_FUN(__glewGetTextureParameterIuivEXT)
 #define glGetTextureParameterfvEXT GLEW_GET_FUN(__glewGetTextureParameterfvEXT)
 #define glGetTextureParameterivEXT GLEW_GET_FUN(__glewGetTextureParameterivEXT)
+#define glGetVertexArrayIntegeri_vEXT GLEW_GET_FUN(__glewGetVertexArrayIntegeri_vEXT)
+#define glGetVertexArrayIntegervEXT GLEW_GET_FUN(__glewGetVertexArrayIntegervEXT)
+#define glGetVertexArrayPointeri_vEXT GLEW_GET_FUN(__glewGetVertexArrayPointeri_vEXT)
+#define glGetVertexArrayPointervEXT GLEW_GET_FUN(__glewGetVertexArrayPointervEXT)
 #define glMapNamedBufferEXT GLEW_GET_FUN(__glewMapNamedBufferEXT)
+#define glMapNamedBufferRangeEXT GLEW_GET_FUN(__glewMapNamedBufferRangeEXT)
 #define glMatrixFrustumEXT GLEW_GET_FUN(__glewMatrixFrustumEXT)
 #define glMatrixLoadIdentityEXT GLEW_GET_FUN(__glewMatrixLoadIdentityEXT)
 #define glMatrixLoadTransposedEXT GLEW_GET_FUN(__glewMatrixLoadTransposedEXT)
@@ -5344,6 +6571,7 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glMultiTexSubImage3DEXT GLEW_GET_FUN(__glewMultiTexSubImage3DEXT)
 #define glNamedBufferDataEXT GLEW_GET_FUN(__glewNamedBufferDataEXT)
 #define glNamedBufferSubDataEXT GLEW_GET_FUN(__glewNamedBufferSubDataEXT)
+#define glNamedCopyBufferSubDataEXT GLEW_GET_FUN(__glewNamedCopyBufferSubDataEXT)
 #define glNamedFramebufferRenderbufferEXT GLEW_GET_FUN(__glewNamedFramebufferRenderbufferEXT)
 #define glNamedFramebufferTexture1DEXT GLEW_GET_FUN(__glewNamedFramebufferTexture1DEXT)
 #define glNamedFramebufferTexture2DEXT GLEW_GET_FUN(__glewNamedFramebufferTexture2DEXT)
@@ -5415,6 +6643,17 @@ typedef GLboolean (GLAPIENTRY * PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
 #define glTextureSubImage2DEXT GLEW_GET_FUN(__glewTextureSubImage2DEXT)
 #define glTextureSubImage3DEXT GLEW_GET_FUN(__glewTextureSubImage3DEXT)
 #define glUnmapNamedBufferEXT GLEW_GET_FUN(__glewUnmapNamedBufferEXT)
+#define glVertexArrayColorOffsetEXT GLEW_GET_FUN(__glewVertexArrayColorOffsetEXT)
+#define glVertexArrayEdgeFlagOffsetEXT GLEW_GET_FUN(__glewVertexArrayEdgeFlagOffsetEXT)
+#define glVertexArrayFogCoordOffsetEXT GLEW_GET_FUN(__glewVertexArrayFogCoordOffsetEXT)
+#define glVertexArrayIndexOffsetEXT GLEW_GET_FUN(__glewVertexArrayIndexOffsetEXT)
+#define glVertexArrayMultiTexCoordOffsetEXT GLEW_GET_FUN(__glewVertexArrayMultiTexCoordOffsetEXT)
+#define glVertexArrayNormalOffsetEXT GLEW_GET_FUN(__glewVertexArrayNormalOffsetEXT)
+#define glVertexArraySecondaryColorOffsetEXT GLEW_GET_FUN(__glewVertexArraySecondaryColorOffsetEXT)
+#define glVertexArrayTexCoordOffsetEXT GLEW_GET_FUN(__glewVertexArrayTexCoordOffsetEXT)
+#define glVertexArrayVertexAttribIOffsetEXT GLEW_GET_FUN(__glewVertexArrayVertexAttribIOffsetEXT)
+#define glVertexArrayVertexAttribOffsetEXT GLEW_GET_FUN(__glewVertexArrayVertexAttribOffsetEXT)
+#define glVertexArrayVertexOffsetEXT GLEW_GET_FUN(__glewVertexArrayVertexOffsetEXT)
 
 #define GLEW_EXT_direct_state_access GLEW_GET_VAR(__GLEW_EXT_direct_state_access)
 
@@ -6223,6 +7462,24 @@ typedef void (GLAPIENTRY * PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat b
 
 #endif /* GL_EXT_polygon_offset */
 
+/* ------------------------ GL_EXT_provoking_vertex ------------------------ */
+
+#ifndef GL_EXT_provoking_vertex
+#define GL_EXT_provoking_vertex 1
+
+#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C
+#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D
+#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E
+#define GL_PROVOKING_VERTEX_EXT 0x8E4F
+
+typedef void (GLAPIENTRY * PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode);
+
+#define glProvokingVertexEXT GLEW_GET_FUN(__glewProvokingVertexEXT)
+
+#define GLEW_EXT_provoking_vertex GLEW_GET_VAR(__GLEW_EXT_provoking_vertex)
+
+#endif /* GL_EXT_provoking_vertex */
+
 /* ------------------------- GL_EXT_rescale_normal ------------------------- */
 
 #ifndef GL_EXT_rescale_normal
@@ -6302,6 +7559,25 @@ typedef void (GLAPIENTRY * PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenu
 
 #endif /* GL_EXT_secondary_color */
 
+/* --------------------- GL_EXT_separate_shader_objects -------------------- */
+
+#ifndef GL_EXT_separate_shader_objects
+#define GL_EXT_separate_shader_objects 1
+
+#define GL_ACTIVE_PROGRAM_EXT 0x8B8D
+
+typedef void (GLAPIENTRY * PFNGLACTIVEPROGRAMEXTPROC) (GLuint program);
+typedef GLuint (GLAPIENTRY * PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const char* string);
+typedef void (GLAPIENTRY * PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program);
+
+#define glActiveProgramEXT GLEW_GET_FUN(__glewActiveProgramEXT)
+#define glCreateShaderProgramEXT GLEW_GET_FUN(__glewCreateShaderProgramEXT)
+#define glUseShaderProgramEXT GLEW_GET_FUN(__glewUseShaderProgramEXT)
+
+#define GLEW_EXT_separate_shader_objects GLEW_GET_VAR(__GLEW_EXT_separate_shader_objects)
+
+#endif /* GL_EXT_separate_shader_objects */
+
 /* --------------------- GL_EXT_separate_specular_color -------------------- */
 
 #ifndef GL_EXT_separate_specular_color
@@ -6315,6 +7591,77 @@ typedef void (GLAPIENTRY * PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenu
 
 #endif /* GL_EXT_separate_specular_color */
 
+/* --------------------- GL_EXT_shader_image_load_store -------------------- */
+
+#ifndef GL_EXT_shader_image_load_store
+#define GL_EXT_shader_image_load_store 1
+
+#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001
+#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT 0x00000002
+#define GL_UNIFORM_BARRIER_BIT_EXT 0x00000004
+#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT 0x00000008
+#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020
+#define GL_COMMAND_BARRIER_BIT_EXT 0x00000040
+#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT 0x00000080
+#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100
+#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT 0x00000200
+#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_MAX_IMAGE_UNITS_EXT 0x8F38
+#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39
+#define GL_IMAGE_BINDING_NAME_EXT 0x8F3A
+#define GL_IMAGE_BINDING_LEVEL_EXT 0x8F3B
+#define GL_IMAGE_BINDING_LAYERED_EXT 0x8F3C
+#define GL_IMAGE_BINDING_LAYER_EXT 0x8F3D
+#define GL_IMAGE_BINDING_ACCESS_EXT 0x8F3E
+#define GL_IMAGE_1D_EXT 0x904C
+#define GL_IMAGE_2D_EXT 0x904D
+#define GL_IMAGE_3D_EXT 0x904E
+#define GL_IMAGE_2D_RECT_EXT 0x904F
+#define GL_IMAGE_CUBE_EXT 0x9050
+#define GL_IMAGE_BUFFER_EXT 0x9051
+#define GL_IMAGE_1D_ARRAY_EXT 0x9052
+#define GL_IMAGE_2D_ARRAY_EXT 0x9053
+#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054
+#define GL_IMAGE_2D_MULTISAMPLE_EXT 0x9055
+#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056
+#define GL_INT_IMAGE_1D_EXT 0x9057
+#define GL_INT_IMAGE_2D_EXT 0x9058
+#define GL_INT_IMAGE_3D_EXT 0x9059
+#define GL_INT_IMAGE_2D_RECT_EXT 0x905A
+#define GL_INT_IMAGE_CUBE_EXT 0x905B
+#define GL_INT_IMAGE_BUFFER_EXT 0x905C
+#define GL_INT_IMAGE_1D_ARRAY_EXT 0x905D
+#define GL_INT_IMAGE_2D_ARRAY_EXT 0x905E
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F
+#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT 0x9060
+#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061
+#define GL_UNSIGNED_INT_IMAGE_1D_EXT 0x9062
+#define GL_UNSIGNED_INT_IMAGE_2D_EXT 0x9063
+#define GL_UNSIGNED_INT_IMAGE_3D_EXT 0x9064
+#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065
+#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT 0x9066
+#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067
+#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068
+#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C
+#define GL_MAX_IMAGE_SAMPLES_EXT 0x906D
+#define GL_IMAGE_BINDING_FORMAT_EXT 0x906E
+#define GL_ALL_BARRIER_BITS_EXT 0xFFFFFFFF
+
+typedef void (GLAPIENTRY * PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format);
+typedef void (GLAPIENTRY * PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers);
+
+#define glBindImageTextureEXT GLEW_GET_FUN(__glewBindImageTextureEXT)
+#define glMemoryBarrierEXT GLEW_GET_FUN(__glewMemoryBarrierEXT)
+
+#define GLEW_EXT_shader_image_load_store GLEW_GET_VAR(__GLEW_EXT_shader_image_load_store)
+
+#endif /* GL_EXT_shader_image_load_store */
+
 /* -------------------------- GL_EXT_shadow_funcs -------------------------- */
 
 #ifndef GL_EXT_shadow_funcs
@@ -6871,6 +8218,41 @@ typedef void (GLAPIENTRY * PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
 
 #endif /* GL_EXT_texture_shared_exponent */
 
+/* -------------------------- GL_EXT_texture_snorm ------------------------- */
+
+#ifndef GL_EXT_texture_snorm
+#define GL_EXT_texture_snorm 1
+
+#define GL_RED_SNORM 0x8F90
+#define GL_RG_SNORM 0x8F91
+#define GL_RGB_SNORM 0x8F92
+#define GL_RGBA_SNORM 0x8F93
+#define GL_R8_SNORM 0x8F94
+#define GL_RG8_SNORM 0x8F95
+#define GL_RGB8_SNORM 0x8F96
+#define GL_RGBA8_SNORM 0x8F97
+#define GL_R16_SNORM 0x8F98
+#define GL_RG16_SNORM 0x8F99
+#define GL_RGB16_SNORM 0x8F9A
+#define GL_RGBA16_SNORM 0x8F9B
+#define GL_SIGNED_NORMALIZED 0x8F9C
+#define GL_ALPHA_SNORM 0x9010
+#define GL_LUMINANCE_SNORM 0x9011
+#define GL_LUMINANCE_ALPHA_SNORM 0x9012
+#define GL_INTENSITY_SNORM 0x9013
+#define GL_ALPHA8_SNORM 0x9014
+#define GL_LUMINANCE8_SNORM 0x9015
+#define GL_LUMINANCE8_ALPHA8_SNORM 0x9016
+#define GL_INTENSITY8_SNORM 0x9017
+#define GL_ALPHA16_SNORM 0x9018
+#define GL_LUMINANCE16_SNORM 0x9019
+#define GL_LUMINANCE16_ALPHA16_SNORM 0x901A
+#define GL_INTENSITY16_SNORM 0x901B
+
+#define GLEW_EXT_texture_snorm GLEW_GET_VAR(__GLEW_EXT_texture_snorm)
+
+#endif /* GL_EXT_texture_snorm */
+
 /* ------------------------- GL_EXT_texture_swizzle ------------------------ */
 
 #ifndef GL_EXT_texture_swizzle
@@ -7018,6 +8400,46 @@ typedef void (GLAPIENTRY * PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type,
 
 #endif /* GL_EXT_vertex_array_bgra */
 
+/* ----------------------- GL_EXT_vertex_attrib_64bit ---------------------- */
+
+#ifndef GL_EXT_vertex_attrib_64bit
+#define GL_EXT_vertex_attrib_64bit 1
+
+#define GL_DOUBLE_MAT2_EXT 0x8F46
+#define GL_DOUBLE_MAT3_EXT 0x8F47
+#define GL_DOUBLE_MAT4_EXT 0x8F48
+#define GL_DOUBLE_VEC2_EXT 0x8FFC
+#define GL_DOUBLE_VEC3_EXT 0x8FFD
+#define GL_DOUBLE_VEC4_EXT 0x8FFE
+
+typedef void (GLAPIENTRY * PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble* params);
+typedef void (GLAPIENTRY * PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void* pointer);
+
+#define glGetVertexAttribLdvEXT GLEW_GET_FUN(__glewGetVertexAttribLdvEXT)
+#define glVertexArrayVertexAttribLOffsetEXT GLEW_GET_FUN(__glewVertexArrayVertexAttribLOffsetEXT)
+#define glVertexAttribL1dEXT GLEW_GET_FUN(__glewVertexAttribL1dEXT)
+#define glVertexAttribL1dvEXT GLEW_GET_FUN(__glewVertexAttribL1dvEXT)
+#define glVertexAttribL2dEXT GLEW_GET_FUN(__glewVertexAttribL2dEXT)
+#define glVertexAttribL2dvEXT GLEW_GET_FUN(__glewVertexAttribL2dvEXT)
+#define glVertexAttribL3dEXT GLEW_GET_FUN(__glewVertexAttribL3dEXT)
+#define glVertexAttribL3dvEXT GLEW_GET_FUN(__glewVertexAttribL3dvEXT)
+#define glVertexAttribL4dEXT GLEW_GET_FUN(__glewVertexAttribL4dEXT)
+#define glVertexAttribL4dvEXT GLEW_GET_FUN(__glewVertexAttribL4dvEXT)
+#define glVertexAttribLPointerEXT GLEW_GET_FUN(__glewVertexAttribLPointerEXT)
+
+#define GLEW_EXT_vertex_attrib_64bit GLEW_GET_VAR(__GLEW_EXT_vertex_attrib_64bit)
+
+#endif /* GL_EXT_vertex_attrib_64bit */
+
 /* -------------------------- GL_EXT_vertex_shader ------------------------- */
 
 #ifndef GL_EXT_vertex_shader
@@ -7686,6 +9108,19 @@ typedef void (GLAPIENTRY * PFNGLENDCONDITIONALRENDERNVPROC) (void);
 
 #endif /* GL_NV_copy_depth_to_color */
 
+/* ---------------------------- GL_NV_copy_image --------------------------- */
+
+#ifndef GL_NV_copy_image
+#define GL_NV_copy_image 1
+
+typedef void (GLAPIENTRY * PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+
+#define glCopyImageSubDataNV GLEW_GET_FUN(__glewCopyImageSubDataNV)
+
+#define GLEW_NV_copy_image GLEW_GET_VAR(__GLEW_NV_copy_image)
+
+#endif /* GL_NV_copy_image */
+
 /* ------------------------ GL_NV_depth_buffer_float ----------------------- */
 
 #ifndef GL_NV_depth_buffer_float
@@ -8034,6 +9469,137 @@ typedef void (GLAPIENTRY * PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum targe
 
 #endif /* GL_NV_gpu_program4 */
 
+/* --------------------------- GL_NV_gpu_program5 -------------------------- */
+
+#ifndef GL_NV_gpu_program5
+#define GL_NV_gpu_program5 1
+
+#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A
+#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 GLEW_NV_gpu_program5 GLEW_GET_VAR(__GLEW_NV_gpu_program5)
+
+#endif /* GL_NV_gpu_program5 */
+
+/* ------------------------- GL_NV_gpu_program_fp64 ------------------------ */
+
+#ifndef GL_NV_gpu_program_fp64
+#define GL_NV_gpu_program_fp64 1
+
+#define GLEW_NV_gpu_program_fp64 GLEW_GET_VAR(__GLEW_NV_gpu_program_fp64)
+
+#endif /* GL_NV_gpu_program_fp64 */
+
+/* --------------------------- GL_NV_gpu_shader5 --------------------------- */
+
+#ifndef GL_NV_gpu_shader5
+#define GL_NV_gpu_shader5 1
+
+#define GL_INT64_NV 0x140E
+#define GL_UNSIGNED_INT64_NV 0x140F
+#define GL_INT8_NV 0x8FE0
+#define GL_INT8_VEC2_NV 0x8FE1
+#define GL_INT8_VEC3_NV 0x8FE2
+#define GL_INT8_VEC4_NV 0x8FE3
+#define GL_INT16_NV 0x8FE4
+#define GL_INT16_VEC2_NV 0x8FE5
+#define GL_INT16_VEC3_NV 0x8FE6
+#define GL_INT16_VEC4_NV 0x8FE7
+#define GL_INT64_VEC2_NV 0x8FE9
+#define GL_INT64_VEC3_NV 0x8FEA
+#define GL_INT64_VEC4_NV 0x8FEB
+#define GL_UNSIGNED_INT8_NV 0x8FEC
+#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED
+#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE
+#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF
+#define GL_UNSIGNED_INT16_NV 0x8FF0
+#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1
+#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2
+#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3
+#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5
+#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6
+#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7
+#define GL_FLOAT16_NV 0x8FF8
+#define GL_FLOAT16_VEC2_NV 0x8FF9
+#define GL_FLOAT16_VEC3_NV 0x8FFA
+#define GL_FLOAT16_VEC4_NV 0x8FFB
+
+typedef void (GLAPIENTRY * PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT* params);
+typedef void (GLAPIENTRY * PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT* params);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x);
+typedef void (GLAPIENTRY * PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x);
+typedef void (GLAPIENTRY * PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (GLAPIENTRY * PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (GLAPIENTRY * PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (GLAPIENTRY * PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (GLAPIENTRY * PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (GLAPIENTRY * PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (GLAPIENTRY * PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT* value);
+
+#define glGetUniformi64vNV GLEW_GET_FUN(__glewGetUniformi64vNV)
+#define glGetUniformui64vNV GLEW_GET_FUN(__glewGetUniformui64vNV)
+#define glProgramUniform1i64NV GLEW_GET_FUN(__glewProgramUniform1i64NV)
+#define glProgramUniform1i64vNV GLEW_GET_FUN(__glewProgramUniform1i64vNV)
+#define glProgramUniform1ui64NV GLEW_GET_FUN(__glewProgramUniform1ui64NV)
+#define glProgramUniform1ui64vNV GLEW_GET_FUN(__glewProgramUniform1ui64vNV)
+#define glProgramUniform2i64NV GLEW_GET_FUN(__glewProgramUniform2i64NV)
+#define glProgramUniform2i64vNV GLEW_GET_FUN(__glewProgramUniform2i64vNV)
+#define glProgramUniform2ui64NV GLEW_GET_FUN(__glewProgramUniform2ui64NV)
+#define glProgramUniform2ui64vNV GLEW_GET_FUN(__glewProgramUniform2ui64vNV)
+#define glProgramUniform3i64NV GLEW_GET_FUN(__glewProgramUniform3i64NV)
+#define glProgramUniform3i64vNV GLEW_GET_FUN(__glewProgramUniform3i64vNV)
+#define glProgramUniform3ui64NV GLEW_GET_FUN(__glewProgramUniform3ui64NV)
+#define glProgramUniform3ui64vNV GLEW_GET_FUN(__glewProgramUniform3ui64vNV)
+#define glProgramUniform4i64NV GLEW_GET_FUN(__glewProgramUniform4i64NV)
+#define glProgramUniform4i64vNV GLEW_GET_FUN(__glewProgramUniform4i64vNV)
+#define glProgramUniform4ui64NV GLEW_GET_FUN(__glewProgramUniform4ui64NV)
+#define glProgramUniform4ui64vNV GLEW_GET_FUN(__glewProgramUniform4ui64vNV)
+#define glUniform1i64NV GLEW_GET_FUN(__glewUniform1i64NV)
+#define glUniform1i64vNV GLEW_GET_FUN(__glewUniform1i64vNV)
+#define glUniform1ui64NV GLEW_GET_FUN(__glewUniform1ui64NV)
+#define glUniform1ui64vNV GLEW_GET_FUN(__glewUniform1ui64vNV)
+#define glUniform2i64NV GLEW_GET_FUN(__glewUniform2i64NV)
+#define glUniform2i64vNV GLEW_GET_FUN(__glewUniform2i64vNV)
+#define glUniform2ui64NV GLEW_GET_FUN(__glewUniform2ui64NV)
+#define glUniform2ui64vNV GLEW_GET_FUN(__glewUniform2ui64vNV)
+#define glUniform3i64NV GLEW_GET_FUN(__glewUniform3i64NV)
+#define glUniform3i64vNV GLEW_GET_FUN(__glewUniform3i64vNV)
+#define glUniform3ui64NV GLEW_GET_FUN(__glewUniform3ui64NV)
+#define glUniform3ui64vNV GLEW_GET_FUN(__glewUniform3ui64vNV)
+#define glUniform4i64NV GLEW_GET_FUN(__glewUniform4i64NV)
+#define glUniform4i64vNV GLEW_GET_FUN(__glewUniform4i64vNV)
+#define glUniform4ui64NV GLEW_GET_FUN(__glewUniform4ui64NV)
+#define glUniform4ui64vNV GLEW_GET_FUN(__glewUniform4ui64vNV)
+
+#define GLEW_NV_gpu_shader5 GLEW_GET_VAR(__GLEW_NV_gpu_shader5)
+
+#endif /* GL_NV_gpu_shader5 */
+
 /* ---------------------------- GL_NV_half_float --------------------------- */
 
 #ifndef GL_NV_half_float
@@ -8229,6 +9795,15 @@ typedef void (GLAPIENTRY * PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target,
 
 #endif /* GL_NV_parameter_buffer_object */
 
+/* --------------------- GL_NV_parameter_buffer_object2 -------------------- */
+
+#ifndef GL_NV_parameter_buffer_object2
+#define GL_NV_parameter_buffer_object2 1
+
+#define GLEW_NV_parameter_buffer_object2 GLEW_GET_VAR(__GLEW_NV_parameter_buffer_object2)
+
+#endif /* GL_NV_parameter_buffer_object2 */
+
 /* ------------------------- GL_NV_pixel_data_range ------------------------ */
 
 #ifndef GL_NV_pixel_data_range
@@ -8288,7 +9863,6 @@ typedef void (GLAPIENTRY * PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum
 typedef void (GLAPIENTRY * PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint* params);
 typedef void (GLAPIENTRY * PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3);
 typedef void (GLAPIENTRY * PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1);
-typedef void (GLAPIENTRY * PFNGLVIDEOPARAMETERIVNVPROC) (GLuint video_slot, GLenum pname, const GLint* params);
 
 #define glGetVideoi64vNV GLEW_GET_FUN(__glewGetVideoi64vNV)
 #define glGetVideoivNV GLEW_GET_FUN(__glewGetVideoivNV)
@@ -8296,7 +9870,6 @@ typedef void (GLAPIENTRY * PFNGLVIDEOPARAMETERIVNVPROC) (GLuint video_slot, GLen
 #define glGetVideouivNV GLEW_GET_FUN(__glewGetVideouivNV)
 #define glPresentFrameDualFillNV GLEW_GET_FUN(__glewPresentFrameDualFillNV)
 #define glPresentFrameKeyedNV GLEW_GET_FUN(__glewPresentFrameKeyedNV)
-#define glVideoParameterivNV GLEW_GET_FUN(__glewVideoParameterivNV)
 
 #define GLEW_NV_present_video GLEW_GET_VAR(__GLEW_NV_present_video)
 
@@ -8426,6 +9999,62 @@ typedef void (GLAPIENTRY * PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage
 
 #endif /* GL_NV_register_combiners2 */
 
+/* ------------------------ GL_NV_shader_buffer_load ----------------------- */
+
+#ifndef GL_NV_shader_buffer_load
+#define GL_NV_shader_buffer_load 1
+
+#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D
+#define GL_GPU_ADDRESS_NV 0x8F34
+#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35
+
+typedef void (GLAPIENTRY * PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT* params);
+typedef void (GLAPIENTRY * PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT* result);
+typedef void (GLAPIENTRY * PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT* params);
+typedef GLboolean (GLAPIENTRY * PFNGLISBUFFERRESIDENTNVPROC) (GLenum target);
+typedef GLboolean (GLAPIENTRY * PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer);
+typedef void (GLAPIENTRY * PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target);
+typedef void (GLAPIENTRY * PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access);
+typedef void (GLAPIENTRY * PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer);
+typedef void (GLAPIENTRY * PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value);
+typedef void (GLAPIENTRY * PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT* value);
+typedef void (GLAPIENTRY * PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value);
+typedef void (GLAPIENTRY * PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT* value);
+
+#define glGetBufferParameterui64vNV GLEW_GET_FUN(__glewGetBufferParameterui64vNV)
+#define glGetIntegerui64vNV GLEW_GET_FUN(__glewGetIntegerui64vNV)
+#define glGetNamedBufferParameterui64vNV GLEW_GET_FUN(__glewGetNamedBufferParameterui64vNV)
+#define glIsBufferResidentNV GLEW_GET_FUN(__glewIsBufferResidentNV)
+#define glIsNamedBufferResidentNV GLEW_GET_FUN(__glewIsNamedBufferResidentNV)
+#define glMakeBufferNonResidentNV GLEW_GET_FUN(__glewMakeBufferNonResidentNV)
+#define glMakeBufferResidentNV GLEW_GET_FUN(__glewMakeBufferResidentNV)
+#define glMakeNamedBufferNonResidentNV GLEW_GET_FUN(__glewMakeNamedBufferNonResidentNV)
+#define glMakeNamedBufferResidentNV GLEW_GET_FUN(__glewMakeNamedBufferResidentNV)
+#define glProgramUniformui64NV GLEW_GET_FUN(__glewProgramUniformui64NV)
+#define glProgramUniformui64vNV GLEW_GET_FUN(__glewProgramUniformui64vNV)
+#define glUniformui64NV GLEW_GET_FUN(__glewUniformui64NV)
+#define glUniformui64vNV GLEW_GET_FUN(__glewUniformui64vNV)
+
+#define GLEW_NV_shader_buffer_load GLEW_GET_VAR(__GLEW_NV_shader_buffer_load)
+
+#endif /* GL_NV_shader_buffer_load */
+
+/* ---------------------- GL_NV_tessellation_program5 ---------------------- */
+
+#ifndef GL_NV_tessellation_program5
+#define GL_NV_tessellation_program5 1
+
+#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV 0x86D8
+#define GL_TESS_CONTROL_PROGRAM_NV 0x891E
+#define GL_TESS_EVALUATION_PROGRAM_NV 0x891F
+#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74
+#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75
+
+#define GLEW_NV_tessellation_program5 GLEW_GET_VAR(__GLEW_NV_tessellation_program5)
+
+#endif /* GL_NV_tessellation_program5 */
+
 /* -------------------------- GL_NV_texgen_emboss -------------------------- */
 
 #ifndef GL_NV_texgen_emboss
@@ -8451,6 +10080,19 @@ typedef void (GLAPIENTRY * PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage
 
 #endif /* GL_NV_texgen_reflection */
 
+/* ------------------------- GL_NV_texture_barrier ------------------------- */
+
+#ifndef GL_NV_texture_barrier
+#define GL_NV_texture_barrier 1
+
+typedef void (GLAPIENTRY * PFNGLTEXTUREBARRIERNVPROC) (void);
+
+#define glTextureBarrierNV GLEW_GET_FUN(__glewTextureBarrierNV)
+
+#define GLEW_NV_texture_barrier GLEW_GET_VAR(__GLEW_NV_texture_barrier)
+
+#endif /* GL_NV_texture_barrier */
+
 /* --------------------- GL_NV_texture_compression_vtc --------------------- */
 
 #ifndef GL_NV_texture_compression_vtc
@@ -8707,6 +10349,36 @@ typedef void (GLAPIENTRY * PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program
 
 #endif /* GL_NV_transform_feedback */
 
+/* ----------------------- GL_NV_transform_feedback2 ----------------------- */
+
+#ifndef GL_NV_transform_feedback2
+#define GL_NV_transform_feedback2 1
+
+#define GL_TRANSFORM_FEEDBACK_NV 0x8E22
+#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23
+#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24
+#define GL_TRANSFORM_FEEDBACK_BINDING_NV 0x8E25
+
+typedef void (GLAPIENTRY * PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id);
+typedef void (GLAPIENTRY * PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint* ids);
+typedef void (GLAPIENTRY * PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id);
+typedef void (GLAPIENTRY * PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint* ids);
+typedef GLboolean (GLAPIENTRY * PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id);
+typedef void (GLAPIENTRY * PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void);
+typedef void (GLAPIENTRY * PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void);
+
+#define glBindTransformFeedbackNV GLEW_GET_FUN(__glewBindTransformFeedbackNV)
+#define glDeleteTransformFeedbacksNV GLEW_GET_FUN(__glewDeleteTransformFeedbacksNV)
+#define glDrawTransformFeedbackNV GLEW_GET_FUN(__glewDrawTransformFeedbackNV)
+#define glGenTransformFeedbacksNV GLEW_GET_FUN(__glewGenTransformFeedbacksNV)
+#define glIsTransformFeedbackNV GLEW_GET_FUN(__glewIsTransformFeedbackNV)
+#define glPauseTransformFeedbackNV GLEW_GET_FUN(__glewPauseTransformFeedbackNV)
+#define glResumeTransformFeedbackNV GLEW_GET_FUN(__glewResumeTransformFeedbackNV)
+
+#define GLEW_NV_transform_feedback2 GLEW_GET_VAR(__GLEW_NV_transform_feedback2)
+
+#endif /* GL_NV_transform_feedback2 */
+
 /* ------------------------ GL_NV_vertex_array_range ----------------------- */
 
 #ifndef GL_NV_vertex_array_range
@@ -8739,6 +10411,116 @@ typedef void (GLAPIENTRY * PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, void* p
 
 #endif /* GL_NV_vertex_array_range2 */
 
+/* ------------------- GL_NV_vertex_attrib_integer_64bit ------------------- */
+
+#ifndef GL_NV_vertex_attrib_integer_64bit
+#define GL_NV_vertex_attrib_integer_64bit 1
+
+#define GL_INT64_NV 0x140E
+#define GL_UNSIGNED_INT64_NV 0x140F
+
+typedef void (GLAPIENTRY * PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT* params);
+typedef void (GLAPIENTRY * PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT* params);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT* v);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);
+
+#define glGetVertexAttribLi64vNV GLEW_GET_FUN(__glewGetVertexAttribLi64vNV)
+#define glGetVertexAttribLui64vNV GLEW_GET_FUN(__glewGetVertexAttribLui64vNV)
+#define glVertexAttribL1i64NV GLEW_GET_FUN(__glewVertexAttribL1i64NV)
+#define glVertexAttribL1i64vNV GLEW_GET_FUN(__glewVertexAttribL1i64vNV)
+#define glVertexAttribL1ui64NV GLEW_GET_FUN(__glewVertexAttribL1ui64NV)
+#define glVertexAttribL1ui64vNV GLEW_GET_FUN(__glewVertexAttribL1ui64vNV)
+#define glVertexAttribL2i64NV GLEW_GET_FUN(__glewVertexAttribL2i64NV)
+#define glVertexAttribL2i64vNV GLEW_GET_FUN(__glewVertexAttribL2i64vNV)
+#define glVertexAttribL2ui64NV GLEW_GET_FUN(__glewVertexAttribL2ui64NV)
+#define glVertexAttribL2ui64vNV GLEW_GET_FUN(__glewVertexAttribL2ui64vNV)
+#define glVertexAttribL3i64NV GLEW_GET_FUN(__glewVertexAttribL3i64NV)
+#define glVertexAttribL3i64vNV GLEW_GET_FUN(__glewVertexAttribL3i64vNV)
+#define glVertexAttribL3ui64NV GLEW_GET_FUN(__glewVertexAttribL3ui64NV)
+#define glVertexAttribL3ui64vNV GLEW_GET_FUN(__glewVertexAttribL3ui64vNV)
+#define glVertexAttribL4i64NV GLEW_GET_FUN(__glewVertexAttribL4i64NV)
+#define glVertexAttribL4i64vNV GLEW_GET_FUN(__glewVertexAttribL4i64vNV)
+#define glVertexAttribL4ui64NV GLEW_GET_FUN(__glewVertexAttribL4ui64NV)
+#define glVertexAttribL4ui64vNV GLEW_GET_FUN(__glewVertexAttribL4ui64vNV)
+#define glVertexAttribLFormatNV GLEW_GET_FUN(__glewVertexAttribLFormatNV)
+
+#define GLEW_NV_vertex_attrib_integer_64bit GLEW_GET_VAR(__GLEW_NV_vertex_attrib_integer_64bit)
+
+#endif /* GL_NV_vertex_attrib_integer_64bit */
+
+/* ------------------- GL_NV_vertex_buffer_unified_memory ------------------ */
+
+#ifndef GL_NV_vertex_buffer_unified_memory
+#define GL_NV_vertex_buffer_unified_memory 1
+
+#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E
+#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F
+#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20
+#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21
+#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22
+#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23
+#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24
+#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25
+#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26
+#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27
+#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28
+#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29
+#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A
+#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B
+#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C
+#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D
+#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E
+#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F
+#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30
+#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31
+#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32
+#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33
+
+typedef void (GLAPIENTRY * PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);
+typedef void (GLAPIENTRY * PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT result[]);
+typedef void (GLAPIENTRY * PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);
+typedef void (GLAPIENTRY * PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+
+#define glBufferAddressRangeNV GLEW_GET_FUN(__glewBufferAddressRangeNV)
+#define glColorFormatNV GLEW_GET_FUN(__glewColorFormatNV)
+#define glEdgeFlagFormatNV GLEW_GET_FUN(__glewEdgeFlagFormatNV)
+#define glFogCoordFormatNV GLEW_GET_FUN(__glewFogCoordFormatNV)
+#define glGetIntegerui64i_vNV GLEW_GET_FUN(__glewGetIntegerui64i_vNV)
+#define glIndexFormatNV GLEW_GET_FUN(__glewIndexFormatNV)
+#define glNormalFormatNV GLEW_GET_FUN(__glewNormalFormatNV)
+#define glSecondaryColorFormatNV GLEW_GET_FUN(__glewSecondaryColorFormatNV)
+#define glTexCoordFormatNV GLEW_GET_FUN(__glewTexCoordFormatNV)
+#define glVertexAttribFormatNV GLEW_GET_FUN(__glewVertexAttribFormatNV)
+#define glVertexAttribIFormatNV GLEW_GET_FUN(__glewVertexAttribIFormatNV)
+#define glVertexFormatNV GLEW_GET_FUN(__glewVertexFormatNV)
+
+#define GLEW_NV_vertex_buffer_unified_memory GLEW_GET_VAR(__GLEW_NV_vertex_buffer_unified_memory)
+
+#endif /* GL_NV_vertex_buffer_unified_memory */
+
 /* -------------------------- GL_NV_vertex_program ------------------------- */
 
 #ifndef GL_NV_vertex_program
@@ -10460,8 +12242,6 @@ GLEW_FUN_EXPORT PFNGLUNIFORMMATRIX4X3FVPROC __glewUniformMatrix4x3fv;
 
 GLEW_FUN_EXPORT PFNGLBEGINCONDITIONALRENDERPROC __glewBeginConditionalRender;
 GLEW_FUN_EXPORT PFNGLBEGINTRANSFORMFEEDBACKPROC __glewBeginTransformFeedback;
-GLEW_FUN_EXPORT PFNGLBINDBUFFERBASEPROC __glewBindBufferBase;
-GLEW_FUN_EXPORT PFNGLBINDBUFFERRANGEPROC __glewBindBufferRange;
 GLEW_FUN_EXPORT PFNGLBINDFRAGDATALOCATIONPROC __glewBindFragDataLocation;
 GLEW_FUN_EXPORT PFNGLCLAMPCOLORPROC __glewClampColor;
 GLEW_FUN_EXPORT PFNGLCLEARBUFFERFIPROC __glewClearBufferfi;
@@ -10475,7 +12255,6 @@ GLEW_FUN_EXPORT PFNGLENDCONDITIONALRENDERPROC __glewEndConditionalRender;
 GLEW_FUN_EXPORT PFNGLENDTRANSFORMFEEDBACKPROC __glewEndTransformFeedback;
 GLEW_FUN_EXPORT PFNGLGETBOOLEANI_VPROC __glewGetBooleani_v;
 GLEW_FUN_EXPORT PFNGLGETFRAGDATALOCATIONPROC __glewGetFragDataLocation;
-GLEW_FUN_EXPORT PFNGLGETINTEGERI_VPROC __glewGetIntegeri_v;
 GLEW_FUN_EXPORT PFNGLGETSTRINGIPROC __glewGetStringi;
 GLEW_FUN_EXPORT PFNGLGETTEXPARAMETERIIVPROC __glewGetTexParameterIiv;
 GLEW_FUN_EXPORT PFNGLGETTEXPARAMETERIUIVPROC __glewGetTexParameterIuiv;
@@ -10517,8 +12296,43 @@ GLEW_FUN_EXPORT PFNGLVERTEXATTRIBI4UIVPROC __glewVertexAttribI4uiv;
 GLEW_FUN_EXPORT PFNGLVERTEXATTRIBI4USVPROC __glewVertexAttribI4usv;
 GLEW_FUN_EXPORT PFNGLVERTEXATTRIBIPOINTERPROC __glewVertexAttribIPointer;
 
+GLEW_FUN_EXPORT PFNGLDRAWARRAYSINSTANCEDPROC __glewDrawArraysInstanced;
+GLEW_FUN_EXPORT PFNGLDRAWELEMENTSINSTANCEDPROC __glewDrawElementsInstanced;
+GLEW_FUN_EXPORT PFNGLPRIMITIVERESTARTINDEXPROC __glewPrimitiveRestartIndex;
+GLEW_FUN_EXPORT PFNGLTEXBUFFERPROC __glewTexBuffer;
+
+GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTUREPROC __glewFramebufferTexture;
+GLEW_FUN_EXPORT PFNGLGETBUFFERPARAMETERI64VPROC __glewGetBufferParameteri64v;
+GLEW_FUN_EXPORT PFNGLGETINTEGER64I_VPROC __glewGetInteger64i_v;
+
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONSEPARATEIPROC __glewBlendEquationSeparatei;
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONIPROC __glewBlendEquationi;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCSEPARATEIPROC __glewBlendFuncSeparatei;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCIPROC __glewBlendFunci;
+GLEW_FUN_EXPORT PFNGLMINSAMPLESHADINGPROC __glewMinSampleShading;
+
 GLEW_FUN_EXPORT PFNGLTBUFFERMASK3DFXPROC __glewTbufferMask3DFX;
 
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONINDEXEDAMDPROC __glewBlendEquationIndexedAMD;
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC __glewBlendEquationSeparateIndexedAMD;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCINDEXEDAMDPROC __glewBlendFuncIndexedAMD;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC __glewBlendFuncSeparateIndexedAMD;
+
+GLEW_FUN_EXPORT PFNGLBEGINPERFMONITORAMDPROC __glewBeginPerfMonitorAMD;
+GLEW_FUN_EXPORT PFNGLDELETEPERFMONITORSAMDPROC __glewDeletePerfMonitorsAMD;
+GLEW_FUN_EXPORT PFNGLENDPERFMONITORAMDPROC __glewEndPerfMonitorAMD;
+GLEW_FUN_EXPORT PFNGLGENPERFMONITORSAMDPROC __glewGenPerfMonitorsAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORCOUNTERDATAAMDPROC __glewGetPerfMonitorCounterDataAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORCOUNTERINFOAMDPROC __glewGetPerfMonitorCounterInfoAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC __glewGetPerfMonitorCounterStringAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORCOUNTERSAMDPROC __glewGetPerfMonitorCountersAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORGROUPSTRINGAMDPROC __glewGetPerfMonitorGroupStringAMD;
+GLEW_FUN_EXPORT PFNGLGETPERFMONITORGROUPSAMDPROC __glewGetPerfMonitorGroupsAMD;
+GLEW_FUN_EXPORT PFNGLSELECTPERFMONITORCOUNTERSAMDPROC __glewSelectPerfMonitorCountersAMD;
+
+GLEW_FUN_EXPORT PFNGLTESSELLATIONFACTORAMDPROC __glewTessellationFactorAMD;
+GLEW_FUN_EXPORT PFNGLTESSELLATIONMODEAMDPROC __glewTessellationModeAMD;
+
 GLEW_FUN_EXPORT PFNGLDRAWELEMENTARRAYAPPLEPROC __glewDrawElementArrayAPPLE;
 GLEW_FUN_EXPORT PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC __glewDrawRangeElementArrayAPPLE;
 GLEW_FUN_EXPORT PFNGLELEMENTPOINTERAPPLEPROC __glewElementPointerAPPLE;
@@ -10537,6 +12351,10 @@ GLEW_FUN_EXPORT PFNGLTESTOBJECTAPPLEPROC __glewTestObjectAPPLE;
 GLEW_FUN_EXPORT PFNGLBUFFERPARAMETERIAPPLEPROC __glewBufferParameteriAPPLE;
 GLEW_FUN_EXPORT PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC __glewFlushMappedBufferRangeAPPLE;
 
+GLEW_FUN_EXPORT PFNGLGETOBJECTPARAMETERIVAPPLEPROC __glewGetObjectParameterivAPPLE;
+GLEW_FUN_EXPORT PFNGLOBJECTPURGEABLEAPPLEPROC __glewObjectPurgeableAPPLE;
+GLEW_FUN_EXPORT PFNGLOBJECTUNPURGEABLEAPPLEPROC __glewObjectUnpurgeableAPPLE;
+
 GLEW_FUN_EXPORT PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC __glewGetTexParameterPointervAPPLE;
 GLEW_FUN_EXPORT PFNGLTEXTURERANGEAPPLEPROC __glewTextureRangeAPPLE;
 
@@ -10549,10 +12367,36 @@ GLEW_FUN_EXPORT PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC __glewFlushVertexArrayRangeA
 GLEW_FUN_EXPORT PFNGLVERTEXARRAYPARAMETERIAPPLEPROC __glewVertexArrayParameteriAPPLE;
 GLEW_FUN_EXPORT PFNGLVERTEXARRAYRANGEAPPLEPROC __glewVertexArrayRangeAPPLE;
 
+GLEW_FUN_EXPORT PFNGLDISABLEVERTEXATTRIBAPPLEPROC __glewDisableVertexAttribAPPLE;
+GLEW_FUN_EXPORT PFNGLENABLEVERTEXATTRIBAPPLEPROC __glewEnableVertexAttribAPPLE;
+GLEW_FUN_EXPORT PFNGLISVERTEXATTRIBENABLEDAPPLEPROC __glewIsVertexAttribEnabledAPPLE;
+GLEW_FUN_EXPORT PFNGLMAPVERTEXATTRIB1DAPPLEPROC __glewMapVertexAttrib1dAPPLE;
+GLEW_FUN_EXPORT PFNGLMAPVERTEXATTRIB1FAPPLEPROC __glewMapVertexAttrib1fAPPLE;
+GLEW_FUN_EXPORT PFNGLMAPVERTEXATTRIB2DAPPLEPROC __glewMapVertexAttrib2dAPPLE;
+GLEW_FUN_EXPORT PFNGLMAPVERTEXATTRIB2FAPPLEPROC __glewMapVertexAttrib2fAPPLE;
+
+GLEW_FUN_EXPORT PFNGLBINDFRAGDATALOCATIONINDEXEDPROC __glewBindFragDataLocationIndexed;
+GLEW_FUN_EXPORT PFNGLGETFRAGDATAINDEXPROC __glewGetFragDataIndex;
+
 GLEW_FUN_EXPORT PFNGLCLAMPCOLORARBPROC __glewClampColorARB;
 
+GLEW_FUN_EXPORT PFNGLCOPYBUFFERSUBDATAPROC __glewCopyBufferSubData;
+
 GLEW_FUN_EXPORT PFNGLDRAWBUFFERSARBPROC __glewDrawBuffersARB;
 
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONSEPARATEIARBPROC __glewBlendEquationSeparateiARB;
+GLEW_FUN_EXPORT PFNGLBLENDEQUATIONIARBPROC __glewBlendEquationiARB;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCSEPARATEIARBPROC __glewBlendFuncSeparateiARB;
+GLEW_FUN_EXPORT PFNGLBLENDFUNCIARBPROC __glewBlendFunciARB;
+
+GLEW_FUN_EXPORT PFNGLDRAWELEMENTSBASEVERTEXPROC __glewDrawElementsBaseVertex;
+GLEW_FUN_EXPORT PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC __glewDrawElementsInstancedBaseVertex;
+GLEW_FUN_EXPORT PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC __glewDrawRangeElementsBaseVertex;
+GLEW_FUN_EXPORT PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC __glewMultiDrawElementsBaseVertex;
+
+GLEW_FUN_EXPORT PFNGLDRAWARRAYSINDIRECTPROC __glewDrawArraysIndirect;
+GLEW_FUN_EXPORT PFNGLDRAWELEMENTSINDIRECTPROC __glewDrawElementsIndirect;
+
 GLEW_FUN_EXPORT PFNGLDRAWARRAYSINSTANCEDARBPROC __glewDrawArraysInstancedARB;
 GLEW_FUN_EXPORT PFNGLDRAWELEMENTSINSTANCEDARBPROC __glewDrawElementsInstancedARB;
 
@@ -10563,10 +12407,10 @@ GLEW_FUN_EXPORT PFNGLCHECKFRAMEBUFFERSTATUSPROC __glewCheckFramebufferStatus;
 GLEW_FUN_EXPORT PFNGLDELETEFRAMEBUFFERSPROC __glewDeleteFramebuffers;
 GLEW_FUN_EXPORT PFNGLDELETERENDERBUFFERSPROC __glewDeleteRenderbuffers;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERRENDERBUFFERPROC __glewFramebufferRenderbuffer;
-GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTURLAYERPROC __glewFramebufferTexturLayer;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTURE1DPROC __glewFramebufferTexture1D;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTURE2DPROC __glewFramebufferTexture2D;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTURE3DPROC __glewFramebufferTexture3D;
+GLEW_FUN_EXPORT PFNGLFRAMEBUFFERTEXTURELAYERPROC __glewFramebufferTextureLayer;
 GLEW_FUN_EXPORT PFNGLGENFRAMEBUFFERSPROC __glewGenFramebuffers;
 GLEW_FUN_EXPORT PFNGLGENRENDERBUFFERSPROC __glewGenRenderbuffers;
 GLEW_FUN_EXPORT PFNGLGENERATEMIPMAPPROC __glewGenerateMipmap;
@@ -10675,6 +12519,25 @@ GLEW_FUN_EXPORT PFNGLISQUERYARBPROC __glewIsQueryARB;
 GLEW_FUN_EXPORT PFNGLPOINTPARAMETERFARBPROC __glewPointParameterfARB;
 GLEW_FUN_EXPORT PFNGLPOINTPARAMETERFVARBPROC __glewPointParameterfvARB;
 
+GLEW_FUN_EXPORT PFNGLPROVOKINGVERTEXPROC __glewProvokingVertex;
+
+GLEW_FUN_EXPORT PFNGLMINSAMPLESHADINGARBPROC __glewMinSampleShadingARB;
+
+GLEW_FUN_EXPORT PFNGLBINDSAMPLERPROC __glewBindSampler;
+GLEW_FUN_EXPORT PFNGLDELETESAMPLERSPROC __glewDeleteSamplers;
+GLEW_FUN_EXPORT PFNGLGENSAMPLERSPROC __glewGenSamplers;
+GLEW_FUN_EXPORT PFNGLGETSAMPLERPARAMETERIIVPROC __glewGetSamplerParameterIiv;
+GLEW_FUN_EXPORT PFNGLGETSAMPLERPARAMETERIUIVPROC __glewGetSamplerParameterIuiv;
+GLEW_FUN_EXPORT PFNGLGETSAMPLERPARAMETERFVPROC __glewGetSamplerParameterfv;
+GLEW_FUN_EXPORT PFNGLGETSAMPLERPARAMETERIVPROC __glewGetSamplerParameteriv;
+GLEW_FUN_EXPORT PFNGLISSAMPLERPROC __glewIsSampler;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERIIVPROC __glewSamplerParameterIiv;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERIUIVPROC __glewSamplerParameterIuiv;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERFPROC __glewSamplerParameterf;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERFVPROC __glewSamplerParameterfv;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERIPROC __glewSamplerParameteri;
+GLEW_FUN_EXPORT PFNGLSAMPLERPARAMETERIVPROC __glewSamplerParameteriv;
+
 GLEW_FUN_EXPORT PFNGLATTACHOBJECTARBPROC __glewAttachObjectARB;
 GLEW_FUN_EXPORT PFNGLCOMPILESHADERARBPROC __glewCompileShaderARB;
 GLEW_FUN_EXPORT PFNGLCREATEPROGRAMOBJECTARBPROC __glewCreateProgramObjectARB;
@@ -10715,6 +12578,33 @@ GLEW_FUN_EXPORT PFNGLUNIFORMMATRIX4FVARBPROC __glewUniformMatrix4fvARB;
 GLEW_FUN_EXPORT PFNGLUSEPROGRAMOBJECTARBPROC __glewUseProgramObjectARB;
 GLEW_FUN_EXPORT PFNGLVALIDATEPROGRAMARBPROC __glewValidateProgramARB;
 
+GLEW_FUN_EXPORT PFNGLGETACTIVESUBROUTINENAMEPROC __glewGetActiveSubroutineName;
+GLEW_FUN_EXPORT PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC __glewGetActiveSubroutineUniformName;
+GLEW_FUN_EXPORT PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC __glewGetActiveSubroutineUniformiv;
+GLEW_FUN_EXPORT PFNGLGETPROGRAMSTAGEIVPROC __glewGetProgramStageiv;
+GLEW_FUN_EXPORT PFNGLGETSUBROUTINEINDEXPROC __glewGetSubroutineIndex;
+GLEW_FUN_EXPORT PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC __glewGetSubroutineUniformLocation;
+GLEW_FUN_EXPORT PFNGLGETUNIFORMSUBROUTINEUIVPROC __glewGetUniformSubroutineuiv;
+GLEW_FUN_EXPORT PFNGLUNIFORMSUBROUTINESUIVPROC __glewUniformSubroutinesuiv;
+
+GLEW_FUN_EXPORT PFNGLCOMPILESHADERINCLUDEARBPROC __glewCompileShaderIncludeARB;
+GLEW_FUN_EXPORT PFNGLDELETENAMEDSTRINGARBPROC __glewDeleteNamedStringARB;
+GLEW_FUN_EXPORT PFNGLGETNAMEDSTRINGARBPROC __glewGetNamedStringARB;
+GLEW_FUN_EXPORT PFNGLGETNAMEDSTRINGIVARBPROC __glewGetNamedStringivARB;
+GLEW_FUN_EXPORT PFNGLISNAMEDSTRINGARBPROC __glewIsNamedStringARB;
+GLEW_FUN_EXPORT PFNGLNAMEDSTRINGARBPROC __glewNamedStringARB;
+
+GLEW_FUN_EXPORT PFNGLCLIENTWAITSYNCPROC __glewClientWaitSync;
+GLEW_FUN_EXPORT PFNGLDELETESYNCPROC __glewDeleteSync;
+GLEW_FUN_EXPORT PFNGLFENCESYNCPROC __glewFenceSync;
+GLEW_FUN_EXPORT PFNGLGETINTEGER64VPROC __glewGetInteger64v;
+GLEW_FUN_EXPORT PFNGLGETSYNCIVPROC __glewGetSynciv;
+GLEW_FUN_EXPORT PFNGLISSYNCPROC __glewIsSync;
+GLEW_FUN_EXPORT PFNGLWAITSYNCPROC __glewWaitSync;
+
+GLEW_FUN_EXPORT PFNGLPATCHPARAMETERFVPROC __glewPatchParameterfv;
+GLEW_FUN_EXPORT PFNGLPATCHPARAMETERIPROC __glewPatchParameteri;
+
 GLEW_FUN_EXPORT PFNGLTEXBUFFERARBPROC __glewTexBufferARB;
 
 GLEW_FUN_EXPORT PFNGLCOMPRESSEDTEXIMAGE1DARBPROC __glewCompressedTexImage1DARB;
@@ -10725,11 +12615,44 @@ GLEW_FUN_EXPORT PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC __glewCompressedTexSubImage2
 GLEW_FUN_EXPORT PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC __glewCompressedTexSubImage3DARB;
 GLEW_FUN_EXPORT PFNGLGETCOMPRESSEDTEXIMAGEARBPROC __glewGetCompressedTexImageARB;
 
+GLEW_FUN_EXPORT PFNGLGETMULTISAMPLEFVPROC __glewGetMultisamplefv;
+GLEW_FUN_EXPORT PFNGLSAMPLEMASKIPROC __glewSampleMaski;
+GLEW_FUN_EXPORT PFNGLTEXIMAGE2DMULTISAMPLEPROC __glewTexImage2DMultisample;
+GLEW_FUN_EXPORT PFNGLTEXIMAGE3DMULTISAMPLEPROC __glewTexImage3DMultisample;
+
+GLEW_FUN_EXPORT PFNGLGETQUERYOBJECTI64VPROC __glewGetQueryObjecti64v;
+GLEW_FUN_EXPORT PFNGLGETQUERYOBJECTUI64VPROC __glewGetQueryObjectui64v;
+GLEW_FUN_EXPORT PFNGLQUERYCOUNTERPROC __glewQueryCounter;
+
+GLEW_FUN_EXPORT PFNGLBINDTRANSFORMFEEDBACKPROC __glewBindTransformFeedback;
+GLEW_FUN_EXPORT PFNGLDELETETRANSFORMFEEDBACKSPROC __glewDeleteTransformFeedbacks;
+GLEW_FUN_EXPORT PFNGLDRAWTRANSFORMFEEDBACKPROC __glewDrawTransformFeedback;
+GLEW_FUN_EXPORT PFNGLGENTRANSFORMFEEDBACKSPROC __glewGenTransformFeedbacks;
+GLEW_FUN_EXPORT PFNGLISTRANSFORMFEEDBACKPROC __glewIsTransformFeedback;
+GLEW_FUN_EXPORT PFNGLPAUSETRANSFORMFEEDBACKPROC __glewPauseTransformFeedback;
+GLEW_FUN_EXPORT PFNGLRESUMETRANSFORMFEEDBACKPROC __glewResumeTransformFeedback;
+
+GLEW_FUN_EXPORT PFNGLBEGINQUERYINDEXEDPROC __glewBeginQueryIndexed;
+GLEW_FUN_EXPORT PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC __glewDrawTransformFeedbackStream;
+GLEW_FUN_EXPORT PFNGLENDQUERYINDEXEDPROC __glewEndQueryIndexed;
+GLEW_FUN_EXPORT PFNGLGETQUERYINDEXEDIVPROC __glewGetQueryIndexediv;
+
 GLEW_FUN_EXPORT PFNGLLOADTRANSPOSEMATRIXDARBPROC __glewLoadTransposeMatrixdARB;
 GLEW_FUN_EXPORT PFNGLLOADTRANSPOSEMATRIXFARBPROC __glewLoadTransposeMatrixfARB;
 GLEW_FUN_EXPORT PFNGLMULTTRANSPOSEMATRIXDARBPROC __glewMultTransposeMatrixdARB;
 GLEW_FUN_EXPORT PFNGLMULTTRANSPOSEMATRIXFARBPROC __glewMultTransposeMatrixfARB;
 
+GLEW_FUN_EXPORT PFNGLBINDBUFFERBASEPROC __glewBindBufferBase;
+GLEW_FUN_EXPORT PFNGLBINDBUFFERRANGEPROC __glewBindBufferRange;
+GLEW_FUN_EXPORT PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC __glewGetActiveUniformBlockName;
+GLEW_FUN_EXPORT PFNGLGETACTIVEUNIFORMBLOCKIVPROC __glewGetActiveUniformBlockiv;
+GLEW_FUN_EXPORT PFNGLGETACTIVEUNIFORMNAMEPROC __glewGetActiveUniformName;
+GLEW_FUN_EXPORT PFNGLGETACTIVEUNIFORMSIVPROC __glewGetActiveUniformsiv;
+GLEW_FUN_EXPORT PFNGLGETINTEGERI_VPROC __glewGetIntegeri_v;
+GLEW_FUN_EXPORT PFNGLGETUNIFORMBLOCKINDEXPROC __glewGetUniformBlockIndex;
+GLEW_FUN_EXPORT PFNGLGETUNIFORMINDICESPROC __glewGetUniformIndices;
+GLEW_FUN_EXPORT PFNGLUNIFORMBLOCKBINDINGPROC __glewUniformBlockBinding;
+
 GLEW_FUN_EXPORT PFNGLBINDVERTEXARRAYPROC __glewBindVertexArray;
 GLEW_FUN_EXPORT PFNGLDELETEVERTEXARRAYSPROC __glewDeleteVertexArrays;
 GLEW_FUN_EXPORT PFNGLGENVERTEXARRAYSPROC __glewGenVertexArrays;
@@ -10825,6 +12748,45 @@ GLEW_FUN_EXPORT PFNGLBINDATTRIBLOCATIONARBPROC __glewBindAttribLocationARB;
 GLEW_FUN_EXPORT PFNGLGETACTIVEATTRIBARBPROC __glewGetActiveAttribARB;
 GLEW_FUN_EXPORT PFNGLGETATTRIBLOCATIONARBPROC __glewGetAttribLocationARB;
 
+GLEW_FUN_EXPORT PFNGLCOLORP3UIPROC __glewColorP3ui;
+GLEW_FUN_EXPORT PFNGLCOLORP3UIVPROC __glewColorP3uiv;
+GLEW_FUN_EXPORT PFNGLCOLORP4UIPROC __glewColorP4ui;
+GLEW_FUN_EXPORT PFNGLCOLORP4UIVPROC __glewColorP4uiv;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP1UIPROC __glewMultiTexCoordP1ui;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP1UIVPROC __glewMultiTexCoordP1uiv;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP2UIPROC __glewMultiTexCoordP2ui;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP2UIVPROC __glewMultiTexCoordP2uiv;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP3UIPROC __glewMultiTexCoordP3ui;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP3UIVPROC __glewMultiTexCoordP3uiv;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP4UIPROC __glewMultiTexCoordP4ui;
+GLEW_FUN_EXPORT PFNGLMULTITEXCOORDP4UIVPROC __glewMultiTexCoordP4uiv;
+GLEW_FUN_EXPORT PFNGLNORMALP3UIPROC __glewNormalP3ui;
+GLEW_FUN_EXPORT PFNGLNORMALP3UIVPROC __glewNormalP3uiv;
+GLEW_FUN_EXPORT PFNGLSECONDARYCOLORP3UIPROC __glewSecondaryColorP3ui;
+GLEW_FUN_EXPORT PFNGLSECONDARYCOLORP3UIVPROC __glewSecondaryColorP3uiv;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP1UIPROC __glewTexCoordP1ui;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP1UIVPROC __glewTexCoordP1uiv;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP2UIPROC __glewTexCoordP2ui;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP2UIVPROC __glewTexCoordP2uiv;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP3UIPROC __glewTexCoordP3ui;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP3UIVPROC __glewTexCoordP3uiv;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP4UIPROC __glewTexCoordP4ui;
+GLEW_FUN_EXPORT PFNGLTEXCOORDP4UIVPROC __glewTexCoordP4uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP1UIPROC __glewVertexAttribP1ui;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP1UIVPROC __glewVertexAttribP1uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP2UIPROC __glewVertexAttribP2ui;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP2UIVPROC __glewVertexAttribP2uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP3UIPROC __glewVertexAttribP3ui;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP3UIVPROC __glewVertexAttribP3uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP4UIPROC __glewVertexAttribP4ui;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBP4UIVPROC __glewVertexAttribP4uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXP2UIPROC __glewVertexP2ui;
+GLEW_FUN_EXPORT PFNGLVERTEXP2UIVPROC __glewVertexP2uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXP3UIPROC __glewVertexP3ui;
+GLEW_FUN_EXPORT PFNGLVERTEXP3UIVPROC __glewVertexP3uiv;
+GLEW_FUN_EXPORT PFNGLVERTEXP4UIPROC __glewVertexP4ui;
+GLEW_FUN_EXPORT PFNGLVERTEXP4UIVPROC __glewVertexP4uiv;
+
 GLEW_FUN_EXPORT PFNGLWINDOWPOS2DARBPROC __glewWindowPos2dARB;
 GLEW_FUN_EXPORT PFNGLWINDOWPOS2DVARBPROC __glewWindowPos2dvARB;
 GLEW_FUN_EXPORT PFNGLWINDOWPOS2FARBPROC __glewWindowPos2fARB;
@@ -11004,7 +12966,14 @@ GLEW_FUN_EXPORT PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC __glewCopyTextureSubImage1DEXT
 GLEW_FUN_EXPORT PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC __glewCopyTextureSubImage2DEXT;
 GLEW_FUN_EXPORT PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC __glewCopyTextureSubImage3DEXT;
 GLEW_FUN_EXPORT PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC __glewDisableClientStateIndexedEXT;
+GLEW_FUN_EXPORT PFNGLDISABLECLIENTSTATEIEXTPROC __glewDisableClientStateiEXT;
+GLEW_FUN_EXPORT PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC __glewDisableVertexArrayAttribEXT;
+GLEW_FUN_EXPORT PFNGLDISABLEVERTEXARRAYEXTPROC __glewDisableVertexArrayEXT;
 GLEW_FUN_EXPORT PFNGLENABLECLIENTSTATEINDEXEDEXTPROC __glewEnableClientStateIndexedEXT;
+GLEW_FUN_EXPORT PFNGLENABLECLIENTSTATEIEXTPROC __glewEnableClientStateiEXT;
+GLEW_FUN_EXPORT PFNGLENABLEVERTEXARRAYATTRIBEXTPROC __glewEnableVertexArrayAttribEXT;
+GLEW_FUN_EXPORT PFNGLENABLEVERTEXARRAYEXTPROC __glewEnableVertexArrayEXT;
+GLEW_FUN_EXPORT PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC __glewFlushMappedNamedBufferRangeEXT;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC __glewFramebufferDrawBufferEXT;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC __glewFramebufferDrawBuffersEXT;
 GLEW_FUN_EXPORT PFNGLFRAMEBUFFERREADBUFFEREXTPROC __glewFramebufferReadBufferEXT;
@@ -11013,7 +12982,9 @@ GLEW_FUN_EXPORT PFNGLGENERATETEXTUREMIPMAPEXTPROC __glewGenerateTextureMipmapEXT
 GLEW_FUN_EXPORT PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC __glewGetCompressedMultiTexImageEXT;
 GLEW_FUN_EXPORT PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC __glewGetCompressedTextureImageEXT;
 GLEW_FUN_EXPORT PFNGLGETDOUBLEINDEXEDVEXTPROC __glewGetDoubleIndexedvEXT;
+GLEW_FUN_EXPORT PFNGLGETDOUBLEI_VEXTPROC __glewGetDoublei_vEXT;
 GLEW_FUN_EXPORT PFNGLGETFLOATINDEXEDVEXTPROC __glewGetFloatIndexedvEXT;
+GLEW_FUN_EXPORT PFNGLGETFLOATI_VEXTPROC __glewGetFloati_vEXT;
 GLEW_FUN_EXPORT PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC __glewGetFramebufferParameterivEXT;
 GLEW_FUN_EXPORT PFNGLGETMULTITEXENVFVEXTPROC __glewGetMultiTexEnvfvEXT;
 GLEW_FUN_EXPORT PFNGLGETMULTITEXENVIVEXTPROC __glewGetMultiTexEnvivEXT;
@@ -11039,6 +13010,7 @@ GLEW_FUN_EXPORT PFNGLGETNAMEDPROGRAMSTRINGEXTPROC __glewGetNamedProgramStringEXT
 GLEW_FUN_EXPORT PFNGLGETNAMEDPROGRAMIVEXTPROC __glewGetNamedProgramivEXT;
 GLEW_FUN_EXPORT PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC __glewGetNamedRenderbufferParameterivEXT;
 GLEW_FUN_EXPORT PFNGLGETPOINTERINDEXEDVEXTPROC __glewGetPointerIndexedvEXT;
+GLEW_FUN_EXPORT PFNGLGETPOINTERI_VEXTPROC __glewGetPointeri_vEXT;
 GLEW_FUN_EXPORT PFNGLGETTEXTUREIMAGEEXTPROC __glewGetTextureImageEXT;
 GLEW_FUN_EXPORT PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC __glewGetTextureLevelParameterfvEXT;
 GLEW_FUN_EXPORT PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC __glewGetTextureLevelParameterivEXT;
@@ -11046,7 +13018,12 @@ GLEW_FUN_EXPORT PFNGLGETTEXTUREPARAMETERIIVEXTPROC __glewGetTextureParameterIivE
 GLEW_FUN_EXPORT PFNGLGETTEXTUREPARAMETERIUIVEXTPROC __glewGetTextureParameterIuivEXT;
 GLEW_FUN_EXPORT PFNGLGETTEXTUREPARAMETERFVEXTPROC __glewGetTextureParameterfvEXT;
 GLEW_FUN_EXPORT PFNGLGETTEXTUREPARAMETERIVEXTPROC __glewGetTextureParameterivEXT;
+GLEW_FUN_EXPORT PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC __glewGetVertexArrayIntegeri_vEXT;
+GLEW_FUN_EXPORT PFNGLGETVERTEXARRAYINTEGERVEXTPROC __glewGetVertexArrayIntegervEXT;
+GLEW_FUN_EXPORT PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC __glewGetVertexArrayPointeri_vEXT;
+GLEW_FUN_EXPORT PFNGLGETVERTEXARRAYPOINTERVEXTPROC __glewGetVertexArrayPointervEXT;
 GLEW_FUN_EXPORT PFNGLMAPNAMEDBUFFEREXTPROC __glewMapNamedBufferEXT;
+GLEW_FUN_EXPORT PFNGLMAPNAMEDBUFFERRANGEEXTPROC __glewMapNamedBufferRangeEXT;
 GLEW_FUN_EXPORT PFNGLMATRIXFRUSTUMEXTPROC __glewMatrixFrustumEXT;
 GLEW_FUN_EXPORT PFNGLMATRIXLOADIDENTITYEXTPROC __glewMatrixLoadIdentityEXT;
 GLEW_FUN_EXPORT PFNGLMATRIXLOADTRANSPOSEDEXTPROC __glewMatrixLoadTransposedEXT;
@@ -11093,6 +13070,7 @@ GLEW_FUN_EXPORT PFNGLMULTITEXSUBIMAGE2DEXTPROC __glewMultiTexSubImage2DEXT;
 GLEW_FUN_EXPORT PFNGLMULTITEXSUBIMAGE3DEXTPROC __glewMultiTexSubImage3DEXT;
 GLEW_FUN_EXPORT PFNGLNAMEDBUFFERDATAEXTPROC __glewNamedBufferDataEXT;
 GLEW_FUN_EXPORT PFNGLNAMEDBUFFERSUBDATAEXTPROC __glewNamedBufferSubDataEXT;
+GLEW_FUN_EXPORT PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC __glewNamedCopyBufferSubDataEXT;
 GLEW_FUN_EXPORT PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC __glewNamedFramebufferRenderbufferEXT;
 GLEW_FUN_EXPORT PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC __glewNamedFramebufferTexture1DEXT;
 GLEW_FUN_EXPORT PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC __glewNamedFramebufferTexture2DEXT;
@@ -11164,6 +13142,17 @@ GLEW_FUN_EXPORT PFNGLTEXTURESUBIMAGE1DEXTPROC __glewTextureSubImage1DEXT;
 GLEW_FUN_EXPORT PFNGLTEXTURESUBIMAGE2DEXTPROC __glewTextureSubImage2DEXT;
 GLEW_FUN_EXPORT PFNGLTEXTURESUBIMAGE3DEXTPROC __glewTextureSubImage3DEXT;
 GLEW_FUN_EXPORT PFNGLUNMAPNAMEDBUFFEREXTPROC __glewUnmapNamedBufferEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYCOLOROFFSETEXTPROC __glewVertexArrayColorOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC __glewVertexArrayEdgeFlagOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC __glewVertexArrayFogCoordOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYINDEXOFFSETEXTPROC __glewVertexArrayIndexOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC __glewVertexArrayMultiTexCoordOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYNORMALOFFSETEXTPROC __glewVertexArrayNormalOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC __glewVertexArraySecondaryColorOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC __glewVertexArrayTexCoordOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC __glewVertexArrayVertexAttribIOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC __glewVertexArrayVertexAttribOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC __glewVertexArrayVertexOffsetEXT;
 
 GLEW_FUN_EXPORT PFNGLCOLORMASKINDEXEDEXTPROC __glewColorMaskIndexedEXT;
 GLEW_FUN_EXPORT PFNGLDISABLEINDEXEDEXTPROC __glewDisableIndexedEXT;
@@ -11309,6 +13298,8 @@ GLEW_FUN_EXPORT PFNGLPOINTPARAMETERFVEXTPROC __glewPointParameterfvEXT;
 
 GLEW_FUN_EXPORT PFNGLPOLYGONOFFSETEXTPROC __glewPolygonOffsetEXT;
 
+GLEW_FUN_EXPORT PFNGLPROVOKINGVERTEXEXTPROC __glewProvokingVertexEXT;
+
 GLEW_FUN_EXPORT PFNGLBEGINSCENEEXTPROC __glewBeginSceneEXT;
 GLEW_FUN_EXPORT PFNGLENDSCENEEXTPROC __glewEndSceneEXT;
 
@@ -11330,6 +13321,13 @@ GLEW_FUN_EXPORT PFNGLSECONDARYCOLOR3USEXTPROC __glewSecondaryColor3usEXT;
 GLEW_FUN_EXPORT PFNGLSECONDARYCOLOR3USVEXTPROC __glewSecondaryColor3usvEXT;
 GLEW_FUN_EXPORT PFNGLSECONDARYCOLORPOINTEREXTPROC __glewSecondaryColorPointerEXT;
 
+GLEW_FUN_EXPORT PFNGLACTIVEPROGRAMEXTPROC __glewActiveProgramEXT;
+GLEW_FUN_EXPORT PFNGLCREATESHADERPROGRAMEXTPROC __glewCreateShaderProgramEXT;
+GLEW_FUN_EXPORT PFNGLUSESHADERPROGRAMEXTPROC __glewUseShaderProgramEXT;
+
+GLEW_FUN_EXPORT PFNGLBINDIMAGETEXTUREEXTPROC __glewBindImageTextureEXT;
+GLEW_FUN_EXPORT PFNGLMEMORYBARRIEREXTPROC __glewMemoryBarrierEXT;
+
 GLEW_FUN_EXPORT PFNGLACTIVESTENCILFACEEXTPROC __glewActiveStencilFaceEXT;
 
 GLEW_FUN_EXPORT PFNGLTEXSUBIMAGE1DEXTPROC __glewTexSubImage1DEXT;
@@ -11377,6 +13375,18 @@ GLEW_FUN_EXPORT PFNGLNORMALPOINTEREXTPROC __glewNormalPointerEXT;
 GLEW_FUN_EXPORT PFNGLTEXCOORDPOINTEREXTPROC __glewTexCoordPointerEXT;
 GLEW_FUN_EXPORT PFNGLVERTEXPOINTEREXTPROC __glewVertexPointerEXT;
 
+GLEW_FUN_EXPORT PFNGLGETVERTEXATTRIBLDVEXTPROC __glewGetVertexAttribLdvEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC __glewVertexArrayVertexAttribLOffsetEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1DEXTPROC __glewVertexAttribL1dEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1DVEXTPROC __glewVertexAttribL1dvEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2DEXTPROC __glewVertexAttribL2dEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2DVEXTPROC __glewVertexAttribL2dvEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3DEXTPROC __glewVertexAttribL3dEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3DVEXTPROC __glewVertexAttribL3dvEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4DEXTPROC __glewVertexAttribL4dEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4DVEXTPROC __glewVertexAttribL4dvEXT;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBLPOINTEREXTPROC __glewVertexAttribLPointerEXT;
+
 GLEW_FUN_EXPORT PFNGLBEGINVERTEXSHADEREXTPROC __glewBeginVertexShaderEXT;
 GLEW_FUN_EXPORT PFNGLBINDLIGHTPARAMETEREXTPROC __glewBindLightParameterEXT;
 GLEW_FUN_EXPORT PFNGLBINDMATERIALPARAMETEREXTPROC __glewBindMaterialParameterEXT;
@@ -11491,6 +13501,8 @@ GLEW_FUN_EXPORT PFNGLWINDOWPOS4SVMESAPROC __glewWindowPos4svMESA;
 GLEW_FUN_EXPORT PFNGLBEGINCONDITIONALRENDERNVPROC __glewBeginConditionalRenderNV;
 GLEW_FUN_EXPORT PFNGLENDCONDITIONALRENDERNVPROC __glewEndConditionalRenderNV;
 
+GLEW_FUN_EXPORT PFNGLCOPYIMAGESUBDATANVPROC __glewCopyImageSubDataNV;
+
 GLEW_FUN_EXPORT PFNGLCLEARDEPTHDNVPROC __glewClearDepthdNV;
 GLEW_FUN_EXPORT PFNGLDEPTHBOUNDSDNVPROC __glewDepthBoundsdNV;
 GLEW_FUN_EXPORT PFNGLDEPTHRANGEDNVPROC __glewDepthRangedNV;
@@ -11541,6 +13553,41 @@ GLEW_FUN_EXPORT PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC __glewProgramLocalParamete
 GLEW_FUN_EXPORT PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC __glewProgramLocalParametersI4ivNV;
 GLEW_FUN_EXPORT PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC __glewProgramLocalParametersI4uivNV;
 
+GLEW_FUN_EXPORT PFNGLGETUNIFORMI64VNVPROC __glewGetUniformi64vNV;
+GLEW_FUN_EXPORT PFNGLGETUNIFORMUI64VNVPROC __glewGetUniformui64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM1I64NVPROC __glewProgramUniform1i64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM1I64VNVPROC __glewProgramUniform1i64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM1UI64NVPROC __glewProgramUniform1ui64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM1UI64VNVPROC __glewProgramUniform1ui64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM2I64NVPROC __glewProgramUniform2i64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM2I64VNVPROC __glewProgramUniform2i64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM2UI64NVPROC __glewProgramUniform2ui64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM2UI64VNVPROC __glewProgramUniform2ui64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM3I64NVPROC __glewProgramUniform3i64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM3I64VNVPROC __glewProgramUniform3i64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM3UI64NVPROC __glewProgramUniform3ui64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM3UI64VNVPROC __glewProgramUniform3ui64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM4I64NVPROC __glewProgramUniform4i64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM4I64VNVPROC __glewProgramUniform4i64vNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM4UI64NVPROC __glewProgramUniform4ui64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORM4UI64VNVPROC __glewProgramUniform4ui64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM1I64NVPROC __glewUniform1i64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM1I64VNVPROC __glewUniform1i64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM1UI64NVPROC __glewUniform1ui64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM1UI64VNVPROC __glewUniform1ui64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM2I64NVPROC __glewUniform2i64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM2I64VNVPROC __glewUniform2i64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM2UI64NVPROC __glewUniform2ui64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM2UI64VNVPROC __glewUniform2ui64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM3I64NVPROC __glewUniform3i64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM3I64VNVPROC __glewUniform3i64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM3UI64NVPROC __glewUniform3ui64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM3UI64VNVPROC __glewUniform3ui64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM4I64NVPROC __glewUniform4i64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM4I64VNVPROC __glewUniform4i64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORM4UI64NVPROC __glewUniform4ui64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORM4UI64VNVPROC __glewUniform4ui64vNV;
+
 GLEW_FUN_EXPORT PFNGLCOLOR3HNVPROC __glewColor3hNV;
 GLEW_FUN_EXPORT PFNGLCOLOR3HVNVPROC __glewColor3hvNV;
 GLEW_FUN_EXPORT PFNGLCOLOR4HNVPROC __glewColor4hNV;
@@ -11612,7 +13659,6 @@ GLEW_FUN_EXPORT PFNGLGETVIDEOUI64VNVPROC __glewGetVideoui64vNV;
 GLEW_FUN_EXPORT PFNGLGETVIDEOUIVNVPROC __glewGetVideouivNV;
 GLEW_FUN_EXPORT PFNGLPRESENTFRAMEDUALFILLNVPROC __glewPresentFrameDualFillNV;
 GLEW_FUN_EXPORT PFNGLPRESENTFRAMEKEYEDNVPROC __glewPresentFrameKeyedNV;
-GLEW_FUN_EXPORT PFNGLVIDEOPARAMETERIVNVPROC __glewVideoParameterivNV;
 
 GLEW_FUN_EXPORT PFNGLPRIMITIVERESTARTINDEXNVPROC __glewPrimitiveRestartIndexNV;
 GLEW_FUN_EXPORT PFNGLPRIMITIVERESTARTNVPROC __glewPrimitiveRestartNV;
@@ -11634,6 +13680,22 @@ GLEW_FUN_EXPORT PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC __glewGetFinalCombin
 GLEW_FUN_EXPORT PFNGLCOMBINERSTAGEPARAMETERFVNVPROC __glewCombinerStageParameterfvNV;
 GLEW_FUN_EXPORT PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC __glewGetCombinerStageParameterfvNV;
 
+GLEW_FUN_EXPORT PFNGLGETBUFFERPARAMETERUI64VNVPROC __glewGetBufferParameterui64vNV;
+GLEW_FUN_EXPORT PFNGLGETINTEGERUI64VNVPROC __glewGetIntegerui64vNV;
+GLEW_FUN_EXPORT PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC __glewGetNamedBufferParameterui64vNV;
+GLEW_FUN_EXPORT PFNGLISBUFFERRESIDENTNVPROC __glewIsBufferResidentNV;
+GLEW_FUN_EXPORT PFNGLISNAMEDBUFFERRESIDENTNVPROC __glewIsNamedBufferResidentNV;
+GLEW_FUN_EXPORT PFNGLMAKEBUFFERNONRESIDENTNVPROC __glewMakeBufferNonResidentNV;
+GLEW_FUN_EXPORT PFNGLMAKEBUFFERRESIDENTNVPROC __glewMakeBufferResidentNV;
+GLEW_FUN_EXPORT PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC __glewMakeNamedBufferNonResidentNV;
+GLEW_FUN_EXPORT PFNGLMAKENAMEDBUFFERRESIDENTNVPROC __glewMakeNamedBufferResidentNV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORMUI64NVPROC __glewProgramUniformui64NV;
+GLEW_FUN_EXPORT PFNGLPROGRAMUNIFORMUI64VNVPROC __glewProgramUniformui64vNV;
+GLEW_FUN_EXPORT PFNGLUNIFORMUI64NVPROC __glewUniformui64NV;
+GLEW_FUN_EXPORT PFNGLUNIFORMUI64VNVPROC __glewUniformui64vNV;
+
+GLEW_FUN_EXPORT PFNGLTEXTUREBARRIERNVPROC __glewTextureBarrierNV;
+
 GLEW_FUN_EXPORT PFNGLACTIVEVARYINGNVPROC __glewActiveVaryingNV;
 GLEW_FUN_EXPORT PFNGLBEGINTRANSFORMFEEDBACKNVPROC __glewBeginTransformFeedbackNV;
 GLEW_FUN_EXPORT PFNGLBINDBUFFERBASENVPROC __glewBindBufferBaseNV;
@@ -11646,9 +13708,50 @@ GLEW_FUN_EXPORT PFNGLGETVARYINGLOCATIONNVPROC __glewGetVaryingLocationNV;
 GLEW_FUN_EXPORT PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC __glewTransformFeedbackAttribsNV;
 GLEW_FUN_EXPORT PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC __glewTransformFeedbackVaryingsNV;
 
+GLEW_FUN_EXPORT PFNGLBINDTRANSFORMFEEDBACKNVPROC __glewBindTransformFeedbackNV;
+GLEW_FUN_EXPORT PFNGLDELETETRANSFORMFEEDBACKSNVPROC __glewDeleteTransformFeedbacksNV;
+GLEW_FUN_EXPORT PFNGLDRAWTRANSFORMFEEDBACKNVPROC __glewDrawTransformFeedbackNV;
+GLEW_FUN_EXPORT PFNGLGENTRANSFORMFEEDBACKSNVPROC __glewGenTransformFeedbacksNV;
+GLEW_FUN_EXPORT PFNGLISTRANSFORMFEEDBACKNVPROC __glewIsTransformFeedbackNV;
+GLEW_FUN_EXPORT PFNGLPAUSETRANSFORMFEEDBACKNVPROC __glewPauseTransformFeedbackNV;
+GLEW_FUN_EXPORT PFNGLRESUMETRANSFORMFEEDBACKNVPROC __glewResumeTransformFeedbackNV;
+
 GLEW_FUN_EXPORT PFNGLFLUSHVERTEXARRAYRANGENVPROC __glewFlushVertexArrayRangeNV;
 GLEW_FUN_EXPORT PFNGLVERTEXARRAYRANGENVPROC __glewVertexArrayRangeNV;
 
+GLEW_FUN_EXPORT PFNGLGETVERTEXATTRIBLI64VNVPROC __glewGetVertexAttribLi64vNV;
+GLEW_FUN_EXPORT PFNGLGETVERTEXATTRIBLUI64VNVPROC __glewGetVertexAttribLui64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1I64NVPROC __glewVertexAttribL1i64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1I64VNVPROC __glewVertexAttribL1i64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1UI64NVPROC __glewVertexAttribL1ui64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL1UI64VNVPROC __glewVertexAttribL1ui64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2I64NVPROC __glewVertexAttribL2i64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2I64VNVPROC __glewVertexAttribL2i64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2UI64NVPROC __glewVertexAttribL2ui64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL2UI64VNVPROC __glewVertexAttribL2ui64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3I64NVPROC __glewVertexAttribL3i64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3I64VNVPROC __glewVertexAttribL3i64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3UI64NVPROC __glewVertexAttribL3ui64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL3UI64VNVPROC __glewVertexAttribL3ui64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4I64NVPROC __glewVertexAttribL4i64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4I64VNVPROC __glewVertexAttribL4i64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4UI64NVPROC __glewVertexAttribL4ui64NV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBL4UI64VNVPROC __glewVertexAttribL4ui64vNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBLFORMATNVPROC __glewVertexAttribLFormatNV;
+
+GLEW_FUN_EXPORT PFNGLBUFFERADDRESSRANGENVPROC __glewBufferAddressRangeNV;
+GLEW_FUN_EXPORT PFNGLCOLORFORMATNVPROC __glewColorFormatNV;
+GLEW_FUN_EXPORT PFNGLEDGEFLAGFORMATNVPROC __glewEdgeFlagFormatNV;
+GLEW_FUN_EXPORT PFNGLFOGCOORDFORMATNVPROC __glewFogCoordFormatNV;
+GLEW_FUN_EXPORT PFNGLGETINTEGERUI64I_VNVPROC __glewGetIntegerui64i_vNV;
+GLEW_FUN_EXPORT PFNGLINDEXFORMATNVPROC __glewIndexFormatNV;
+GLEW_FUN_EXPORT PFNGLNORMALFORMATNVPROC __glewNormalFormatNV;
+GLEW_FUN_EXPORT PFNGLSECONDARYCOLORFORMATNVPROC __glewSecondaryColorFormatNV;
+GLEW_FUN_EXPORT PFNGLTEXCOORDFORMATNVPROC __glewTexCoordFormatNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBFORMATNVPROC __glewVertexAttribFormatNV;
+GLEW_FUN_EXPORT PFNGLVERTEXATTRIBIFORMATNVPROC __glewVertexAttribIFormatNV;
+GLEW_FUN_EXPORT PFNGLVERTEXFORMATNVPROC __glewVertexFormatNV;
+
 GLEW_FUN_EXPORT PFNGLAREPROGRAMSRESIDENTNVPROC __glewAreProgramsResidentNV;
 GLEW_FUN_EXPORT PFNGLBINDPROGRAMNVPROC __glewBindProgramNV;
 GLEW_FUN_EXPORT PFNGLDELETEPROGRAMSNVPROC __glewDeleteProgramsNV;
@@ -11866,32 +13969,59 @@ GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_1_5;
 GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_2_0;
 GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_2_1;
 GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_3_0;
+GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_3_1;
+GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_3_2;
+GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_3_3;
+GLEW_VAR_EXPORT GLboolean __GLEW_VERSION_4_0;
 GLEW_VAR_EXPORT GLboolean __GLEW_3DFX_multisample;
 GLEW_VAR_EXPORT GLboolean __GLEW_3DFX_tbuffer;
 GLEW_VAR_EXPORT GLboolean __GLEW_3DFX_texture_compression_FXT1;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_conservative_depth;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_draw_buffers_blend;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_performance_monitor;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_seamless_cubemap_per_texture;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_shader_stencil_export;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_texture_texture4;
+GLEW_VAR_EXPORT GLboolean __GLEW_AMD_vertex_shader_tessellator;
+GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_aux_depth_stencil;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_client_storage;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_element_array;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_fence;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_float_pixels;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_flush_buffer_range;
+GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_object_purgeable;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_pixel_buffer;
+GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_rgb_422;
+GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_row_bytes;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_specular_vector;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_texture_range;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_transform_hint;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_vertex_array_object;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_vertex_array_range;
+GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_vertex_program_evaluators;
 GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_ycbcr_422;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_blend_func_extended;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_color_buffer_float;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_compatibility;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_copy_buffer;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_depth_buffer_float;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_depth_clamp;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_depth_texture;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_buffers;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_buffers_blend;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_elements_base_vertex;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_indirect;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_instanced;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_explicit_attrib_location;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_fragment_coord_conventions;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_fragment_program;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_fragment_program_shadow;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_fragment_shader;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_framebuffer_object;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_framebuffer_sRGB;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_geometry_shader4;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_gpu_shader5;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_gpu_shader_fp64;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_half_float_pixel;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_half_float_vertex;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_imaging;
@@ -11901,33 +14031,58 @@ GLEW_VAR_EXPORT GLboolean __GLEW_ARB_matrix_palette;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_multisample;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_multitexture;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_occlusion_query;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_occlusion_query2;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_pixel_buffer_object;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_point_parameters;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_point_sprite;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_provoking_vertex;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_sample_shading;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_sampler_objects;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_seamless_cube_map;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shader_bit_encoding;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shader_objects;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shader_subroutine;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shader_texture_lod;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shading_language_100;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shading_language_include;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shadow;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shadow_ambient;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_sync;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_tessellation_shader;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_border_clamp;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_buffer_object;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_buffer_object_rgb32;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_compression;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_compression_bptc;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_compression_rgtc;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_cube_map;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_cube_map_array;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_env_add;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_env_combine;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_env_crossbar;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_env_dot3;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_float;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_gather;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_mirrored_repeat;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_multisample;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_non_power_of_two;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_query_lod;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_rectangle;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_rg;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_rgb10_a2ui;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_swizzle;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_timer_query;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_transform_feedback2;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_transform_feedback3;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_transpose_matrix;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_uniform_buffer_object;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_array_bgra;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_array_object;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_blend;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_buffer_object;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_program;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_shader;
+GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_type_2_10_10_10_rev;
 GLEW_VAR_EXPORT GLboolean __GLEW_ARB_window_pos;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATIX_point_sprites;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATIX_texture_env_combine3;
@@ -11938,6 +14093,7 @@ GLEW_VAR_EXPORT GLboolean __GLEW_ATI_element_array;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_envmap_bumpmap;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_fragment_shader;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_map_object_buffer;
+GLEW_VAR_EXPORT GLboolean __GLEW_ATI_meminfo;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_pn_triangles;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_separate_stencil;
 GLEW_VAR_EXPORT GLboolean __GLEW_ATI_shader_texture_lod;
@@ -12000,10 +14156,13 @@ GLEW_VAR_EXPORT GLboolean __GLEW_EXT_pixel_transform;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_pixel_transform_color_table;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_point_parameters;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_polygon_offset;
+GLEW_VAR_EXPORT GLboolean __GLEW_EXT_provoking_vertex;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_rescale_normal;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_scene_marker;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_secondary_color;
+GLEW_VAR_EXPORT GLboolean __GLEW_EXT_separate_shader_objects;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_separate_specular_color;
+GLEW_VAR_EXPORT GLboolean __GLEW_EXT_shader_image_load_store;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_shadow_funcs;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_shared_texture_palette;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_stencil_clear_tag;
@@ -12033,11 +14192,13 @@ GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_perturb_normal;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_rectangle;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_sRGB;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_shared_exponent;
+GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_snorm;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_swizzle;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_timer_query;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_transform_feedback;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_vertex_array;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_vertex_array_bgra;
+GLEW_VAR_EXPORT GLboolean __GLEW_EXT_vertex_attrib_64bit;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_vertex_shader;
 GLEW_VAR_EXPORT GLboolean __GLEW_EXT_vertex_weighting;
 GLEW_VAR_EXPORT GLboolean __GLEW_GREMEDY_frame_terminator;
@@ -12065,6 +14226,7 @@ GLEW_VAR_EXPORT GLboolean __GLEW_MESA_ycbcr_texture;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_blend_square;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_conditional_render;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_copy_depth_to_color;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_copy_image;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_depth_buffer_float;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_depth_clamp;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_depth_range_unclamped;
@@ -12081,20 +14243,27 @@ GLEW_VAR_EXPORT GLboolean __GLEW_NV_framebuffer_multisample_coverage;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_geometry_program4;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_geometry_shader4;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_gpu_program4;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_gpu_program5;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_gpu_program_fp64;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_gpu_shader5;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_half_float;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_light_max_exponent;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_multisample_filter_hint;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_occlusion_query;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_packed_depth_stencil;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_parameter_buffer_object;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_parameter_buffer_object2;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_pixel_data_range;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_point_sprite;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_present_video;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_primitive_restart;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_register_combiners;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_register_combiners2;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_shader_buffer_load;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_tessellation_program5;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texgen_emboss;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texgen_reflection;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_barrier;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_compression_vtc;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_env_combine4;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_expand_normal;
@@ -12103,8 +14272,11 @@ GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_shader;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_shader2;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_texture_shader3;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_transform_feedback;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_transform_feedback2;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_array_range;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_array_range2;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_attrib_integer_64bit;
+GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_buffer_unified_memory;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_program;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_program1_1;
 GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_program2;
@@ -12244,6 +14416,7 @@ GLEWAPI const GLubyte* glewGetString (GLenum name);
 #undef GLEW_APIENTRY_DEFINED
 #undef APIENTRY
 #undef GLAPIENTRY
+#define GLAPIENTRY
 #endif
 
 #ifdef GLEW_CALLBACK_DEFINED
diff --git a/modules/gfx/src/GL/glxew.h b/modules/gfx/src/GL/glxew.h
index a29030da3cbeb435ceb66f488315621a74913954..637ef1eaab7757446f25ffc7473ea386b96fff1a 100644
--- a/modules/gfx/src/GL/glxew.h
+++ b/modules/gfx/src/GL/glxew.h
@@ -83,13 +83,16 @@
 #ifdef __glxext_h_
 #error glxext.h included before glxew.h
 #endif
-#ifdef GLX_H
+
+#if defined(GLX_H) || defined(__GLX_glx_h__) || defined(__glx_h__)
 #error glx.h included before glxew.h
 #endif
 
 #define __glxext_h_
-#define __GLX_glx_h__
+
 #define GLX_H
+#define __GLX_glx_h__
+#define __glx_h__
 
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
@@ -362,6 +365,19 @@ typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display* dpy, GLXFBCo
 
 #endif /* GLX_ARB_create_context */
 
+/* --------------------- GLX_ARB_create_context_profile -------------------- */
+
+#ifndef GLX_ARB_create_context_profile
+#define GLX_ARB_create_context_profile 1
+
+#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
+#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
+#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
+
+#define GLXEW_ARB_create_context_profile GLXEW_GET_VAR(__GLXEW_ARB_create_context_profile)
+
+#endif /* GLX_ARB_create_context_profile */
+
 /* ------------------------- GLX_ARB_fbconfig_float ------------------------ */
 
 #ifndef GLX_ARB_fbconfig_float
@@ -408,6 +424,17 @@ extern void ( * glXGetProcAddressARB (const GLubyte *procName)) (void);
 
 #endif /* GLX_ARB_multisample */
 
+/* ---------------------- GLX_ARB_vertex_buffer_object --------------------- */
+
+#ifndef GLX_ARB_vertex_buffer_object
+#define GLX_ARB_vertex_buffer_object 1
+
+#define GLX_CONTEXT_ALLOW_BUFFER_BYTE_ORDER_MISMATCH_ARB 0x2095
+
+#define GLXEW_ARB_vertex_buffer_object GLXEW_GET_VAR(__GLXEW_ARB_vertex_buffer_object)
+
+#endif /* GLX_ARB_vertex_buffer_object */
+
 /* ----------------------- GLX_ATI_pixel_format_float ---------------------- */
 
 #ifndef GLX_ATI_pixel_format_float
@@ -529,6 +556,22 @@ typedef int ( * PFNGLXQUERYCONTEXTINFOEXTPROC) (Display* dpy, GLXContext context
 
 #endif /* GLX_EXT_scene_marker */
 
+/* -------------------------- GLX_EXT_swap_control ------------------------- */
+
+#ifndef GLX_EXT_swap_control
+#define GLX_EXT_swap_control 1
+
+#define GLX_SWAP_INTERVAL_EXT 0x20F1
+#define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2
+
+typedef void ( * PFNGLXSWAPINTERVALEXTPROC) (Display* dpy, GLXDrawable drawable, int interval);
+
+#define glXSwapIntervalEXT GLXEW_GET_FUN(__glewXSwapIntervalEXT)
+
+#define GLXEW_EXT_swap_control GLXEW_GET_VAR(__GLXEW_EXT_swap_control)
+
+#endif /* GLX_EXT_swap_control */
+
 /* ---------------------- GLX_EXT_texture_from_pixmap ---------------------- */
 
 #ifndef GLX_EXT_texture_from_pixmap
@@ -615,6 +658,20 @@ typedef void ( * PFNGLXRELEASETEXIMAGEEXTPROC) (Display* display, GLXDrawable dr
 
 #endif /* GLX_EXT_visual_rating */
 
+/* -------------------------- GLX_INTEL_swap_event ------------------------- */
+
+#ifndef GLX_INTEL_swap_event
+#define GLX_INTEL_swap_event 1
+
+#define GLX_EXCHANGE_COMPLETE_INTEL 0x8180
+#define GLX_COPY_COMPLETE_INTEL 0x8181
+#define GLX_FLIP_COMPLETE_INTEL 0x8182
+#define GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK 0x04000000
+
+#define GLXEW_INTEL_swap_event GLXEW_GET_VAR(__GLXEW_INTEL_swap_event)
+
+#endif /* GLX_INTEL_swap_event */
+
 /* -------------------------- GLX_MESA_agp_offset -------------------------- */
 
 #ifndef GLX_MESA_agp_offset
@@ -683,6 +740,19 @@ typedef GLboolean ( * PFNGLXSET3DFXMODEMESAPROC) (GLint mode);
 
 #endif /* GLX_MESA_set_3dfx_mode */
 
+/* --------------------------- GLX_NV_copy_image --------------------------- */
+
+#ifndef GLX_NV_copy_image
+#define GLX_NV_copy_image 1
+
+typedef void ( * PFNGLXCOPYIMAGESUBDATANVPROC) (Display *dpy, GLXContext srcCtx, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLXContext dstCtx, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+
+#define glXCopyImageSubDataNV GLXEW_GET_FUN(__glewXCopyImageSubDataNV)
+
+#define GLXEW_NV_copy_image GLXEW_GET_VAR(__GLXEW_NV_copy_image)
+
+#endif /* GLX_NV_copy_image */
+
 /* -------------------------- GLX_NV_float_buffer -------------------------- */
 
 #ifndef GLX_NV_float_buffer
@@ -1217,6 +1287,8 @@ extern PFNGLXGETCONTEXTIDEXTPROC __glewXGetContextIDEXT;
 extern PFNGLXIMPORTCONTEXTEXTPROC __glewXImportContextEXT;
 extern PFNGLXQUERYCONTEXTINFOEXTPROC __glewXQueryContextInfoEXT;
 
+extern PFNGLXSWAPINTERVALEXTPROC __glewXSwapIntervalEXT;
+
 extern PFNGLXBINDTEXIMAGEEXTPROC __glewXBindTexImageEXT;
 extern PFNGLXRELEASETEXIMAGEEXTPROC __glewXReleaseTexImageEXT;
 
@@ -1230,6 +1302,8 @@ extern PFNGLXRELEASEBUFFERSMESAPROC __glewXReleaseBuffersMESA;
 
 extern PFNGLXSET3DFXMODEMESAPROC __glewXSet3DfxModeMESA;
 
+extern PFNGLXCOPYIMAGESUBDATANVPROC __glewXCopyImageSubDataNV;
+
 extern PFNGLXBINDVIDEODEVICENVPROC __glewXBindVideoDeviceNV;
 extern PFNGLXENUMERATEVIDEODEVICESNVPROC __glewXEnumerateVideoDevicesNV;
 
@@ -1318,24 +1392,29 @@ GLXEW_EXPORT GLboolean __GLXEW_VERSION_1_3;
 GLXEW_EXPORT GLboolean __GLXEW_VERSION_1_4;
 GLXEW_EXPORT GLboolean __GLXEW_3DFX_multisample;
 GLXEW_EXPORT GLboolean __GLXEW_ARB_create_context;
+GLXEW_EXPORT GLboolean __GLXEW_ARB_create_context_profile;
 GLXEW_EXPORT GLboolean __GLXEW_ARB_fbconfig_float;
 GLXEW_EXPORT GLboolean __GLXEW_ARB_framebuffer_sRGB;
 GLXEW_EXPORT GLboolean __GLXEW_ARB_get_proc_address;
 GLXEW_EXPORT GLboolean __GLXEW_ARB_multisample;
+GLXEW_EXPORT GLboolean __GLXEW_ARB_vertex_buffer_object;
 GLXEW_EXPORT GLboolean __GLXEW_ATI_pixel_format_float;
 GLXEW_EXPORT GLboolean __GLXEW_ATI_render_texture;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_fbconfig_packed_float;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_framebuffer_sRGB;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_import_context;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_scene_marker;
+GLXEW_EXPORT GLboolean __GLXEW_EXT_swap_control;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_texture_from_pixmap;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_visual_info;
 GLXEW_EXPORT GLboolean __GLXEW_EXT_visual_rating;
+GLXEW_EXPORT GLboolean __GLXEW_INTEL_swap_event;
 GLXEW_EXPORT GLboolean __GLXEW_MESA_agp_offset;
 GLXEW_EXPORT GLboolean __GLXEW_MESA_copy_sub_buffer;
 GLXEW_EXPORT GLboolean __GLXEW_MESA_pixmap_colormap;
 GLXEW_EXPORT GLboolean __GLXEW_MESA_release_buffers;
 GLXEW_EXPORT GLboolean __GLXEW_MESA_set_3dfx_mode;
+GLXEW_EXPORT GLboolean __GLXEW_NV_copy_image;
 GLXEW_EXPORT GLboolean __GLXEW_NV_float_buffer;
 GLXEW_EXPORT GLboolean __GLXEW_NV_present_video;
 GLXEW_EXPORT GLboolean __GLXEW_NV_swap_group;
diff --git a/modules/gfx/src/GL/wglew.h b/modules/gfx/src/GL/wglew.h
index e35cd04b72a17e73b9470d18b894e04b00eada67..7c7a3804794cbe861bbaefe67a2d01a4f965c14a 100644
--- a/modules/gfx/src/GL/wglew.h
+++ b/modules/gfx/src/GL/wglew.h
@@ -62,11 +62,12 @@
 
 #define __wglext_h_
 
-#if !defined(APIENTRY) && !defined(__CYGWIN__)
-#  ifndef _MSC_VER_LEAN_AND_MEAN
-#    define _MSC_VER_LEAN_AND_MEAN 1
+#if !defined(WINAPI)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
 #  endif
 #include <windows.h>
+#  undef WIN32_LEAN_AND_MEAN
 #endif
 
 /*
@@ -117,6 +118,46 @@ typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState
 
 #endif /* WGL_3DL_stereo_control */
 
+/* ------------------------ WGL_AMD_gpu_association ------------------------ */
+
+#ifndef WGL_AMD_gpu_association
+#define WGL_AMD_gpu_association 1
+
+#define WGL_GPU_VENDOR_AMD 0x1F00
+#define WGL_GPU_RENDERER_STRING_AMD 0x1F01
+#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
+#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
+#define WGL_GPU_RAM_AMD 0x21A3
+#define WGL_GPU_CLOCK_AMD 0x21A4
+#define WGL_GPU_NUM_PIPES_AMD 0x21A5
+#define WGL_GPU_NUM_SIMD_AMD 0x21A6
+#define WGL_GPU_NUM_RB_AMD 0x21A7
+#define WGL_GPU_NUM_SPI_AMD 0x21A8
+
+typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id);
+typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int* attribList);
+typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc);
+typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc);
+typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
+typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT* ids);
+typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, INT property, GLenum dataType, UINT size, void* data);
+typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc);
+
+#define wglBlitContextFramebufferAMD WGLEW_GET_FUN(__wglewBlitContextFramebufferAMD)
+#define wglCreateAssociatedContextAMD WGLEW_GET_FUN(__wglewCreateAssociatedContextAMD)
+#define wglCreateAssociatedContextAttribsAMD WGLEW_GET_FUN(__wglewCreateAssociatedContextAttribsAMD)
+#define wglDeleteAssociatedContextAMD WGLEW_GET_FUN(__wglewDeleteAssociatedContextAMD)
+#define wglGetContextGPUIDAMD WGLEW_GET_FUN(__wglewGetContextGPUIDAMD)
+#define wglGetCurrentAssociatedContextAMD WGLEW_GET_FUN(__wglewGetCurrentAssociatedContextAMD)
+#define wglGetGPUIDsAMD WGLEW_GET_FUN(__wglewGetGPUIDsAMD)
+#define wglGetGPUInfoAMD WGLEW_GET_FUN(__wglewGetGPUInfoAMD)
+#define wglMakeAssociatedContextCurrentAMD WGLEW_GET_FUN(__wglewMakeAssociatedContextCurrentAMD)
+
+#define WGLEW_AMD_gpu_association WGLEW_GET_VAR(__WGLEW_AMD_gpu_association)
+
+#endif /* WGL_AMD_gpu_association */
+
 /* ------------------------- WGL_ARB_buffer_region ------------------------- */
 
 #ifndef WGL_ARB_buffer_region
@@ -161,6 +202,19 @@ typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShar
 
 #endif /* WGL_ARB_create_context */
 
+/* --------------------- WGL_ARB_create_context_profile -------------------- */
+
+#ifndef WGL_ARB_create_context_profile
+#define WGL_ARB_create_context_profile 1
+
+#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
+#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
+#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
+
+#define WGLEW_ARB_create_context_profile WGLEW_GET_VAR(__WGLEW_ARB_create_context_profile)
+
+#endif /* WGL_ARB_create_context_profile */
+
 /* ----------------------- WGL_ARB_extensions_string ----------------------- */
 
 #ifndef WGL_ARB_extensions_string
@@ -752,6 +806,19 @@ typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD* pFrameCount, DWO
 
 #endif /* WGL_I3D_swap_frame_usage */
 
+/* --------------------------- WGL_NV_copy_image --------------------------- */
+
+#ifndef WGL_NV_copy_image
+#define WGL_NV_copy_image 1
+
+typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+
+#define wglCopyImageSubDataNV WGLEW_GET_FUN(__wglewCopyImageSubDataNV)
+
+#define WGLEW_NV_copy_image WGLEW_GET_VAR(__WGLEW_NV_copy_image)
+
+#endif /* WGL_NV_copy_image */
+
 /* -------------------------- WGL_NV_float_buffer -------------------------- */
 
 #ifndef WGL_NV_float_buffer
@@ -863,7 +930,7 @@ typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrie
 typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
 typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint* count);
 typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint* maxGroups, GLuint *maxBarriers);
-typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint* group);
+typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint* group, GLuint *barrier);
 typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
 
 #define wglBindSwapBarrierNV WGLEW_GET_FUN(__wglewBindSwapBarrierNV)
@@ -969,6 +1036,16 @@ struct WGLEWContextStruct
 
 WGLEW_EXPORT PFNWGLSETSTEREOEMITTERSTATE3DLPROC __wglewSetStereoEmitterState3DL;
 
+WGLEW_EXPORT PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC __wglewBlitContextFramebufferAMD;
+WGLEW_EXPORT PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC __wglewCreateAssociatedContextAMD;
+WGLEW_EXPORT PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC __wglewCreateAssociatedContextAttribsAMD;
+WGLEW_EXPORT PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC __wglewDeleteAssociatedContextAMD;
+WGLEW_EXPORT PFNWGLGETCONTEXTGPUIDAMDPROC __wglewGetContextGPUIDAMD;
+WGLEW_EXPORT PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC __wglewGetCurrentAssociatedContextAMD;
+WGLEW_EXPORT PFNWGLGETGPUIDSAMDPROC __wglewGetGPUIDsAMD;
+WGLEW_EXPORT PFNWGLGETGPUINFOAMDPROC __wglewGetGPUInfoAMD;
+WGLEW_EXPORT PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC __wglewMakeAssociatedContextCurrentAMD;
+
 WGLEW_EXPORT PFNWGLCREATEBUFFERREGIONARBPROC __wglewCreateBufferRegionARB;
 WGLEW_EXPORT PFNWGLDELETEBUFFERREGIONARBPROC __wglewDeleteBufferRegionARB;
 WGLEW_EXPORT PFNWGLRESTOREBUFFERREGIONARBPROC __wglewRestoreBufferRegionARB;
@@ -1054,6 +1131,8 @@ WGLEW_EXPORT PFNWGLENDFRAMETRACKINGI3DPROC __wglewEndFrameTrackingI3D;
 WGLEW_EXPORT PFNWGLGETFRAMEUSAGEI3DPROC __wglewGetFrameUsageI3D;
 WGLEW_EXPORT PFNWGLQUERYFRAMETRACKINGI3DPROC __wglewQueryFrameTrackingI3D;
 
+WGLEW_EXPORT PFNWGLCOPYIMAGESUBDATANVPROC __wglewCopyImageSubDataNV;
+
 WGLEW_EXPORT PFNWGLCREATEAFFINITYDCNVPROC __wglewCreateAffinityDCNV;
 WGLEW_EXPORT PFNWGLDELETEDCNVPROC __wglewDeleteDCNV;
 WGLEW_EXPORT PFNWGLENUMGPUDEVICESNVPROC __wglewEnumGpuDevicesNV;
@@ -1089,8 +1168,10 @@ WGLEW_EXPORT PFNWGLWAITFORMSCOMLPROC __wglewWaitForMscOML;
 WGLEW_EXPORT PFNWGLWAITFORSBCOMLPROC __wglewWaitForSbcOML;
 WGLEW_EXPORT GLboolean __WGLEW_3DFX_multisample;
 WGLEW_EXPORT GLboolean __WGLEW_3DL_stereo_control;
+WGLEW_EXPORT GLboolean __WGLEW_AMD_gpu_association;
 WGLEW_EXPORT GLboolean __WGLEW_ARB_buffer_region;
 WGLEW_EXPORT GLboolean __WGLEW_ARB_create_context;
+WGLEW_EXPORT GLboolean __WGLEW_ARB_create_context_profile;
 WGLEW_EXPORT GLboolean __WGLEW_ARB_extensions_string;
 WGLEW_EXPORT GLboolean __WGLEW_ARB_framebuffer_sRGB;
 WGLEW_EXPORT GLboolean __WGLEW_ARB_make_current_read;
@@ -1117,6 +1198,7 @@ WGLEW_EXPORT GLboolean __WGLEW_I3D_genlock;
 WGLEW_EXPORT GLboolean __WGLEW_I3D_image_buffer;
 WGLEW_EXPORT GLboolean __WGLEW_I3D_swap_frame_lock;
 WGLEW_EXPORT GLboolean __WGLEW_I3D_swap_frame_usage;
+WGLEW_EXPORT GLboolean __WGLEW_NV_copy_image;
 WGLEW_EXPORT GLboolean __WGLEW_NV_float_buffer;
 WGLEW_EXPORT GLboolean __WGLEW_NV_gpu_affinity;
 WGLEW_EXPORT GLboolean __WGLEW_NV_present_video;
diff --git a/modules/gfx/src/bitmap_io.cc b/modules/gfx/src/bitmap_io.cc
index 2723be73e9b7fc033279a975934f4557dfb67942..8117d4cc4dbce26e3312910f82d5bb01b8a42859 100644
--- a/modules/gfx/src/bitmap_io.cc
+++ b/modules/gfx/src/bitmap_io.cc
@@ -38,7 +38,8 @@ void export_png(const String& filename, unsigned int width, unsigned int height,
     LOG_ERROR("error opening" << filename << " for exporting");
     return;
   }
-  
+
+  LOG_DEBUG("creating png write struct");
   png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                 NULL, NULL, NULL);
   if (png_ptr == NULL) {
@@ -47,6 +48,7 @@ void export_png(const String& filename, unsigned int width, unsigned int height,
     return;
   }
   
+  LOG_DEBUG("creating png info struct");
   png_infop info_ptr = png_create_info_struct(png_ptr);
   if (info_ptr == NULL) {
     fclose(fp);
@@ -72,20 +74,24 @@ void export_png(const String& filename, unsigned int width, unsigned int height,
                PNG_INTERLACE_NONE,
                PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
   
+  LOG_DEBUG("writing png info");
   png_write_info(png_ptr, info_ptr);
   
   png_bytep* row_pointers = new png_bytep[height];
 
   png_byte* png_data = data;
 
+  LOG_DEBUG("assigning png row pointers");
   for(uint i=0;i<height;++i){
     row_pointers[height-i-1]=&png_data[i*4*width];
   }
 
+  LOG_DEBUG("writing png image");
   png_write_image(png_ptr, row_pointers);
 
   delete []row_pointers;
 
+  LOG_DEBUG("finalizing png write");
   png_write_end(png_ptr, info_ptr);
   
   png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
diff --git a/modules/gfx/src/color.cc b/modules/gfx/src/color.cc
index c1da35d27c6984d71896b06d18a80f01883109da..4b0c2f785cc1b0321c0b4d76965a7933600396ef 100644
--- a/modules/gfx/src/color.cc
+++ b/modules/gfx/src/color.cc
@@ -26,12 +26,108 @@
 
 namespace ost { namespace gfx {
 
-Color::Color(int code)
+namespace {
+// maps hsv to rgb (0-1)
+geom::Vec3 HSVtoRGB(const geom::Vec3& hsv)
 {
-  rgba[0]=static_cast<float>((code>>16)&0xff)/255.0;
-  rgba[1]=static_cast<float>((code>>8)&0xff)/255.0;
-  rgba[2]=static_cast<float>(code&0xff)/255.0;
-  rgba[3]=1.0;
+  geom::Vec3 rgb;
+  if (hsv[1]<1e-9){
+    rgb[0]=hsv[2];
+    rgb[1]=hsv[2];
+    rgb[2]=hsv[2];
+  } else {
+    double var_h=hsv[0]*6.0<6.0?hsv[0]*6.0:0.0;
+    int var_i =static_cast<int>(var_h);
+    double var_1 = hsv[2]*(1-hsv[1]);
+    double var_2 = hsv[2]*(1-hsv[1]*( var_h -var_i));
+    double var_3 = hsv[2]*(1-hsv[1]*(1-(var_h-var_i)));
+    switch(var_i){
+    case 0:
+      rgb[0]=hsv[2];
+      rgb[1]=var_3;
+      rgb[2]=var_1;
+      break;
+    case 1:
+      rgb[0] = var_2;
+      rgb[1] = hsv[2];
+      rgb[2] = var_1;
+      break;
+    case 2:
+      rgb[0] = var_1;
+      rgb[1] = hsv[2];
+      rgb[2] = var_3;
+      break;
+    case 3:
+      rgb[0] = var_1 ; 
+      rgb[1] = var_2 ; 
+      rgb[2] = hsv[2];
+      break;
+    case 4:
+      rgb[0] = var_3 ;
+      rgb[1] = var_1 ;
+      rgb[2] = hsv[2];
+      break;
+    case 5:
+      rgb[0] = hsv[2];
+      rgb[1] = var_1 ;
+      rgb[2] = var_2;
+      break;
+    }
+  }
+  return rgb;
+}
+
+// maps rgb (0-1) to hsv
+geom::Vec3 RGBtoHSV(const geom::Vec3& rgb)
+{
+  geom::Vec3 hsv;
+  double var_R = ( rgb[0] / 255.0 );
+  double var_G = ( rgb[1] / 255.0 );
+  double var_B = ( rgb[2] / 255.0 );
+
+  double var_Min = std::min(std::min( var_R, var_G), var_B );
+  double var_Max = std::max(std::max( var_R, var_G), var_B );
+  double del_Max = var_Max - var_Min;
+
+  hsv[2] = var_Max;
+
+  if ( del_Max < 1.0e-9 ){
+    hsv[0] = 0.0;
+    hsv[1] = 0.0;
+  } else {
+    hsv[1] = del_Max / var_Max;
+    double del_R = ( ( ( var_Max - var_R ) / 6.0 ) + ( del_Max / 2.0 ) ) / del_Max;
+    double del_G = ( ( ( var_Max - var_G ) / 6.0 ) + ( del_Max / 2.0 ) ) / del_Max;
+    double del_B = ( ( ( var_Max - var_B ) / 6.0 ) + ( del_Max / 2.0 ) ) / del_Max;
+    
+    if ( var_R == var_Max ){
+      hsv[0] = del_B - del_G;
+    } else if ( var_G == var_Max ){
+      hsv[0] = ( 1.0 / 3.0 ) + del_R - del_B;
+    } else if ( var_B == var_Max ){
+      hsv[0] = ( 2.0 / 3.0 ) + del_G - del_R;
+    }
+    if ( hsv[0] < 0 ){
+      hsv[0] += 1;
+    }
+    if ( hsv[0] > 1 ){
+      hsv[0] -= 1;
+    }
+  }
+  return hsv;
+}
+} // anon ns
+
+geom::Vec3 Color::ToHSV()
+{
+  return RGBtoHSV(geom::Vec3(rgba[0],rgba[1],rgba[2]));
+}
+
+
+Color HSV(double h, double s, double v)
+{
+  geom::Vec3 rgb=HSVtoRGB(geom::Vec3(h,s,v));
+  return Color(rgb[0],rgb[1],rgb[2]);
 }
 
 std::ostream& operator<<(std::ostream& s, const Color& c)
diff --git a/modules/gfx/src/color.hh b/modules/gfx/src/color.hh
index c659fe71c93c906bc3e37604fb1bf0727c40ee53..9357a1687d62053062d772e140376bb5762a10a9 100644
--- a/modules/gfx/src/color.hh
+++ b/modules/gfx/src/color.hh
@@ -28,6 +28,7 @@
 #include <boost/operators.hpp>
 
 #include <ost/gfx/module_config.hh>
+#include <ost/geom/geom.hh>
 
 namespace ost { namespace gfx {
 
@@ -51,22 +52,6 @@ public:
     rgba[3]=a;
   }
 
-  enum COLOR_NAME {
-    WHITE=0xffffff,
-    LIGHT_GREY=0xaaaaff,
-    GREY=0x999999ff,
-    DARK_GREY=0x333333ff,
-    BLACK=0x000000,
-    RED=0xff0000,
-    GREEN=0x00ff00,
-    BLUE=0x0000ff,
-    CYAN=0x00ffff,
-    MAGENTA=0xff00ff,
-    YELLOW=0xffff00
-  };
-
-  Color(int hex_code);
-
   float& Red() {return rgba[0];}
   const float& Red() const {return rgba[0];}
   float& Green() {return rgba[1];}
@@ -80,9 +65,10 @@ public:
                        unsigned char b, unsigned char a = 0xff) {
     static float f=1.0/255.0;
     return Color(f*static_cast<float>(r),f*static_cast<float>(g),
-		 f*static_cast<float>(b),f*static_cast<float>(a));
+                 f*static_cast<float>(b),f*static_cast<float>(a));
   }
-  //static Color HSB();
+
+  geom::Vec3 ToHSV();
 
   // these also take care of operator[](uint i) !
   operator float* () {return rgba;}
@@ -99,6 +85,8 @@ private:
   float rgba[4];
 };
 
+Color DLLEXPORT_OST_GFX HSV(double h, double s, double v);
+
 DLLEXPORT_OST_GFX std::ostream& operator<<(std::ostream&, const Color& c);
 
 }}
diff --git a/modules/gfx/src/entity.cc b/modules/gfx/src/entity.cc
index b5b068b21650ef79fce2956b443292a44999fcc9..e1c3fd0a6dbbc20343b5d55845950fa36cc7214a 100644
--- a/modules/gfx/src/entity.cc
+++ b/modules/gfx/src/entity.cc
@@ -64,10 +64,18 @@ using namespace impl;
 
 Entity::Entity(const String& name,
                const EntityHandle& h,
-               const Query& q):
+               const Query& q,
+               QueryFlags f):
   GfxObj(name),
-  qv_(q, h),
-  bbox_(geom::Vec3(), geom::Vec3())
+  qv_(q, f, h),
+  bbox_(geom::Vec3(), geom::Vec3()),
+  sel_(),
+  sel_update_(),
+  trace_(),
+  opacity_(1.0),
+  blur_(false),
+  blurf1_(1.0),
+  blurf2_(0.8)
 {
   init(RenderMode::SIMPLE);
 }
@@ -75,10 +83,18 @@ Entity::Entity(const String& name,
 Entity::Entity(const String& name,
                RenderMode::Type m,
                const EntityHandle& h,
-               const Query& q):
+               const Query& q,
+               QueryFlags f):
   GfxObj(name),
-  qv_(q, h),
-  bbox_(geom::Vec3(), geom::Vec3())  
+  qv_(q, f, h),
+  bbox_(geom::Vec3(), geom::Vec3()),
+  sel_(),
+  sel_update_(),
+  trace_(),
+  opacity_(1.0),
+  blur_(false),
+  blurf1_(1.0),
+  blurf2_(0.8)
 {
   init(m);
 }
@@ -87,7 +103,14 @@ Entity::Entity(const String& name,
                const EntityView& v):
   GfxObj(name),
   qv_(v),
-  bbox_(geom::Vec3(), geom::Vec3())  
+  bbox_(geom::Vec3(), geom::Vec3()),
+  sel_(),
+  sel_update_(),
+  trace_(),
+  opacity_(1.0),
+  blur_(false),
+  blurf1_(1.0),
+  blurf2_(0.8)
 {
   init(RenderMode::SIMPLE);
 }
@@ -97,7 +120,14 @@ Entity::Entity(const String& name,
                const EntityView& v):
   GfxObj(name),
   qv_(v),
-  bbox_(geom::Vec3(), geom::Vec3())  
+  bbox_(geom::Vec3(), geom::Vec3()),
+  sel_(),
+  sel_update_(),
+  trace_(),
+  opacity_(1.0),
+  blur_(false),
+  blurf1_(1.0),
+  blurf2_(0.8)
 {
   init(m);
 }
@@ -105,8 +135,9 @@ Entity::Entity(const String& name,
 
 impl::EntityRenderer* Entity::GetOrCreateRenderer(RenderMode::Type rm)
 {
-  if (renderer_.find(rm)!=renderer_.end()) {
-    return renderer_.find(rm)->second;
+  RendererMap::iterator rit = renderer_.find(rm);
+  if(rit!=renderer_.end()) {
+    return rit->second;
   }
   impl::EntityRenderer* r=NULL;
   switch (rm) {
@@ -117,22 +148,22 @@ impl::EntityRenderer* Entity::GetOrCreateRenderer(RenderMode::Type rm)
       r=new impl::CustomRenderer();
       break;
     case RenderMode::SLINE:
-      r=new impl::SlineRenderer(trace_);
+      r=new impl::SlineRenderer(&trace_);
       break;
     case RenderMode::LINE_TRACE:
-      r=new impl::LineTraceRenderer(trace_);
+      r=new impl::LineTraceRenderer(&trace_);
       break;
     case RenderMode::TRACE:
-      r=new impl::TraceRenderer(trace_);
+      r=new impl::TraceRenderer(&trace_);
       break;
     case RenderMode::HSC:
-      r=new impl::CartoonRenderer(trace_);
+      r=new impl::CartoonRenderer(&trace_,false);
       break;
     case RenderMode::CPK:
       r=new impl::CPKRenderer();
       break;
     case RenderMode::TUBE:
-      r=new impl::CartoonRenderer(trace_, true);
+      r=new impl::CartoonRenderer(&trace_, true);
       break;
     default:
       return 0;
@@ -144,11 +175,14 @@ impl::EntityRenderer* Entity::GetOrCreateRenderer(RenderMode::Type rm)
 void Entity::init(RenderMode::Type rm)
 {
   // TODO replace with def mat for this gfx obj type
-  SetMat(0.0,1.0,0.8,96.0);
+  SetMatAmb(Color(0,0,0));
+  SetMatDiff(Color(1,1,1));
+  SetMatSpec(Color(0.7,0.7,0.7));
+  SetMatShin(96);
 
   update_view_=true;
   render_mode_=rm;
-  trace_.SetView(this->GetView());
+  trace_.ResetView(this->GetView());
   sel_=this->GetView().CreateEmptyView();  
   impl::EntityRenderer* r=this->GetOrCreateRenderer(rm);
   if(!r) return;
@@ -160,43 +194,47 @@ void Entity::init(RenderMode::Type rm)
   Rebuild();
 }
 
-namespace {
-
-SimpleRenderOptionsPtr get_sro(impl::EntityRenderer* renderer)
-{
-  impl::SimpleRenderer* sr=dynamic_cast<SimpleRenderer*>(renderer);
-  assert(sr);  
-  return dyn_cast<SimpleRenderOptions>(sr->GetOptions());  
-}
-}
 void Entity::SetBlur(bool f)
 {
-  impl::EntityRenderer* renderer=this->GetOrCreateRenderer(RenderMode::SIMPLE);
-  if(!renderer) return;
-  SimpleRenderOptionsPtr sro=get_sro(renderer);
-  sro->SetBlurFlag(f);
+  blur_=f;
 }
 
 void Entity::BlurSnapshot()
 {
-  impl::EntityRenderer* renderer=this->GetOrCreateRenderer(RenderMode::SIMPLE);
-  if(!renderer) return;
-  impl::SimpleRenderer* sr=dynamic_cast<SimpleRenderer*>(renderer);
-  assert(sr);
-  sr->BlurSnapshot();
+  for (RendererMap::iterator i=renderer_.begin(),e=renderer_.end(); i!=e; ++i) {
+    impl::SimpleRenderer* sr = dynamic_cast<impl::SimpleRenderer*>(i->second);
+    if(sr) {
+      DoBlurSnapshot(sr->GetBondEntryList());
+    }
+    impl::LineTraceRenderer* lr = dynamic_cast<impl::LineTraceRenderer*>(i->second);
+    if(lr) {
+      DoBlurSnapshot(lr->GetBondEntryList());
+    }
+  }
 }
 
 void Entity::SetBlurFactors(float bf1,float bf2)
 {
-  impl::EntityRenderer* renderer=this->GetOrCreateRenderer(RenderMode::SIMPLE);
-  if(!renderer) return;
-  SimpleRenderOptionsPtr sro=get_sro(renderer);
-  sro->SetBlurFactors(bf1, bf2);
+  blurf1_=bf1;
+  blurf2_=bf2;
 }
 
 void Entity::Rebuild()
 {
   geom::Vec3 delta=GetTF().GetTrans()-GetTF().GetCenter();
+
+  if(update_view_) {
+    EntityView nv=this->GetView();
+    trace_.ResetView(nv);
+    for (RendererMap::iterator i=renderer_.begin(), 
+           e=renderer_.end(); i!=e; ++i) {
+      i->second->ClearViews();
+      i->second->AddView(nv);
+      i->second->UpdateViews();
+      i->second->PrepareRendering();
+    }
+  }
+
   this->ReapplyColorOps();
   FlagRebuild();
   geom::Vec3 center=this->GetCenter();
@@ -237,19 +275,19 @@ void Entity::ProcessLimits(geom::Vec3& minc, geom::Vec3& maxc,
     geom::Vec3 mmax=coord_limits.GetMax();
     geom::Vec3 t1=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmin[2]));
     geom::Vec3 t2=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmin[2]));
-    geom::Vec3 t3=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmin[2]));
-    geom::Vec3 t4=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmin[2]));
+    geom::Vec3 t3=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmin[2]));
+    geom::Vec3 t4=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmin[2]));
     geom::Vec3 t5=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmax[2]));
     geom::Vec3 t6=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmax[2]));
-    geom::Vec3 t7=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmax[2]));
-    geom::Vec3 t8=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmax[2]));
+    geom::Vec3 t7=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmax[2]));
+    geom::Vec3 t8=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmax[2]));
     minc = geom::Min(minc, geom::Min(t1, geom::Min(t2, geom::Min(t3, 
                      geom::Min(t4, geom::Min(t5, geom::Min(t6, 
                      geom::Min(t7, t8))))))));
     maxc = geom::Max(maxc, geom::Max(t1, geom::Max(t2, geom::Max(t3, 
                      geom::Max(t4, geom::Max(t5, geom::Max(t6,
                      geom::Max(t7, t8))))))));
-  } catch(Error&) {
+  } catch(Error& e) {
     // in case the object is empty...
   }
 } 
@@ -276,11 +314,11 @@ void Entity::CacheBoundingBox() const
     const impl::EntityRenderer* r=i->second;
     if (r->IsEnabled() && r->HasDataToRender()) {
       if (!has_data) {
-        coord_limits=r->GetBoundingBox();          
+        coord_limits=r->GetBoundingBox();
         has_data=true;
       } else {
         coord_limits=geom::Union(coord_limits, r->GetBoundingBox());
-      }      
+      }
     }
   }
   bbox_=coord_limits;  
@@ -296,6 +334,7 @@ bool Entity::UpdateIfNeeded() const
       renderer->PrepareRendering();
       updated=true;
     }
+    renderer->VA().SetOpacity(opacity_);
   }
   if (updated) {
     this->CacheBoundingBox();
@@ -324,66 +363,29 @@ void Entity::CustomRenderGL(RenderPass pass)
   for (RendererMap::iterator i=renderer_.begin(), 
        e=renderer_.end(); i!=e; ++i) {
     impl::EntityRenderer* r=i->second;
-    if(r->IsEnabled()){
-      switch(pass) {
-        case STANDARD_RENDER_PASS:
-        case OPAQUE_RENDER_PASS:
-          r->Render(pass);
-          break;
-        case GLOW_RENDER_PASS:
-          if (r->HasSelection()) {
-            r->Render(pass);
-          }
-          break;
+    if(r->IsEnabled()) {
+      if(pass==STANDARD_RENDER_PASS) {
+        r->Render(pass);
+        if(outline_flag_) {
+          r->VA().SetOutlineMode(outline_mode_);
+          r->Render(STANDARD_RENDER_PASS);
+          r->VA().SetOutlineMode(0);
+        }
+      } else if(pass==GLOW_RENDER_PASS) {
+        r->Render(GLOW_RENDER_PASS);
+      }
+      if(blur_) {
+        impl::SimpleRenderer* sr = dynamic_cast<impl::SimpleRenderer*>(r);
+        if(sr) {
+          DoRenderBlur(sr->GetBondEntryList(),blurf1_,blurf2_);
+        }
+        impl::LineTraceRenderer* lr = dynamic_cast<impl::LineTraceRenderer*>(r);
+        if(lr) {
+          DoRenderBlur(lr->GetBondEntryList(),blurf1_,blurf2_);
+        }
       }
     }
   }
-  geom::AlignedCuboid bbox=this->GetBoundingBox();
-  geom::Vec3 mmin=bbox.GetMin();
-  geom::Vec3 mmax=bbox.GetMax();
-#if 0  
-  glDisable(GL_LIGHTING);
-  glLineWidth(1.0);
-  glColor3f(1.0, 1.0, 1.0);
-  glBegin(GL_LINES);
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmin[2]));
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmin[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmin[2]));
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmax[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmax[2]));
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmax[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmax[2]));
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmin[2]));   
-    
-    
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmin[2]));
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmin[2]));
-    
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmin[2]));
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmax[2]));
-    
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmax[2]));
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmax[2]));
-    
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmax[2]));
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmin[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmin[2]));
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmin[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmin[2]));
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmin[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmax[1], mmax[2]));
-    glVertex3(geom::Vec3(mmax[0], mmax[1], mmax[2]));
-    
-    glVertex3(geom::Vec3(mmin[0], mmin[1], mmax[2]));
-    glVertex3(geom::Vec3(mmax[0], mmin[1], mmax[2]));
-  glEnd();
-#endif
 }
 
 void Entity::CustomRenderPov(PovState& pov)
@@ -568,6 +570,43 @@ void Entity::OptionsChanged(RenderMode::Type render_mode)
   Scene::Instance().ObjectChanged(this->GetName());
 }
 
+void Entity::SetOpacity(float f)
+{
+  opacity_=f;
+  this->UpdateIfNeeded();
+  Scene::Instance().RequestRedraw();
+}
+
+void Entity::SetOutlineWidth(float f)
+{
+  for (RendererMap::iterator it=renderer_.begin(); it!=renderer_.end(); ++it) {
+    if(it->second->IsEnabled()){
+      it->second->VA().SetOutlineWidth(f);
+    }
+  }
+  Scene::Instance().RequestRedraw();
+}
+
+void Entity::SetOutlineExpandFactor(float f)
+{
+  for (RendererMap::iterator it=renderer_.begin(); it!=renderer_.end(); ++it) {
+    if(it->second->IsEnabled()){
+      it->second->VA().SetOutlineExpandFactor(f);
+    }
+  }
+  Scene::Instance().RequestRedraw();
+}
+
+void Entity::SetOutlineExpandColor(const Color& c)
+{
+  for (RendererMap::iterator it=renderer_.begin(); it!=renderer_.end(); ++it) {
+    if(it->second->IsEnabled()){
+      it->second->VA().SetOutlineExpandColor(c);
+    }
+  }
+  Scene::Instance().RequestRedraw();
+}
+
 void Entity::OnRenderModeChange()
 {
   for (RendererMap::iterator i=renderer_.begin(), 
@@ -653,7 +692,7 @@ void Entity::SetRenderMode(RenderMode::Type mode,
      }
      renderer->UpdateViews();
   }
-  this->ReapplyColorOps();
+  this->ReapplyColorOps(); // done in rebuild?
   this->FlagRebuild();
   Scene::Instance().RenderModeChanged(GetName());
 }
@@ -677,7 +716,7 @@ void Entity::SetVisible(const mol::EntityView& view, bool visible){
     renderer->SetVisible(view, visible);
     renderer->UpdateViews();
   }
-  this->ReapplyColorOps();
+  this->ReapplyColorOps(); // done in rebuild?
   this->FlagRebuild();
 }
 
@@ -766,6 +805,16 @@ void Entity::ColorBy(const String& prop,
   this->Apply(glop);
 }
 
+void Entity::DetailColorBy(const String& prop,
+                           const Gradient& gradient,
+                           float minv,float maxv,
+                           mol::Prop::Level level)
+{
+  GradientLevelColorOp glop = GradientLevelColorOp("",prop, gradient,minv,maxv,level);
+  glop.SetMask(DETAIL_COLOR);
+  this->Apply(glop);
+}
+
 void Entity::ColorBy(const String& prop,
                      const Color& c1, const Color& c2,
                      float minv, float maxv,
@@ -794,6 +843,13 @@ mol::EntityView Entity::GetView() const
   return cached_view_;
 }
 
+void Entity::SetQuery(const mol::Query& q)
+{
+  qv_.SetQuery(q);
+  update_view_=true;
+  Rebuild();
+}
+
 void Entity::ColorBy(const String& prop,
                      const Color& c1, const Color& c2,
                      mol::Prop::Level level)
@@ -951,4 +1007,24 @@ void Entity::ReapplyColorOps()
   GfxObj::ReapplyColorOps();
 }
 
+void Entity::UpdateView() 
+{
+  update_view_=true; 
+  Rebuild();
+  UpdatePositions();
+}
+
+void Entity::SetSeqHack(bool b)
+{
+  if(b!=trace_.GetSeqHack()) {
+    trace_.SetSeqHack(b);
+    FlagRebuild();
+  }
+}
+
+bool Entity::GetSeqHack() const
+{
+  return trace_.GetSeqHack();
+}
+
 }} // ns
diff --git a/modules/gfx/src/entity.hh b/modules/gfx/src/entity.hh
index 368445df056732e6ad47777a1a36fea0b72deea8..e23860682e9f986e8f0252026fe167ef7975fc25 100644
--- a/modules/gfx/src/entity.hh
+++ b/modules/gfx/src/entity.hh
@@ -70,13 +70,15 @@ public:
   /// Rebuild() will re-apply the mol::Query to the given mol::EntityHandle
   Entity(const String& name,
          const mol::EntityHandle& eh,
-         const mol::Query& q=mol::Query());
+         const mol::Query& q=mol::Query(),
+         mol::QueryFlags f=0);
 
   /// \brief variant with explicit graphics mode instead of the default
   Entity(const String& name,
          RenderMode::Type m,
          const mol::EntityHandle& eh,
-         const mol::Query& q=mol::Query());
+         const mol::Query& q=mol::Query(),
+         mol::QueryFlags f=0);
 
   /// \brief Initialize with an object name and an explicit mol::Entity view; 
   ///    later calls to Rebuild always use this mol::Entity view
@@ -140,7 +142,16 @@ public:
 
   virtual void OptionsChanged(RenderMode::Type mode);
 
+  virtual void SetOpacity(float f);
+  virtual float GetOpacity() const {return opacity_;}
+  virtual void SetOutlineWidth(float f);
+  virtual void SetOutlineExpandFactor(float f);
+  virtual void SetOutlineExpandColor(const Color& c);
+
   /// \brief rebuild graphical object (see ctor comments)
+  /*
+    the naming here is misleading - this method WON'T be called upon FlagRebuild
+  */
   void Rebuild();
 
   /// \brief only grab updated positions, dont rebuild the whole thing
@@ -165,6 +176,7 @@ public:
   /// \brief get view
   mol::EntityView GetView() const;
 
+  void SetQuery(const mol::Query& q);
 
   // turn blur on or off
   void SetBlur(bool f);
@@ -199,6 +211,12 @@ public:
                float minv,float maxv,
                mol::Prop::Level hint=mol::Prop::UNSPECIFIED);
 
+  // temporary, should be incorporated with ColorBy
+  void DetailColorBy(const String& prop, 
+                     const Gradient& gradient,
+                     float minv,float maxv,
+                     mol::Prop::Level hint=mol::Prop::UNSPECIFIED);
+
   // convenience
   void ColorBy(const String& prop, 
                const Gradient& gradient,
@@ -257,6 +275,12 @@ public:
   void ApplyOptions(RenderMode::Type render_mode,
                           RenderOptionsPtr& render_options);
   bool HasSelection() const;
+
+  void UpdateView();
+
+  void SetSeqHack(bool b);
+  bool GetSeqHack() const;
+  
 protected:
 
   virtual void CustomPreRenderGL(bool flag);
@@ -282,6 +306,11 @@ private:
 
   typedef boost::ptr_map<RenderMode::Type, impl::EntityRenderer> RendererMap;
   mutable RendererMap renderer_;
+
+  float opacity_;
+  bool blur_;
+  float blurf1_;
+  float blurf2_;
 };
 
 
diff --git a/modules/gfx/src/gfx_node.cc b/modules/gfx/src/gfx_node.cc
index 93f900980fd15afde02631f7c26790b6c7109bf3..ea4b58e89e23aba759f4c3fc51e1a130105ad4ee 100644
--- a/modules/gfx/src/gfx_node.cc
+++ b/modules/gfx/src/gfx_node.cc
@@ -59,6 +59,17 @@ void GfxNode::DeepSwap(GfxNode& n)
   std::swap(show_,n.show_);
 }
 
+bool GfxNode::IsNameAvailable(const String& name) const
+{
+  for (GfxNodeVector::const_iterator it =node_vector_.begin();
+       it!=node_vector_.end();++it) {
+    if ((*it)->GetName()==name) {
+      return false;
+    }
+  }
+  return true;
+}
+
 void GfxNode::Apply(GfxNodeVisitor& v,GfxNodeVisitor::Stack st)
 {
   if(!v.VisitNode(this,st)) return;
@@ -101,45 +112,104 @@ void GfxNode::Rename(const String& name)
   Scene::Instance().ObjectChanged(name_);
 }
 
+bool GfxNode::IsAttachedToScene() const
+{
+  GfxNodeP root=Scene::Instance().GetRootNode();
+  if (root==this->shared_from_this()) { return true; }
+  GfxNodeP parent=this->GetParent();
+  while (parent) {
+    if (parent==root) {
+      return true;
+    }
+    parent=parent->GetParent();
+  }
+  return false;
+}
+
 void GfxNode::Add(GfxObjP obj)
 {
-  node_vector_.push_back(obj);
-  Scene::Instance().NodeAdded(obj);
+  GfxNodeP node=obj;
+  this->Add(obj);
 }
 
 void GfxNode::Remove(GfxObjP obj)
 {
-  GfxNodeVector::iterator it = find (node_vector_.begin(), node_vector_.end(), obj);
+  GfxNodeVector::iterator it = find(node_vector_.begin(), 
+                                    node_vector_.end(), obj);
   if(it!=node_vector_.end()) {
     node_vector_.erase(it);
+    obj->parent_.reset();
+    if (this->IsAttachedToScene()) {
+      Scene::Instance().NotifyObservers(bind(&SceneObserver::NodeRemoved, 
+                                             _1, obj));
+    }    
   }
+
 }
+
 using boost::bind;
+
+
 void GfxNode::RemoveAll()
 {
-  GfxNodeVector v=node_vector_;
-  node_vector_.clear();
-  for (GfxNodeVector::iterator i=v.begin(), e=v.end(); i!=e; ++i) {
-    if (GfxObjP o=dyn_cast<GfxObj>(*i)) {
-      Scene::Instance().NotifyObservers(bind(&SceneObserver::NodeRemoved, _1, o));
-    }
+  bool attached=this->IsAttachedToScene();
+  for (GfxNodeVector::iterator i=node_vector_.begin(), 
+       e=node_vector_.end(); i!=e; ++i) {
+    (*i)->parent_.reset();
+    if (!attached) 
+      continue;
+    Scene::Instance().NotifyObservers(bind(&SceneObserver::NodeRemoved, 
+                                           _1, *i));
   }
+  node_vector_.clear();
 }
 
 void GfxNode::Add(GfxNodeP node)
 {
+  if (!node) {
+    return;
+  }
+  if (!this->IsNameAvailable(node->GetName())) {
+    std::stringstream ss;
+    ss << "node '" << this->GetName() << "' has already a node with name '" 
+       << node->GetName() << "'";
+    throw Error(ss.str());
+  }
+
   node_vector_.push_back(node);
-  Scene::Instance().NodeAdded(node);    
+  if (!node->parent_.expired()) {
+    node->GetParent()->Remove(node);
+  }
+  node->parent_=this->shared_from_this();
+  if (this->IsAttachedToScene()) {
+    Scene::Instance().NodeAdded(node);
+  }
 }
 
 void GfxNode::Remove(GfxNodeP node)
 {
-  GfxNodeVector::iterator it = find (node_vector_.begin(), node_vector_.end(), node);
+  GfxNodeVector::iterator it=std::find(node_vector_.begin(), 
+                                       node_vector_.end(), node);
   if(it!=node_vector_.end()) {
+    node->parent_=GfxNodeP();
     node_vector_.erase(it);
   }
+  if (this->IsAttachedToScene()) {
+    Scene::Instance().NotifyObservers(bind(&SceneObserver::NodeRemoved, 
+                                           _1, node));
+  }
+}
+
+gfx::GfxNodeP GfxNode::GetParent() const
+{
+  if (parent_.expired()) {
+    return gfx::GfxNodeP();
+  }
+  return parent_.lock();
 }
 
+
+
 void GfxNode::Remove(const String& name)
 {
   GfxNodeVector::iterator node;
@@ -172,5 +242,11 @@ bool GfxNode::IsVisible() const
   return show_;
 }
 
+void GfxNode::ContextSwitch()
+{
+  for(GfxNodeVector::iterator it =node_vector_.begin();it!=node_vector_.end();++it) {
+    (*it)->ContextSwitch();
+  }
+}
 
 }} // ns
diff --git a/modules/gfx/src/gfx_node.hh b/modules/gfx/src/gfx_node.hh
index c91df438b41fe91a92bc910126c8534a5eb2acc6..aff9564750228dbfd9e79552dbd2db846f1b4a2a 100644
--- a/modules/gfx/src/gfx_node.hh
+++ b/modules/gfx/src/gfx_node.hh
@@ -75,7 +75,13 @@ class DLLEXPORT_OST_GFX GfxNode: public boost::enable_shared_from_this<GfxNode>
 
   // add a graphical object - leaf
   void Add(GfxObjP obj);
-
+  
+  
+  /// \brief returns true if no scene node of the given name is a child
+  ///   of this node.
+  bool IsNameAvailable(const String& name) const;
+  
+  
   // remove given graphical object
   void Remove(GfxObjP obj);
 
@@ -97,15 +103,26 @@ class DLLEXPORT_OST_GFX GfxNode: public boost::enable_shared_from_this<GfxNode>
   // return visibility state
   bool IsVisible() const;
 
-
+  virtual void ContextSwitch();
+  
+  /// \brief whether the node (or one of it's parents) has been added to the
+  ///    scene
+  bool IsAttachedToScene() const;
+  
+  
+  gfx::GfxNodeP GetParent() const;
+  
+  const GfxNodeVector& GetChildren() const { return node_vector_; }
+  GfxNodeVector& GetChildren() { return node_vector_; }
  private:
   GfxNode(const GfxNode& o);
   GfxNode& operator=(const GfxNode&);
 
 
-  String name_;
-  bool show_;
-  GfxNodeVector node_vector_;
+  String                   name_;
+  bool                     show_;
+  GfxNodeVector            node_vector_;
+  boost::weak_ptr<GfxNode> parent_;
 };
 
 }}
diff --git a/modules/gfx/src/gfx_object.cc b/modules/gfx/src/gfx_object.cc
index 5806328aea2721972c25fa8e61bda1e2670d102b..c5f7fd2ac076d139f59a064f3946d81fd27d280c 100644
--- a/modules/gfx/src/gfx_object.cc
+++ b/modules/gfx/src/gfx_object.cc
@@ -41,7 +41,7 @@
 namespace ost { namespace gfx {
 
 GfxObj::GfxObj(const String& name):
-  GfxNode(name),
+  GfxObjBase(name),
   va_(),
   render_mode_(RenderMode::SIMPLE),
   debug_flags_(0),
@@ -49,9 +49,6 @@ GfxObj::GfxObj(const String& name):
   rebuild_(true),
   refresh_(false),
   line_width_(2.0),
-  sphere_detail_(4),
-  arc_detail_(4),
-  spline_detail_(8),
   poly_mode_(2),
   aalines_flag_(false),
   line_halo_(0.0),
@@ -60,64 +57,22 @@ GfxObj::GfxObj(const String& name):
   mat_update_(true),
   opacity_(1.0),
   smoothf_(0.0),
-  omode_(0),
+  outline_flag_(false),
+  outline_mode_(1),
   c_ops_(),
   labels_(),
   use_occlusion_(false)
 {
 }
 
-GfxObj::~GfxObj()
-{}
-
-GfxObj::GfxObj(const GfxObj& o):
-  GfxNode("") // to make the compiler happy
+GfxObj::GfxObj(const GfxObj&):
+  GfxObjBase("") // to make the compiler happy
 {}
 
 GfxObj& GfxObj::operator=(const GfxObj&) {return *this;}
 
-void GfxObj::Apply(GfxNodeVisitor& v, GfxNodeVisitor::Stack st)
-{
-  v.VisitObject(this,st);
-}
-
-int GfxObj::GetType() const
-{
-  return 1;
-}
-
-geom::AlignedCuboid GfxObj::GetBoundingBox() const
-{
-  return geom::AlignedCuboid(geom::Vec3(),geom::Vec3());
-}
-
-void GfxObj::ProcessLimits(geom::Vec3& minc, geom::Vec3& maxc, 
-                           const mol::Transform& tf) const
-{
-  try {
-    geom::AlignedCuboid coord_limits=this->GetBoundingBox();
-    // update min/max by transforming all 8 corners of the bounding box and 
-    // comparing it against the current min/max
-    geom::Vec3 mmin=coord_limits.GetMin();
-    geom::Vec3 mmax=coord_limits.GetMax();
-    geom::Vec3 t1=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmin[2]));
-    geom::Vec3 t2=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmin[2]));
-    geom::Vec3 t3=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmin[2]));
-    geom::Vec3 t4=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmin[2]));
-    geom::Vec3 t5=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmax[2]));
-    geom::Vec3 t6=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmax[2]));
-    geom::Vec3 t7=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmax[2]));
-    geom::Vec3 t8=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmax[2]));
-    minc = geom::Min(minc, geom::Min(t1, geom::Min(t2, geom::Min(t3, 
-                     geom::Min(t4, geom::Min(t5, geom::Min(t6, 
-                     geom::Min(t7, t8))))))));
-    maxc = geom::Max(maxc, geom::Max(t1, geom::Max(t2, geom::Max(t3, 
-                     geom::Max(t4, geom::Max(t5, geom::Max(t6,
-                     geom::Max(t7, t8))))))));
-  } catch(Error&) {
-    // in case the object is empty...
-  }
-}
+////////////////////////////////////////
+// the GfxNode interface
 
 GfxNodeP GfxObj::Copy() const
 {
@@ -130,9 +85,6 @@ void GfxObj::DeepSwap(GfxObj& go)
   std::swap(transform_,go.transform_);
   std::swap(rebuild_,go.rebuild_);
   std::swap(refresh_,go.refresh_);
-  std::swap(sphere_detail_,go.sphere_detail_);
-  std::swap(arc_detail_,go.arc_detail_);
-  std::swap(spline_detail_,go.spline_detail_);
   std::swap(poly_mode_,go.poly_mode_);
   std::swap(aalines_flag_,go.aalines_flag_);
   std::swap(line_halo_,go.line_halo_);
@@ -141,95 +93,155 @@ void GfxObj::DeepSwap(GfxObj& go)
   std::swap(mat_update_,go.mat_update_);
   std::swap(opacity_,go.opacity_);
   std::swap(smoothf_,go.smoothf_);
+  std::swap(outline_flag_,go.outline_flag_);
+  std::swap(outline_mode_,go.outline_mode_);
+  std::swap(c_ops_,go.c_ops_);
+  std::swap(labels_,go.labels_);
+  std::swap(use_occlusion_,go.use_occlusion_);
 }
 
-void GfxObj::CustomRenderGL(RenderPass pass) {}
-void GfxObj::CustomPreRenderGL(bool flag) {}
+void GfxObj::RenderGL(RenderPass pass)
+{
+  LOG_TRACE("object " << GetName() << ": RenderGL()");
 
-void GfxObj::CustomRenderPov(PovState& pov) {}
+  if(pass==0) {
+    if(mat_update_) {
+      LOG_TRACE("updating material display list");
+      if(mat_dlist_==0) {
+        mat_dlist_=glGenLists(1);
+      }
+      glNewList(mat_dlist_,GL_COMPILE);
+      mat_.RenderGL();
+      glEndList();
+      mat_update_=false;
+    }
+    
+    if(rebuild_ || refresh_) {
+      PreRenderGL(rebuild_);
+      rebuild_=false;
+      refresh_=false;
+      // there really needs to be a central place
+      // where the va attributes are re-applied
+      va_.SetOpacity(opacity_);
+    }
+  }
+  if(IsVisible()) {
+    LOG_TRACE("applying local transformation");
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrix(transform_.GetTransposedMatrix().Data());
+    if(Scene::Instance().InOffscreenMode()) {
+      LOG_TRACE("applying material");
+      mat_.RenderGL();
+    } else {
+      LOG_TRACE("applying material display list");
+      glCallList(mat_dlist_);
+    }
+    LOG_TRACE("calling custom render gl pass " << pass);
 
-void GfxObj::RefreshVA(IndexedVertexArray& va)
-{
-  va.SetLineWidth(GetLineWidth());
-  va.SetPolyMode(GetPolyMode());
-  va.SetAALines(GetAALines());
-  va.SetLineHalo(GetLineHalo());
-  va.DrawNormals(debug_flags_&0x1);
-  va.SetPolyMode(debug_flags_&0x2 ? 1 : 2);
-  va.UseAmbient(use_occlusion_);
-  va.FlagRefresh();
+    /*
+      only STANDARD_RENDER_PASS and GLOW_RENDER_PASS are
+      passed down to the custom rendering routines
+    */
+   
+    if(pass==DEPTH_RENDER_PASS) {
+      render_depth_only();
+    } else if(pass==TRANSPARENT_RENDER_PASS) {
+      if(GetOpacity()<1.0) {
+        render_depth_only();
+        CustomRenderGL(STANDARD_RENDER_PASS);
+        if(outline_flag_) {
+          va_.SetOutlineMode(outline_mode_);
+          CustomRenderGL(pass);
+          va_.SetOutlineMode(0);
+        }
+      }
+    } else if(pass==STANDARD_RENDER_PASS) {
+      if(GetOpacity()>=1.0) {
+        CustomRenderGL(STANDARD_RENDER_PASS);
+        if(outline_flag_) {
+          va_.SetOutlineMode(outline_mode_);
+          CustomRenderGL(pass);
+          va_.SetOutlineMode(0);
+        }
+      }
+    } else if(pass==GLOW_RENDER_PASS) {
+      CustomRenderGL(GLOW_RENDER_PASS);
+    } else if(pass==OVERLAY_RENDER_PASS) {
+      LOG_TRACE("drawing labels");
+      render_labels();
+    }
+
+    glPopMatrix();    
+  }
 }
 
-void GfxObj::OnInput(const InputEvent& e) 
-{
-  geom::Mat3 rot=gfx::Scene::Instance().GetTransform().GetRot();
-  geom::Vec3 cam_trans=gfx::Scene::Instance().GetTransform().GetTrans();  
-  float x=e.GetDelta()*M_PI/180.0;
-  bool transformed=false;
-  if (e.GetCommand()==INPUT_COMMAND_ROTX) {
-    transformed=true;
-    transform_.SetRot(AxisRotation(geom::Vec3(1,0,0)*rot,x)*transform_.GetRot());
-  } else if(e.GetCommand()==INPUT_COMMAND_ROTY) {
-    transformed=true;
-    transform_.SetRot(AxisRotation(geom::Vec3(0,1,0)*rot,x)*transform_.GetRot());
-  } else if(e.GetCommand()==INPUT_COMMAND_ROTZ) {
-    transformed=true;
-    transform_.SetRot(AxisRotation(geom::Vec3(0,0,1)*rot,x)*transform_.GetRot());
-  } else if(e.GetCommand()==INPUT_COMMAND_TRANSX ||
-            e.GetCommand()==INPUT_COMMAND_TRANSY) {
- 
-    double mm[]={1,0,0,0,
-                 0,1,0,0,
-                 0,0,1,0,
-                 transform_.GetTrans()[0]-cam_trans[0],
-                 transform_.GetTrans()[1]-cam_trans[1],
-                 transform_.GetTrans()[2]-cam_trans[2], 1};
-    double pm[16];
-    glGetDoublev(GL_PROJECTION_MATRIX,pm);
-    GLint vp[4];
-    glGetIntegerv(GL_VIEWPORT,vp);
-    double wx,wy,wz;
-    gluProject(0.0,0.0,0.0,mm,pm,vp,&wx,&wy,&wz);
-    double ox,oy,oz;
-    gluUnProject(wx+1.0,wy+1.0,wz,mm,pm,vp,&ox,&oy,&oz);
 
-    float fx=ox;
-    float fy=oy;   
-    geom::Vec3 trans=transform_.GetTrans();
-    transformed=true;    
-    if (e.GetCommand()==INPUT_COMMAND_TRANSX) {
-      trans+=geom::Vec3(-fx*e.GetDelta(), 0.0, 0.0)*rot;
-    } else {
-      trans+=geom::Vec3(0.0, -fy*e.GetDelta(), 0.0)*rot;
+void GfxObj::RenderPov(PovState& pov)
+{
+  if(IsVisible()) {
+    pov.start_obj(GetName(),1.0,1.0,1.0);
+    // apply local transformation
+    // using transform_
+    if(rebuild_ || refresh_) {
+      PreRenderGL(true);
     }
-    transform_.SetTrans(trans);
-  }
-  if (transformed) {
-    GfxObjP obj=dyn_cast<GfxObj>(this->shared_from_this());
-    Scene::Instance().NodeTransformed(obj);
+    CustomRenderPov(pov);
+    pov.end_obj();
   }
 }
 
-const mol::Transform& GfxObj::GetTF() const
+void GfxObj::Apply(GfxNodeVisitor& v, GfxNodeVisitor::Stack st)
 {
-  return transform_;
+  v.VisitObject(this,st);
 }
 
+int GfxObj::GetType() const
+{
+  return 1;
+}
 
-void GfxObj::SetTF(const mol::Transform& tf)
+////////////////////////////////////////
+// now for the GfxObjBase interface
+void GfxObj::SetMatAmb(const Color& c)
 {
-  transform_=tf;
+  mat_.SetAmb(c);
+  mat_update_=true;
+  Scene::Instance().RequestRedraw();
 }
 
-geom::Vec3 GfxObj::GetCenter() const 
+void GfxObj::SetMatDiff(const Color& c)
 {
-  return this->GetBoundingBox().GetCenter();
+  mat_.SetDiff(c);
+  mat_update_=true;
+  Scene::Instance().RequestRedraw();
 }
 
-bool GfxObj::OnSelect(const geom::Line3& l, geom::Vec3& result, 
-                      float zlim, bool pick_flag)
+void GfxObj::SetMatSpec(const Color& c)
 {
-  return false;
+  mat_.SetSpec(c);
+  mat_update_=true;
+  Scene::Instance().RequestRedraw();
+}
+
+void GfxObj::SetMatShin(float s)
+{
+  mat_.SetShin(s);
+  mat_update_=true;
+  Scene::Instance().RequestRedraw();
+}
+
+void GfxObj::SetMatEmm(const Color& c)
+{
+  mat_.SetEmm(c);
+  mat_update_=true;
+  Scene::Instance().RequestRedraw();
+}
+
+void GfxObj::ContextSwitch()
+{
+  FlagRebuild();
+  GfxNode::ContextSwitch();
 }
 
 void GfxObj::SetRenderMode(RenderMode::Type m)
@@ -245,197 +257,240 @@ RenderMode::Type GfxObj::GetRenderMode() const
   return render_mode_;
 }
 
-void GfxObj::FlagRebuild()
+geom::Vec3 GfxObj::GetCenter() const 
 {
-  rebuild_=true;
-  Scene::Instance().RequestRedraw();
+  return this->GetBoundingBox().GetCenter();
 }
 
-void GfxObj::FlagRefresh()
+void GfxObj::SetLineWidth(float w)
 {
-  refresh_=true;
-  Scene::Instance().RequestRedraw();
+  va_.SetLineWidth(w);
+  line_width_=std::max(float(0.01),w);
+  FlagRefresh();
+  Scene::Instance().RenderModeChanged(GetName());
 }
 
-void GfxObj::SetNormalSmoothFactor(float smoothf)
+void GfxObj::SetPolyMode(unsigned int m)
 {
-  smoothf_=smoothf;
-  FlagRebuild();
+  if(m==poly_mode_) return;
+  poly_mode_=std::min((unsigned int)2,m);
+  va_.SetPolyMode(poly_mode_);
+  FlagRefresh();
 }
 
-float GfxObj::GetNormalSmoothFactor() const
+void GfxObj::SetAALines(bool f)
 {
-  return smoothf_;
+  if(f==aalines_flag_) return;
+  va_.SetAALines(f);
+  aalines_flag_=f;
+  FlagRefresh();
 }
 
-void GfxObj::OnRenderModeChange()
+void GfxObj::SetLineHalo(float f)
 {
-  Scene::Instance().ObjectChanged(GetName());
-  Scene::Instance().RenderModeChanged(GetName());
+  va_.SetLineHalo(f);
+  line_halo_=f;
+  FlagRefresh();
 }
 
-void GfxObj::SetLineWidth(float w)
+void GfxObj::SetOutline(bool f)
 {
-  line_width_=std::max(float(0.01),w);
+  outline_flag_=f;
   FlagRefresh();
-  Scene::Instance().RenderModeChanged(GetName());
+  if(f) {
+    outline_mode_=std::min(3,std::max(1,outline_mode_));
+  }
+  Scene::Instance().RequestRedraw();
 }
 
-float GfxObj::GetLineWidth() const
+void GfxObj::SetOutlineMode(int m)
 {
-  return line_width_;
+  outline_mode_=m;
+  if(outline_flag_) {
+    FlagRefresh();
+    Scene::Instance().RequestRedraw();
+  }
 }
 
-void GfxObj::SetSphereDetail(unsigned int d)
+void GfxObj::SetOutlineWidth(float f)
 {
-  if(d==sphere_detail_) return;
-  sphere_detail_=d;
-  FlagRebuild();
+  va_.SetOutlineWidth(f);
+  Scene::Instance().RequestRedraw();
 }
 
-unsigned int GfxObj::GetSphereDetail() const
+void GfxObj::SetOutlineExpandFactor(float f)
 {
-  return sphere_detail_;
+  va_.SetOutlineExpandFactor(f);
+  Scene::Instance().RequestRedraw();
 }
 
-void GfxObj::SetArcDetail(unsigned int d)
+void GfxObj::SetOutlineExpandColor(const Color& c)
 {
-  if(d==arc_detail_) return;
-  arc_detail_=d;
-  FlagRebuild();
+  va_.SetOutlineExpandColor(c);
+  Scene::Instance().RequestRedraw();
 }
 
-unsigned int GfxObj::GetArcDetail() const
+void GfxObj::SetOpacity(float o)
 {
-  return arc_detail_;
+  opacity_=o;
+  va_.SetOpacity(opacity_);
+  FlagRefresh();
+  Scene::Instance().RequestRedraw();
 }
 
-void GfxObj::SetSplineDetail(unsigned int d)
+void GfxObj::ColorBy(const mol::EntityView& ev, 
+                      const String& prop,
+                      const Gradient& g, float minv, float maxv)
 {
-  if(d==spline_detail_) return;
-  spline_detail_=d;
-  FlagRebuild();
+  LOG_VERBOSE("ColorBy not implemented for this gfx object");
 }
 
-unsigned int GfxObj::GetSplineDetail() const
+#if OST_IMG_ENABLED
+void GfxObj::ColorBy(const img::MapHandle& mh,
+                      const String& prop,
+                      const Gradient& g, float minv, float maxv)
 {
-  return spline_detail_;
+  LOG_VERBOSE("ColorBy not implemented for this gfx object");
 }
+#endif
 
-void GfxObj::SetPolyMode(unsigned int m)
+//////////////////////////////////////////////////
+// and now for the rest of the GfxObj interface
+
+geom::AlignedCuboid GfxObj::GetBoundingBox() const
 {
-  if(m==poly_mode_) return;
-  poly_mode_=std::min((unsigned int)2,m);
-  FlagRefresh();
+  return geom::AlignedCuboid(geom::Vec3(),geom::Vec3());
 }
 
-unsigned int GfxObj::GetPolyMode() const
+void GfxObj::ProcessLimits(geom::Vec3& minc, geom::Vec3& maxc, 
+                           const mol::Transform& tf) const
 {
-  return poly_mode_;
+  try {
+    geom::AlignedCuboid coord_limits=this->GetBoundingBox();
+    // update min/max by transforming all 8 corners of the bounding box and 
+    // comparing it against the current min/max
+    geom::Vec3 mmin=coord_limits.GetMin();
+    geom::Vec3 mmax=coord_limits.GetMax();
+    geom::Vec3 t1=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmin[2]));
+    geom::Vec3 t2=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmin[2]));
+    geom::Vec3 t3=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmin[2]));
+    geom::Vec3 t4=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmin[2]));
+    geom::Vec3 t5=tf.Apply(geom::Vec3(mmin[0], mmin[1], mmax[2]));
+    geom::Vec3 t6=tf.Apply(geom::Vec3(mmin[0], mmax[1], mmax[2]));
+    geom::Vec3 t7=tf.Apply(geom::Vec3(mmax[0], mmax[1], mmax[2]));
+    geom::Vec3 t8=tf.Apply(geom::Vec3(mmax[0], mmin[1], mmax[2]));
+    minc = geom::Min(minc, geom::Min(t1, geom::Min(t2, geom::Min(t3, 
+                     geom::Min(t4, geom::Min(t5, geom::Min(t6, 
+                     geom::Min(t7, t8))))))));
+    maxc = geom::Max(maxc, geom::Max(t1, geom::Max(t2, geom::Max(t3, 
+                     geom::Max(t4, geom::Max(t5, geom::Max(t6,
+                     geom::Max(t7, t8))))))));
+  } catch(Error& e) {
+    // in case the object is empty...
+  }
 }
 
-void GfxObj::SetAALines(bool f)
-{
-  if(f==aalines_flag_) return;
-  aalines_flag_=f;
-  FlagRefresh();
+
+void GfxObj::CustomRenderGL(RenderPass pass) {}
+
+void GfxObj::CustomPreRenderGL(bool flag) {}
+
+void GfxObj::CustomRenderPov(PovState& pov) {}
+
+bool GfxObj::OnSelect(const geom::Line3& l, geom::Vec3& result, 
+                      float zlim, bool pick_flag)
+{
+  return false;
+}
+
+void GfxObj::OnInput(const InputEvent& e) 
+{
+  geom::Mat3 rot=gfx::Scene::Instance().GetTransform().GetRot();
+  geom::Vec3 cam_trans=gfx::Scene::Instance().GetTransform().GetTrans();  
+  float x=e.GetDelta()*M_PI/180.0;
+  bool transformed=false;
+  if (e.GetCommand()==INPUT_COMMAND_ROTX) {
+    transformed=true;
+    transform_.SetRot(AxisRotation(geom::Vec3(1,0,0)*rot,x)*transform_.GetRot());
+  } else if(e.GetCommand()==INPUT_COMMAND_ROTY) {
+    transformed=true;
+    transform_.SetRot(AxisRotation(geom::Vec3(0,1,0)*rot,x)*transform_.GetRot());
+  } else if(e.GetCommand()==INPUT_COMMAND_ROTZ) {
+    transformed=true;
+    transform_.SetRot(AxisRotation(geom::Vec3(0,0,1)*rot,x)*transform_.GetRot());
+  } else if(e.GetCommand()==INPUT_COMMAND_TRANSX ||
+            e.GetCommand()==INPUT_COMMAND_TRANSY) {
+ 
+    double mm[]={1,0,0,0,
+                 0,1,0,0,
+                 0,0,1,0,
+                 transform_.GetTrans()[0]-cam_trans[0],
+                 transform_.GetTrans()[1]-cam_trans[1],
+                 transform_.GetTrans()[2]-cam_trans[2], 1};
+    double pm[16];
+    glGetDoublev(GL_PROJECTION_MATRIX,pm);
+    GLint vp[4];
+    glGetIntegerv(GL_VIEWPORT,vp);
+    double wx,wy,wz;
+    gluProject(0.0,0.0,0.0,mm,pm,vp,&wx,&wy,&wz);
+    double ox,oy,oz;
+    gluUnProject(wx+1.0,wy+1.0,wz,mm,pm,vp,&ox,&oy,&oz);
+
+    float fx=ox;
+    float fy=oy;   
+    geom::Vec3 trans=transform_.GetTrans();
+    transformed=true;    
+    if (e.GetCommand()==INPUT_COMMAND_TRANSX) {
+      trans+=geom::Vec3(-fx*e.GetDelta(), 0.0, 0.0)*rot;
+    } else {
+      trans+=geom::Vec3(0.0, -fy*e.GetDelta(), 0.0)*rot;
+    }
+    transform_.SetTrans(trans);
+  }
+  if (transformed) {
+    GfxObjP obj=dyn_cast<GfxObj>(this->shared_from_this());
+    Scene::Instance().NodeTransformed(obj);
+  }
 }
 
-bool GfxObj::GetAALines() const
+const mol::Transform& GfxObj::GetTF() const
 {
-  return aalines_flag_;
+  return transform_;
 }
 
-void GfxObj::SetLineHalo(float f)
-{
-  line_halo_=f;
-  FlagRefresh();
-}
 
-float GfxObj::GetLineHalo() const
+void GfxObj::SetTF(const mol::Transform& tf)
 {
-  return line_halo_;
+  transform_=tf;
 }
 
-void GfxObj::SetOutlineMode(int m)
+void GfxObj::FlagRebuild()
 {
-  omode_=m;
-  FlagRefresh();
+  rebuild_=true;
+  Scene::Instance().RequestRedraw();
 }
 
-void GfxObj::SetOutlineExpandFactor(float f)
+void GfxObj::FlagRefresh()
 {
-  va_.SetOutlineExpandFactor(f);
+  refresh_=true;
+  Scene::Instance().RequestRedraw();
 }
 
-void GfxObj::SetOutlineExpandColor(const Color& c)
+void GfxObj::SetNormalSmoothFactor(float smoothf)
 {
-  va_.SetOutlineExpandColor(c);
+  smoothf_=smoothf;
+  FlagRebuild();
 }
 
-void GfxObj::RenderGL(RenderPass pass)
+float GfxObj::GetNormalSmoothFactor() const
 {
-  LOG_TRACE("object " << GetName() << ": RenderGL()");
-
-  if(pass==0) {
-    if(mat_update_) {
-      LOG_TRACE("updating material display list");
-      if(mat_dlist_==0) {
-        mat_dlist_=glGenLists(1);
-      }
-      glNewList(mat_dlist_,GL_COMPILE);
-      mat_.RenderGL();
-      glEndList();
-      mat_update_=false;
-    }
-    
-    if(rebuild_ || refresh_) {
-      PreRenderGL(rebuild_);
-      rebuild_=false;
-      refresh_=false;
-    }
-  }
-  if(IsVisible()) {
-    LOG_TRACE("applying local transformation");
-    glMatrixMode(GL_MODELVIEW);
-    glPushMatrix();
-    glMultMatrix(transform_.GetTransposedMatrix().Data());
-    if(Scene::Instance().InOffscreenMode()) {
-      LOG_TRACE("applying material");
-      mat_.RenderGL();
-    } else {
-      LOG_TRACE("applying material display list");
-      glCallList(mat_dlist_);
-    }
-    LOG_TRACE("calling custom render gl pass " << pass);
-
-    CustomRenderGL(pass);
-
-    if(pass==0 && omode_>0) {
-      va_.SetOutlineMode(omode_);
-      CustomRenderGL(pass);
-      va_.SetOutlineMode(0);
-    }
-
-    if(pass==1) {
-      LOG_TRACE("drawing labels");
-      render_labels();
-    }
-
-    glPopMatrix();    
-  }
+  return smoothf_;
 }
 
-
-void GfxObj::RenderPov(PovState& pov)
+void GfxObj::OnRenderModeChange()
 {
-  if(IsVisible()) {
-    pov.start_obj(GetName(),1.0,1.0,1.0);
-    // apply local transformation
-    // using transform_
-    CustomRenderPov(pov);
-    pov.end_obj();
-  }
+  Scene::Instance().ObjectChanged(GetName());
+  Scene::Instance().RenderModeChanged(GetName());
 }
 
 void GfxObj::PreRenderGL(bool f)
@@ -446,6 +501,7 @@ void GfxObj::PreRenderGL(bool f)
 
 void GfxObj::Clear()
 {
+  va_.Clear();
 }
 
 Color GfxObj::Ele2Color(const String& ele)
@@ -487,90 +543,6 @@ void GfxObj::ClearLabels()
   labels_.clear();
 }
 
-void GfxObj::SetMatAmb(const Color& c)
-{
-  mat_.SetAmb(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatAmb(float c)
-{
-  mat_.SetAmb(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatDiff(const Color& c)
-{
-  mat_.SetDiff(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatDiff(float c)
-{
-  mat_.SetDiff(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatSpec(const Color& c)
-{
-  mat_.SetSpec(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatSpec(float c)
-{
-  mat_.SetSpec(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatShin(float s)
-{
-  mat_.SetShin(s);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatEmm(const Color& c)
-{
-  mat_.SetEmm(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMatEmm(float c)
-{
-  mat_.SetEmm(c);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMat(const Color& amb, const Color& diff, const Color& spec, float shin)
-{
-  SetMatAmb(amb);
-  SetMatDiff(diff);
-  SetMatSpec(spec);
-  SetMatShin(shin);
-  SetMatEmm(0.0);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::SetMat(float amb, float diff, float spec, float shin)
-{
-  SetMatAmb(amb);
-  SetMatDiff(diff);
-  SetMatSpec(spec);
-  SetMatShin(shin);
-  SetMatEmm(0.0);
-  mat_update_=true;
-  Scene::Instance().RequestRedraw();
-}
 
 Material GfxObj::GetMaterial() const
 {
@@ -594,141 +566,12 @@ void GfxObj::GLCleanup()
 void GfxObj::OnGLCleanup()
 {}
 
-void GfxObj::SetOpacity(float o)
-{
-  opacity_=o;
-  FlagRebuild();
-}
-
-float GfxObj::GetOpacity() const
-{
-  return opacity_;
-}
-
 void GfxObj::SmoothVertices(float smoothf)
 {
   va_.SmoothVertices(smoothf);
   FlagRefresh();
 }
 
-void GfxObj::AmbientOcclusion(bool f)
-{
-  use_occlusion_=f;
-  va_.UseAmbient(f);
-  Scene::Instance().RequestRedraw();
-}
-
-void GfxObj::ColorBy(const mol::EntityView& ev, 
-                      const String& prop,
-                      const Gradient& g, float minv, float maxv)
-{ 
-  // FIXME: Throw exception here...
-  LOG_ERROR("ColorBy not implemented for this gfx object");
-}
-
-
-void GfxObj::ColorBy(const mol::EntityView& ev, 
-                      const String& prop,
-                      const Color& c1, const Color& c2, float minv, float maxv)
-{
-  Gradient g;
-  g.SetColorAt(0.0,c1);
-  g.SetColorAt(1.0,c2);
-  this->ColorBy(ev,prop,g,minv,maxv);
-}
-
-#if OST_IMG_ENABLED
-void GfxObj::ColorBy(const img::MapHandle& mh,
-                      const String& prop,
-                      const Gradient& g, float minv, float maxv)
-{
-  // FIXME: Throw exception here
-  LOG_ERROR("ColorBy not implemented for this gfx object");
-}
-
-void GfxObj::ColorBy(const img::MapHandle& mh,
-                      const String& prop,
-                      const Color& c1, const Color& c2, float minv, float maxv)
-{
-  Gradient g;
-  g.SetColorAt(0.0,c1);
-  g.SetColorAt(1.0,c2);
-  this->ColorBy(mh,prop,g,minv,maxv);
-}
-
-void GfxObj::ColorBy(const img::MapHandle& mh,
-                      const String& prop,
-                      const Gradient& g)
-{
-  ost::img::alg::Stat stat;
-  mh.Apply(stat);
-  float min = static_cast<float>(stat.GetMinimum());
-  float max = static_cast<float>(stat.GetMaximum());
-  std::pair<float,float> minmax = std::make_pair(min,max);
-  this->ColorBy(mh,prop,g,minmax.first, minmax.second);
-}
-
-void GfxObj::ColorBy(const img::MapHandle& mh,
-                      const String& prop,
-                      const Color& c1, const Color& c2)
-{
-  ost::img::alg::Stat stat;
-  mh.Apply(stat);
-  float min = static_cast<float>(stat.GetMinimum());
-  float max = static_cast<float>(stat.GetMaximum());
-  std::pair<float,float> minmax = std::make_pair(min,max);
-  this->ColorBy(mh,prop,c1,c2,minmax.first, minmax.second);
-}
-
-#endif //OST_IMG_ENABLED
-
-void GfxObj::ColorBy(const mol::EntityHandle& eh, 
-                      const String& prop,
-                      const Gradient& g, float minv, float maxv)
-{
-  this->ColorBy(eh.CreateFullView(),prop,g,minv,maxv);
-}
-    
-void GfxObj::ColorBy(const mol::EntityHandle& eh, 
-                      const String& prop,
-                      const Color& c1, const Color& c2, float minv, float maxv)
-{
-  Gradient g;
-  g.SetColorAt(0.0,c1);
-  g.SetColorAt(1.0,c2);
-  this->ColorBy(eh,prop,g,minv,maxv);
-}
-
-void GfxObj::ColorBy(const mol::EntityView& ev, 
-                      const String& prop,
-                      const Gradient& g)
-{
-  std::pair<float,float> minmax = ev.GetMinMax(prop);
-  this->ColorBy(ev,prop,g,minmax.first, minmax.second);
-}
-    
-void GfxObj::ColorBy(const mol::EntityView& ev, 
-                      const String& prop,
-                      const Color& c1, const Color& c2)
-{
-  std::pair<float,float> minmax = ev.GetMinMax(prop);
-  this->ColorBy(ev,prop,c1,c2,minmax.first, minmax.second);
-}
-
-void GfxObj::ColorBy(const mol::EntityHandle& eh, 
-                      const String& prop,
-                      const Gradient& g)
-{
-  this->ColorBy(eh.CreateFullView(),prop,g);
-}
-
-void GfxObj::ColorBy(const mol::EntityHandle& eh, 
-                      const String& prop,
-                      const Color& c1, const Color& c2)
-{
-  this->ColorBy(eh.CreateFullView(),prop,c1,c2);
-}
-
 namespace {
 
 float normalize(float v, float min_v, float max_v)
@@ -750,7 +593,7 @@ void GfxObj::ReapplyColorOps(){
     GfxObjP o=dyn_cast<GfxObj>(shared_from_this());
     for(boost::ptr_vector<gfx::ColorOp>::iterator it=c_ops_.begin();
       it!=c_ops_.end();++it) {
-	    it->ApplyTo(o);
+      it->ApplyTo(o);
     }
   }
 }
@@ -763,4 +606,32 @@ void GfxObj::CleanColorOps(){
   c_ops_.release();
 }
 
+void GfxObj::Debug(unsigned int flags)
+{
+  debug_flags_=flags;
+  va_.DrawNormals(flags & 0x1);
+}
+
+void GfxObj::render_depth_only()
+{
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
+  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+  glDisable(GL_LIGHTING);
+  glDisable(GL_COLOR_MATERIAL);
+  glDisable(GL_BLEND);
+  glDisable(GL_FOG);
+  glShadeModel(GL_FLAT);
+  glDisable(GL_LINE_SMOOTH);
+  glDisable(GL_POINT_SMOOTH);
+  glDisable(GL_POLYGON_SMOOTH);
+  glDisable(GL_DITHER);
+  glDisable(GL_NORMALIZE);
+  glEnable(GL_DEPTH_TEST);
+  CustomRenderGL(STANDARD_RENDER_PASS);
+  CustomRenderGL(TRANSPARENT_RENDER_PASS);
+  glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);      
+  glPopAttrib();
+}
+
+
 }} // ns
diff --git a/modules/gfx/src/gfx_object.hh b/modules/gfx/src/gfx_object.hh
index 5a4bd4877dec27e434a1cdce1fe7ade9abf58adc..42f9fbbfecca4636f2742edb573d468b5f0cf1d9 100644
--- a/modules/gfx/src/gfx_object.hh
+++ b/modules/gfx/src/gfx_object.hh
@@ -33,58 +33,66 @@
 #include <ost/config.hh>
 #include <ost/gfx/module_config.hh>
 
-#include <ost/gfx/color_ops/color_op.hh>
-
-#include <ost/geom/geom.hh>
-#include <ost/mol/entity_handle.hh>
-#include <ost/mol/entity_view.hh>
 #include <ost/mol/transform.hh>
 
-
-#if OST_IMG_ENABLED
-#  include <ost/img/map.hh>
-#endif
-
 #include "gfx_object_fw.hh"
-#include "gfx_node.hh"
+#include "gfx_object_base.hh"
 #include "gfx_prim.hh"
 #include "vertex_array.hh"
 #include "input.hh"
-#include "render_mode.hh"
-#include "material.hh"
-#include "gradient.hh"
-
 
 namespace ost { namespace gfx {
 
 class Scene; // fw decl
 
-/// \brief Base class for all graphical rendering objects
-class DLLEXPORT_OST_GFX GfxObj: public GfxNode
+/// \brief main class for all graphic objects
+class DLLEXPORT_OST_GFX GfxObj: public GfxObjBase
 {
-
 public:
   GfxObj(const String& name);
-  virtual ~GfxObj();
 
+  // gfx node interface
   virtual GfxNodeP Copy() const;
-
+  virtual void DeepSwap(GfxObj& go);
+  virtual void RenderGL(RenderPass pass);
+  virtual void RenderPov(PovState& pov);
   virtual void Apply(GfxNodeVisitor& v,GfxNodeVisitor::Stack st);
-
   virtual int GetType() const;
+  //
+
+  // gfx obj base interface
+  virtual void SetMatAmb(const Color& c);
+  virtual void SetMatDiff(const Color& c);
+  virtual void SetMatSpec(const Color& c);
+  virtual void SetMatShin(float s);
+  virtual void SetMatEmm(const Color& c);
+  virtual void ContextSwitch();
+  virtual void SetRenderMode(RenderMode::Type m);
+  virtual RenderMode::Type GetRenderMode() const;
+  virtual geom::Vec3 GetCenter() const;
+  virtual void SetLineWidth(float w);
+  virtual void SetPolyMode(unsigned int m);
+  virtual void SetAALines(bool f);
+  virtual void SetLineHalo(float f);
+  virtual void SetOutline(bool f);
+  virtual void SetOutlineMode(int m);
+  virtual void SetOutlineWidth(float f);
+  virtual void SetOutlineExpandFactor(float f);
+  virtual void SetOutlineExpandColor(const Color& c);
+  virtual void SetOpacity(float f);
+  virtual float GetOpacity() const {return opacity_;}
+  virtual void ColorBy(const mol::EntityView& ev, 
+                       const String& prop,
+                       const Gradient& g, float minv, float maxv);
+#if OST_IMG_ENABLED
+  virtual void ColorBy(const img::MapHandle& mh,
+                       const String& prop,
+                       const Gradient& g,float minv, float maxv);
+#endif
 
-  virtual void RenderGL(RenderPass pass);
-
-  virtual void RenderPov(PovState& pov);
+  // end of gfx obj base interface
 
-  void Clear();
-  
-  /// \brief get transform
-  const mol::Transform& GetTF() const;
-  /// \brief set transform
-  void SetTF(const mol::Transform& tf);
-  
-  virtual geom::Vec3 GetCenter() const;
+  // new gfx obj virtual interface starts here
 
   /// \brief returns the left-bottom-front and the right-top-back corner
   /// that encompasses all graphical elements in this object
@@ -98,8 +106,14 @@ public:
   virtual void ProcessLimits(geom::Vec3& minc, geom::Vec3& maxc, 
                              const mol::Transform& tf) const;
 
+  // implemented in derived classes for the actual GL rendering
+  /*
+    note: only STANDARD_RENDER_PASS and GLOW_RENDER_PASS need to 
+    be implemented, the rest is taken care of by GfxObj::RenderGL
+  */
   virtual void CustomRenderGL(RenderPass pass);
 
+  // implemented in derived classes for the actual POVray export
   virtual void CustomRenderPov(PovState& pov);
 
   // handle pick (select) event
@@ -116,43 +130,20 @@ public:
 
   // input event entry point
   virtual void OnInput(const InputEvent& e);
-  
-  virtual void DeepSwap(GfxObj& go);
-  
+
+  // informs derived class that render mode has changes
   virtual void OnRenderModeChange();
   virtual void OnGLCleanup();
+  //
 
-  /// \brief change render mode
-  virtual void SetRenderMode(RenderMode::Type m);
-  /// \brief current render mode
-  RenderMode::Type GetRenderMode() const;
-
-  /// \brief set line width
-  void SetLineWidth(float w);
+  /// \brief removes all graphical elements
+  void Clear();
+  
+  /// \brief get transform
+  const mol::Transform& GetTF() const;
+  /// \brief set transform
+  void SetTF(const mol::Transform& tf);
   
-  /// \brief get line width 
-  float GetLineWidth() const;
-
-  void SetSphereDetail(unsigned int d);
-  unsigned int GetSphereDetail() const;
-
-  // subdivions per 90deg
-  void SetArcDetail(unsigned int d);
-  unsigned int GetArcDetail() const;
-
-  void SetSplineDetail(unsigned int d);
-  unsigned int GetSplineDetail() const;
-
-  void SetPolyMode(unsigned int m);
-  unsigned int GetPolyMode() const;
-
-  // sophisticated line anti-aliasing, requires shader
-  void SetAALines(bool f);
-  bool GetAALines() const;
-
-  void SetLineHalo(float f);
-  float GetLineHalo() const;
-
   // add a label at the given position
   void AddLabel(const String& s, const geom::Vec3& pos, const Color& col, float psize);
   // convenience method
@@ -161,112 +152,37 @@ public:
   void AddLabel(const String& s, const geom::Vec3& pos, float psize);
   // convenience method
   void AddLabel(const String& s, const geom::Vec3& pos);
-
   // remove all labels
   void ClearLabels();
 
-  void SetMatAmb(const Color& c);
-  void SetMatAmb(float c);
-  void SetMatDiff(const Color& c);
-  void SetMatDiff(float c);
-  void SetMatSpec(const Color& c);
-  void SetMatSpec(float c);
-  void SetMatShin(float s);
-  void SetMatEmm(const Color& c);
-  void SetMatEmm(float c);
-  void SetMat(const Color& amb, const Color& diff, const Color& spec, float shin);
-  void SetMat(float amb, float diff, float spec, float shin);
-
-  void SetOpacity(float o);
-  float GetOpacity() const;
-
-  static Color Ele2Color(const String& ele);
-
   void FlagRebuild();
   void FlagRefresh();
 
+  bool GetAALines() const {return aalines_flag_;}
+  float GetLineWidth() const {return line_width_;}
+  float GetLineHalo() const {return line_halo_;}
+
   void SetNormalSmoothFactor(float smoothf);
   float GetNormalSmoothFactor() const;
 
   Material GetMaterial() const;
   void SetMaterial(const Material& m);
 
-  void SetOutlineMode(int m);
-  void SetOutlineExpandFactor(float f);
-  void SetOutlineExpandColor(const Color& c);
-
   // experimental, don't use
   void SmoothVertices(float smoothf);
-  // experimental, don't use
-  void AmbientOcclusion(bool f);
  
   void GLCleanup();
 
-  /// \brief color each component based on the gradient-mapped property of 
-  ///    the given entity
-  virtual void ColorBy(const mol::EntityView& ev, 
-                       const String& prop,
-                       const Gradient& g, float minv, float maxv);
-    
-  /// \brief convenience method
-  void ColorBy(const mol::EntityView& ev, 
-               const String& prop,
-               const Color& c1, const Color& c2, float minv, float maxv);
-
-  /// \brief convenience method
-  void ColorBy(const mol::EntityHandle& eh, 
-               const String& prop,
-               const Gradient& g, float minv, float maxv);
-  /// \brief convenience method
-  void ColorBy(const mol::EntityHandle& eh, 
-               const String& prop,
-               const Color& c1, const Color& c2, float minv, float maxv);
-  // convenience method
-  void ColorBy(const mol::EntityView& ev, 
-               const String& prop,
-               const Gradient& g);
-  // convenience method
-  void ColorBy(const mol::EntityView& ev, 
-               const String& prop,
-               const Color& c1, const Color& c2);
-  // convenience method
-  void ColorBy(const mol::EntityHandle& ev, 
-               const String& prop,
-               const Gradient& g);
-  // convenience method
-  void ColorBy(const mol::EntityHandle& ev, 
-               const String& prop,
-               const Color& c1, const Color& c2);
-#if OST_IMG_ENABLED
-  // convenience method
-  void ColorBy(const img::MapHandle& mh,
-               const String& prop,
-               const Gradient& g);
-  // convenience method
-  void ColorBy(const img::MapHandle& mh,
-               const String& prop,
-               const Color& c1, const Color& c2);
-  // dito for maps
-  virtual void ColorBy(const img::MapHandle& mh,
-                       const String& prop,
-                       const Gradient& g,float minv, float maxv);
-  // convenience method
-  void ColorBy(const img::MapHandle& mh,
-               const String& prop,
-               const Color& c1, const Color& c2, float minv, float maxv);  
-#endif
+  // this really should not be here
+  static Color Ele2Color(const String& ele);
 
-  void Debug(unsigned int flags) {debug_flags_=flags; RefreshVA();}
+  void Debug(unsigned int flags);
 
  protected:
   
   void PreRenderGL(bool flag);
   virtual void CustomPreRenderGL(bool flag);
 
-  void RefreshVA(IndexedVertexArray& va);
-
-  virtual void RefreshVA() {RefreshVA(va_);}
-  
  private:
   GfxObj(const GfxObj& o);
   GfxObj& operator=(const GfxObj&);
@@ -275,19 +191,17 @@ public:
   void AppendColorOp(gfx::ColorOp* op);
   void CleanColorOps();
   void ReapplyColorOps();
+  void render_labels() const;
+  void render_depth_only();
 
   IndexedVertexArray va_;
   RenderMode::Type render_mode_;
   unsigned int debug_flags_;
  
- private: 
   mol::Transform transform_;
   bool rebuild_;
   bool refresh_;
   float line_width_;
-  unsigned int sphere_detail_;
-  unsigned int arc_detail_;
-  unsigned int spline_detail_;
   unsigned int poly_mode_;
   bool aalines_flag_;
   float line_halo_;
@@ -298,12 +212,12 @@ public:
 
   float opacity_;
   float smoothf_;
-  int omode_;
+  bool outline_flag_;
+  int outline_mode_;
 
   boost::ptr_vector<gfx::ColorOp> c_ops_;
 
   TextPrimList labels_;
-  void render_labels() const;
 
   bool use_occlusion_;
 };
diff --git a/modules/gfx/src/gfx_object_base.hh b/modules/gfx/src/gfx_object_base.hh
index bcbf4613f8e1c7216988845e1f93ccf72e229685..24b331a4134e87479dc2e5411affdb2f1477ddf3 100644
--- a/modules/gfx/src/gfx_object_base.hh
+++ b/modules/gfx/src/gfx_object_base.hh
@@ -84,33 +84,26 @@ class DLLEXPORT_OST_GFX GfxObjBase: public GfxNode
   virtual void SetPolyMode(unsigned int m) = 0;
 
   /// \brief turn on sophisticated line anti-aliasing, requires shader
-  virtual void AALines(bool f) = 0;
+  virtual void SetAALines(bool f) = 0;
 
   /// \brief turn on line halo of given strength
   virtual void SetLineHalo(float f) = 0;
 
   /// \brief turn outline rendering on or off
-  virtual void Outline(bool f) = 0;
-
+  virtual void SetOutline(bool f) = 0;
   /// \brief set outline mode
   virtual void SetOutlineMode(int m) = 0;
-  /// \brief set outline tweak factor
+  /// \brief set outline width (modes 1 + 2)
+  virtual void SetOutlineWidth(float f) = 0;
+  /// \brief set outline tweak factor (mode 3)
   virtual void SetOutlineExpandFactor(float f) = 0;
-  /// \brief set outline color
+  /// \brief set outline color (mode 3)
   virtual void SetOutlineExpandColor(const Color& c) = 0;
 
-  /// \brief ambient occlusion rendering
-  /// results are cached, but may be very slow on first call 
-  virtual void AmbientOcclusion(bool f) = 0;
-  
-  /// \brief blending weight of local color to fragment color
-  virtual void SetAmbientLocalWeight(float w) = 0;
-  
-  /// \brief blending weight of occlusion factor
-  virtual void SetAmbientOcclusionWeight(float w) = 0;
-
   /// \brief set opacity (1 = no transparency)
   virtual void SetOpacity(float f) = 0;
+  /// \brief returns a value smaller than 1.0 if transparency is used in this object
+  virtual float GetOpacity() const = 0;
 
   /// \brief color each component based on the gradient-mapped property of 
   ///    the given entity
diff --git a/modules/gfx/src/gfx_object_fw.hh b/modules/gfx/src/gfx_object_fw.hh
index 7e54f3599b25dfc33776f4ffda0c2120258e33d0..56c9d1906b9cbef4ef7ad2d67f3627d183f60739 100644
--- a/modules/gfx/src/gfx_object_fw.hh
+++ b/modules/gfx/src/gfx_object_fw.hh
@@ -27,8 +27,9 @@
 
 namespace ost { namespace gfx {
 
+class GfxObjBase;
+typedef boost::shared_ptr<GfxObjBase> GfxObjBaseP;
 class GfxObj;
-
 typedef boost::shared_ptr<GfxObj> GfxObjP;
 
 }} // ns
diff --git a/modules/gfx/src/gfx_prim.hh b/modules/gfx/src/gfx_prim.hh
index 1ec2bc25a55c382af86d52087a56b5c900e069d5..aead546538e44fe83dab8c948b65b976cf2eb6d7 100644
--- a/modules/gfx/src/gfx_prim.hh
+++ b/modules/gfx/src/gfx_prim.hh
@@ -48,13 +48,19 @@ typedef std::vector<SpherePrim> SpherePrimList;
 
 struct CylinderPrim {
   CylinderPrim():
-    start(),end(),radius(1.0),color(),length(1.0),rotmat(),rotmat_t()
+    start(),end(),radius(1.0),color1(),color2(),length(1.0),rotmat(),rotmat_t()
   {
     calc_rotmat();
   }
 
   CylinderPrim(const geom::Vec3& st, const geom::Vec3& en, float rad, const Color& col):
-    start(st),end(en),radius(rad),color(col),length(geom::Length(end-start)),rotmat(),rotmat_t() 
+    start(st),end(en),radius(rad),color1(col),color2(col),length(geom::Length(end-start)),rotmat(),rotmat_t() 
+  {
+    calc_rotmat();
+  }
+
+  CylinderPrim(const geom::Vec3& st, const geom::Vec3& en, float rad, const Color& col1, const Color& col2):
+    start(st),end(en),radius(rad),color1(col1),color2(col2),length(geom::Length(end-start)),rotmat(),rotmat_t() 
   {
     calc_rotmat();
   }
@@ -63,7 +69,7 @@ struct CylinderPrim {
 
   geom::Vec3 start,end;
   float radius;
-  Color color;
+  Color color1, color2;
   float length;
   geom::Mat3 rotmat;
   geom::Mat3 rotmat_t;
diff --git a/modules/gfx/src/gfx_test_object.cc b/modules/gfx/src/gfx_test_object.cc
index 6e6cb3ae4c3d3f4dc78d05dc2bbe23facada2820..69ae91439ec62f8fa00041a8a48b5eab58f14a1a 100644
--- a/modules/gfx/src/gfx_test_object.cc
+++ b/modules/gfx/src/gfx_test_object.cc
@@ -26,6 +26,7 @@
 #include <boost/filesystem/fstream.hpp>
 
 #include <ost/platform.hh>
+#include "texture.hh"
 #include "glext_include.hh"
 #include "gfx_test_object.hh"
 #include "scene.hh"
@@ -59,8 +60,9 @@ GfxTestObj::GfxTestObj():
   String ost_root=GetSharedDataPath();
   bf::path ost_root_dir(ost_root);
   bf::path tex_file(ost_root_dir / "textures/test_texture.png");
-  Bitmap bm = BitmapImport(tex_file.string(),".png");
-  if(!bm.data) {
+
+  Texture tex(BitmapImport(tex_file.string(),".png"));
+  if(!tex.IsValid()) {
     LOG_ERROR("error loading " << tex_file.string());
   } else {
     LOG_DEBUG("importing tex with id " << tex_id);
@@ -70,11 +72,7 @@ GfxTestObj::GfxTestObj():
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    if(bm.channels==3) {
-      glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,bm.width,bm.height,0,GL_RGB,GL_UNSIGNED_BYTE,bm.data.get());
-    } else if(bm.channels==4) {
-      glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,bm.width,bm.height,0,GL_RGBA,GL_UNSIGNED_BYTE,bm.data.get());
-    }
+    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,tex.width(),tex.height(),tex.border(),tex.format(),tex.type(),tex.data());
   }
 }
 
diff --git a/modules/gfx/src/gfx_test_object.hh b/modules/gfx/src/gfx_test_object.hh
index b233f2812d397352cefe4d197d9375b97b6d2d19..95eeeb2cc6e32a292b58ce457a8027124c4379d5 100644
--- a/modules/gfx/src/gfx_test_object.hh
+++ b/modules/gfx/src/gfx_test_object.hh
@@ -26,7 +26,7 @@
 */
 
 #include "gfx_object.hh"
-#include "gl_include.hh"
+#include "glext_include.hh"
 
 namespace ost { namespace gfx {
 
diff --git a/modules/gfx/src/gl_helper.hh b/modules/gfx/src/gl_helper.hh
index 1c955212cd7e228ad9ef54939b82e1ab9a6d6b8d..4243d242253074b4b3ece5fcfccc8e555ab2a2da 100644
--- a/modules/gfx/src/gl_helper.hh
+++ b/modules/gfx/src/gl_helper.hh
@@ -36,20 +36,25 @@ Author: Juergen Haas
 #include <ost/geom/vec3.hh>
 
 #include "glext_include.hh"
-#include "gl_include.hh"
+
+#include <ost/log.hh>
+
+inline void check_gl_error()
+{
+  GLenum error_code;
+  if((error_code=glGetError())!=GL_NO_ERROR) {
+    LOG_VERBOSE("GL error: " << gluErrorString(error_code));
+  }
+}
 
 inline void glVertex3v(double* v){
   glVertex3dv(v);
 }
 
-
-
 inline void glVertex3v(const double* v){
   glVertex3dv(v);
 }
 
-
-
 inline void glVertex3v(float* v){
   glVertex3fv(v);
 }
@@ -106,5 +111,16 @@ inline void glLoadMatrix(double* arr) {
   glLoadMatrixd(arr);
 }
 
+#if OST_SHADER_SUPPORT_ENABLED
+
+inline void glLoadTransposeMatrix(float* arr) {
+  glLoadTransposeMatrixf(arr);
+}
+
+inline void glLoadTransposeMatrix(double* arr) {
+  glLoadTransposeMatrixd(arr);
+}
+
+#endif
 
 #endif
diff --git a/modules/gfx/src/glext_include.hh b/modules/gfx/src/glext_include.hh
index b297153e2cf7a62ae864e7ef2b4e6ec69c7b95ef..308103f42bfde82b7653f3a4d7252a26a8df3266 100644
--- a/modules/gfx/src/glext_include.hh
+++ b/modules/gfx/src/glext_include.hh
@@ -35,11 +35,21 @@
 #  if !defined(__APPLE__)
 #   include <ost/gfx/GL/glew.h>
 #  endif
-#  if defined(_WIN32)
+#  if defined(_MSC_VER)
 #    include <ost/gfx/GL/wglew.h>
 #  endif
 #endif
 
 #include <ost/gfx/gl_include.hh>
 
+#if defined(__APPLE__)
+// On all MacOS X version we support, OpenGL 2.0 is available, so it's safe to 
+// hardcode the value here...
+//same for windows vista and above, XP only has 1.1
+#define OST_GL_VERSION_2_0 1
+#else
+#ifdef GLEW_VERSION_2_0
+#define OST_GL_VERSION_2_0 1
+#endif
+#endif
 #endif
diff --git a/modules/gfx/src/glwin_base.hh b/modules/gfx/src/glwin_base.hh
index 69ce405252c271a4ba32f57467a5e0b0df484e58..1be6d819f78fb15eba23eb82c440f59d8654ae09 100644
--- a/modules/gfx/src/glwin_base.hh
+++ b/modules/gfx/src/glwin_base.hh
@@ -33,11 +33,15 @@ class DLLEXPORT_OST_GFX GLWinBase {
 public:
   virtual ~GLWinBase() {}
 
+  virtual void MakeActive() {}
+
   virtual void DoRefresh() = 0;
 
   virtual void StatusMessage(const String& m) = 0;
 
-  virtual void SetStereo(bool s) = 0;
+  virtual bool HasStereo() const = 0;
+
+  virtual bool HasMultisample() const = 0;
 };
 
 }}
diff --git a/modules/gfx/src/impl/backbone_trace.cc b/modules/gfx/src/impl/backbone_trace.cc
index c61fd23a5dc991025cad4c1de9a0400662e1d898..095da24f228df77728e87c3447a0357d2d033022 100644
--- a/modules/gfx/src/impl/backbone_trace.cc
+++ b/modules/gfx/src/impl/backbone_trace.cc
@@ -27,19 +27,39 @@
  
 namespace ost { namespace gfx { namespace impl {
 
+namespace {
+
+bool in_sequence(const mol::ResidueHandle& r1, const mol::ResidueHandle& r2, bool seqhack)
+{
+  if(!r1.IsValid() || !r2.IsValid()) return false;
+  if(r1.GetChain()!=r2.GetChain()) return false;
+  mol::ResNum n1 = r1.GetNumber();
+  mol::ResNum n2 = r2.GetNumber();
+  if(n2.GetInsCode()!='\0') {
+    if(n1.NextInsertionCode()==n2) return true;
+  }
+  if(mol::InSequence(r1,r2)) return true;
+  if(seqhack && n1.GetNum()+1==n2.GetNum()) return true;
+  return false;
+}
+
+} // anon ns
+
 class TraceBuilder: public mol::EntityVisitor {
 public:
-  TraceBuilder(BackboneTrace* bb_trace):
+  TraceBuilder(BackboneTrace* bb_trace, bool sh):
     backbone_trace_(bb_trace),
     last_residue_(),
-    list_()
+    list_(),
+    id_counter_(0),
+    seq_hack_(sh)
   {}
 
   virtual bool VisitChain(const mol::ChainHandle& chain)
   {
     if(last_chain_ && chain!=last_chain_) {
       if(!list_.empty()) {
-        backbone_trace_->AddNodeList(list_);
+        backbone_trace_->AddNodeEntryList(list_);
         list_.clear();
       }
       last_chain_=chain;
@@ -49,9 +69,11 @@ public:
 
   virtual bool VisitResidue(const mol::ResidueHandle& res)
   {
-    if(!mol::InSequence(last_residue_,res)) {
+    // check in-sequence
+    bool in_seq=in_sequence(last_residue_,res,seq_hack_);
+    if(!in_seq) {
       if(!list_.empty()) {
-        backbone_trace_->AddNodeList(list_);
+        backbone_trace_->AddNodeEntryList(list_);
         list_.clear();
       }
     }
@@ -60,11 +82,11 @@ public:
     if (ca) {
       NodeEntry entry={ca, GfxObj::Ele2Color(ca.GetElement()),
                        GfxObj::Ele2Color(ca.GetElement()),
-                       geom::Vec3(0.0,0.0,0.0), // this will be set by the gfx trace obj
+                       geom::Vec3(), // this will be set by the gfx trace obj
                        res.GetCentralNormal(),
                        1.0,
-                       geom::Vec3(),geom::Vec3(),geom::Vec3(),
-                       false};
+                       geom::Vec3(),geom::Vec3(),geom::Vec3(), // for later use in NA rendering
+                       false,id_counter_++};
       list_.push_back(entry);
     }
 
@@ -76,7 +98,7 @@ public:
   virtual void OnExit()
   {
     if (!list_.empty()) {
-      backbone_trace_->AddNodeList(list_);
+      backbone_trace_->AddNodeEntryList(list_);
       list_.clear();
     }
   }
@@ -85,97 +107,28 @@ private:
   mol::ResidueHandle last_residue_;
   mol::ChainHandle   last_chain_;
   NodeEntryList      list_;
+  int                id_counter_;
+  bool               seq_hack_;
 };
 
-BackboneTrace::BackboneTrace(const mol::EntityView& ent)
-{
-  view_=ent;
-  TraceBuilder trace(this);
-  if (view_) {
-    view_.Apply(trace);
-  }
-}
+BackboneTrace::BackboneTrace():
+  view_(),
+  node_list_list_(),
+  seq_hack_(false)
+{}
 
-BackboneTrace::BackboneTrace()
+BackboneTrace::BackboneTrace(const mol::EntityView& ent):
+  view_(ent),
+  node_list_list_(),
+  seq_hack_(false)
 {
-  
+  Rebuild();
 }
 
-void BackboneTrace::SetView(const mol::EntityView& ent)
+void BackboneTrace::ResetView(const mol::EntityView& ent)
 {
   view_=ent;
-  if (view_) {
-    node_list_list_.clear();
-    TraceBuilder trace(this);    
-    view_.Apply(trace);
-  }
-}
-
-void BackboneTrace::AddNodeList(const NodeEntryList& l)
-{
-  if(l.size()>=3) {
-    node_list_list_.push_back(l);
-    // assign direction and normal vectors for each entry
-    // they are composed of the i-1 -> i and i->i+1 directions
-    //
-    // this same algorithm is used in the spline generation, so
-    // perhaps all of this here is not necessary ?!
-    //
-    NodeEntry* e0=&node_list_list_.back()[0];
-    NodeEntry* e1=&node_list_list_.back()[1];
-    NodeEntry* e2=&node_list_list_.back()[2];
-    geom::Vec3 p0 = e0->atom.GetPos();
-    geom::Vec3 p1 = e1->atom.GetPos();
-    geom::Vec3 p2 = e2->atom.GetPos();
-
-    e0->direction=geom::Normalize(p1-p0);
-    // e0->normal is set afterwards to normal of second one
-    // backup residue normal
-    e0->v1 = e0->normal;
-
-    //reference normal to avoid twisting
-    geom::Vec3 nref=geom::Normalize(geom::Cross(p0-p1,p2-p1));
-
-    // start loop with the second
-    unsigned int i=1;
-    for(;i<node_list_list_.back().size()-1;++i) {
-      geom::Vec3 p10 = p0-p1;
-      geom::Vec3 p12 = p2-p1;
-      if(p10==-p12 || p10==p12) p12+=geom::Vec3(0.001,0.001,0.001);
-      e1->v1=e1->normal;
-      // twist avoidance
-      if(geom::Dot(e0->v1,e1->v1)<0.0) {
-        e1->v1=-e1->v1;
-      }
-      e1->normal=geom::Normalize(geom::Cross(p10,p12));
-      float omega=0.5*acos(geom::Dot(geom::Normalize(p10),geom::Normalize(p12)));
-      geom::Vec3 orth=geom::AxisRotation(e1->normal, -omega)*p12;
-      e1->direction=geom::Normalize(geom::Cross(e1->normal,orth));
-
-      // align normals to avoid twisting
-      //if(geom::Dot(e1->normal,nref)<0.0) e1->normal=-e1->normal;
-      //nref=e1->normal;
-      // skip over shift for the last iteration
-      if(i==node_list_list_.back().size()-2) break;
-      // shift to i+1 for next iteration
-      e0=&node_list_list_.back()[i];
-      e1=&node_list_list_.back()[i+1];
-      e2=&node_list_list_.back()[i+2];
-      p0 = e0->atom.GetPos();
-      p1 = e1->atom.GetPos();
-      p2 = e2->atom.GetPos();
-    }
-    // finish remaining values
-    // i is at size-2 due to break statement above
-    node_list_list_.back()[0].normal=node_list_list_.back()[1].normal;
-    node_list_list_.back()[i+1].direction=geom::Normalize(p2-p1);
-    node_list_list_.back()[i+1].v1=node_list_list_.back()[i+1].normal;
-    if (geom::Dot(node_list_list_.back()[i].v1,
-                  node_list_list_.back()[i+1].v1)<0.0) {
-      node_list_list_.back()[i+1].v1=-node_list_list_.back()[i+1].v1;
-    }
-    node_list_list_.back()[i+1].normal=node_list_list_.back()[i].normal;
-  }
+  Rebuild();
 }
 
 int BackboneTrace::GetListCount() const
@@ -195,97 +148,109 @@ NodeEntryList& BackboneTrace::GetList(int index)
 
 void BackboneTrace::Rebuild()
 {
-  TraceBuilder trace(this);
-  view_.Apply(trace);  
-}
-
-NodeListSubset::NodeListSubset(BackboneTrace& trace, int index):
-  trace_(trace), list_index_(index), at_start_(0), at_end_(0)
-{
-}
-
-TraceSubset::TraceSubset(BackboneTrace& trace, 
-                         const mol::EntityView& view, int n):
-  trace_(trace), overshoot_(n)
-{
-  this->Update(view);
+  if (view_) {
+    node_list_list_.clear();
+    TraceBuilder trace(this,seq_hack_);    
+    view_.Apply(trace);
+  }
 }
 
-TraceSubset::TraceSubset(BackboneTrace& trace, int n):
-  trace_(trace), overshoot_(n)
+void BackboneTrace::OnUpdatedPositions()
 {
-  
+  for(NodeEntryListList::iterator nitnit=node_list_list_.begin();nitnit!=node_list_list_.end();++nitnit) {
+    NodeEntryList& nlist=*nitnit;
+    for(NodeEntryList::iterator nit=nlist.begin();nit!=nlist.end();++nit) {
+      nit->normal=nit->atom.GetResidue().GetCentralNormal();
+    }
+    PrepList(nlist);
+  }
 }
 
-
-void TraceSubset::NodeListEnd(NodeListSubset& nl, int c, int s)
+void BackboneTrace::AddNodeEntryList(const NodeEntryList& l)
 {
-  if (nl.GetSize()>0) {
-    int n=std::min(s-(nl.indices_.back()+1), overshoot_);
-    nl.at_end_=n;    
-    while (n>0) {
-      nl.indices_.push_back(nl.indices_.back()+1);
-      --n;
-    }
+  if(l.size()>=3) {
+    node_list_list_.push_back(l);
+    PrepList(node_list_list_.back());
   }
 }
 
-void TraceSubset::NodeListStart(NodeListSubset& nl, int c)
+void BackboneTrace::PrepList(NodeEntryList& nelist)
 {
-  if (nl.GetSize()==0 && c>0) {
-    for (int i=std::max(0,c-overshoot_); i<c; ++i) {
-      nl.indices_.push_back(i);
+  // orthogonalize the residue normals with
+  // twist detection; important for later
+  // spline generation
+  if(nelist.size()<3) return;
+  NodeEntry* e0=&nelist[0];
+  NodeEntry* e1=&nelist[1];
+  NodeEntry* e2=&nelist[2];
+  geom::Vec3 p0 = e0->atom.GetPos();
+  geom::Vec3 p1 = e1->atom.GetPos();
+  geom::Vec3 p2 = e2->atom.GetPos();
+
+  geom::Vec3 dir=geom::Normalize(p1-p0);
+  e0->direction=geom::Normalize(p1-p0);
+  geom::Vec3 orth=geom::Normalize(geom::Cross(e0->direction,e0->normal));
+  geom::Vec3 norm=geom::Normalize(geom::Cross(orth,dir));
+  e0->normal=norm;
+  // start loop with the second residue
+  unsigned int i=1;
+  for(;i<nelist.size()-1;++i) {
+    geom::Vec3 p10=p0-p1;
+    geom::Vec3 p12=p2-p1;
+    dir=geom::Normalize(p2-p0);
+    e1->direction = dir;
+    orth=geom::Normalize(geom::Cross(dir,e1->normal));
+    norm=geom::Normalize(geom::Cross(orth,dir));
+    // twist check
+    if(geom::Dot(geom::Cross(e0->normal,dir),geom::Cross(norm,dir))<0.0) {
+      norm=-norm;
     }
-    nl.at_start_=nl.indices_.size();
+    e1->normal=norm;
+    // skip over shift for the last iteration
+    if(i==nelist.size()-2) break;
+    // shift to i+1 for next iteration
+    e0=&nelist[i];
+    e1=&nelist[i+1];
+    e2=&nelist[i+2];
+    p0 = e0->atom.GetPos();
+    p1 = e1->atom.GetPos();
+    p2 = e2->atom.GetPos();
+  }
+  dir=geom::Normalize(p2-p1);
+  e2->direction=dir;
+  orth=geom::Normalize(geom::Cross(dir,e2->normal));
+  norm=geom::Normalize(geom::Cross(orth,dir));
+  if(geom::Dot(geom::Cross(e1->normal,dir),geom::Cross(norm,dir))<0.0) {
+    norm=-norm;
   }
+  e2->normal=norm;
 }
 
-
-void TraceSubset::Update(const mol::EntityView& view)
+BackboneTrace BackboneTrace::CreateSubset(const mol::EntityView& subview)
 {
-
-  lists_.clear();
-  if (!view.IsValid()) {
-    return;
-  }
-  for (int i=0; i<trace_.GetListCount(); ++i) {
-    const NodeEntryList& l=trace_.GetList(i); 
-    int c=0;
-    NodeEntryList::const_iterator j=l.begin(),e=l.end();  
-    NodeListSubset curr(trace_, i);
-    while (j!=e) {  
-      while (j!=e && view.FindAtom(j->atom)) {
-        if (curr.indices_.empty()) {
-          this->NodeListStart(curr, c);
-        }
-        curr.indices_.push_back(c);
-        ++j; ++c;
-      }
-      if (curr.GetSize()) {
-        this->NodeListEnd(curr, curr.indices_.back(), l.size());
-        lists_.push_back(curr);
-        curr=NodeListSubset(trace_, i);
-      } else {
-        ++c; ++j;        
+  BackboneTrace nrvo;
+  nrvo.view_=subview;
+  nrvo.node_list_list_.clear();
+  for(NodeEntryListList::const_iterator nitnit=node_list_list_.begin();nitnit!=node_list_list_.end();++nitnit) {
+    NodeEntryList new_nlist;
+    const NodeEntryList& nlist=*nitnit;
+    for(NodeEntryList::const_iterator nit=nlist.begin();nit!=nlist.end();++nit) {
+      if(subview.FindAtom(nit->atom).IsValid()) {
+        new_nlist.push_back(*nit);
       }
     }
+    if(!new_nlist.empty()) {
+      nrvo.node_list_list_.push_back(new_nlist);
+    }
   }
+  return nrvo;
 }
 
-NodeListSubset& NodeListSubset::operator=(const NodeListSubset& rhs)
+void BackboneTrace::SetSeqHack(bool f)
 {
-  trace_=rhs.trace_;
-  list_index_=rhs.list_index_;
-  indices_=rhs.indices_;
-  return *this;
+  seq_hack_=f;
+  Rebuild();
 }
 
-TraceSubset& TraceSubset::operator=(const TraceSubset& rhs)
-{
-  trace_=rhs.trace_;
-  lists_=rhs.lists_;
-  overshoot_=rhs.overshoot_;
-  return *this;
-}
+}}} // ns
 
-}}}
diff --git a/modules/gfx/src/impl/backbone_trace.hh b/modules/gfx/src/impl/backbone_trace.hh
index c6663f12c336b9b87470bf8cce4c3540ef711d4e..cb2e27e2bc0022279e473020cf59d93ed986e6b8 100644
--- a/modules/gfx/src/impl/backbone_trace.hh
+++ b/modules/gfx/src/impl/backbone_trace.hh
@@ -40,97 +40,51 @@ class BackboneTraceBuilder;
 class DLLEXPORT_OST_GFX BackboneTrace {
 public:
 
-  BackboneTrace(const mol::EntityView& ent);
+  // empty trace
   BackboneTrace();
-  
+
+  // initialize with a view, and build
+  BackboneTrace(const mol::EntityView& ent);
+
+  // number of node-lists
   int GetListCount() const;
-  
+
+  // grab a list
   const NodeEntryList& GetList(int index) const;
+  // grab a list
   NodeEntryList& GetList(int index);
+
+  // reset the view and rebuild
+  void ResetView(const mol::EntityView& ent);
+
+  // used internally - adds a finished nodelist
+  void AddNodeEntryList(const NodeEntryList& entries);  
   
-  void SetView(const mol::EntityView& ent);
-  
-  // used internally
-  void AddNodeList(const NodeEntryList& entries);  
-  
+  // used internally - calculates some derived values for a nodelist
+  static void PrepList(NodeEntryList& nelist);
+
+  // re-creates internal nodelist-list based on view
+  /*
+    seq_hack will apply an additional hackish N/N+1 rnum check
+    to determine if two consecutive residues are connected
+  */
   void Rebuild();
+
+  // entity has new positions
+  void OnUpdatedPositions();
   
+  // extract portions of this backbone trace for a subview
+  // this is faster then re-generating a trace
+  BackboneTrace CreateSubset(const mol::EntityView& subview);
+
+  void SetSeqHack(bool f);
+  bool GetSeqHack() const {return seq_hack_;}
+
 private:  
   mol::EntityView      view_;
   NodeEntryListList    node_list_list_;
-};
+  bool seq_hack_;
 
-/// \internal
-/// \brief a subset of a node list
-class DLLEXPORT_OST_GFX NodeListSubset {
-public:
-  friend class TraceSubset;
-  
-  NodeListSubset(BackboneTrace& trace, int index);
-  
-  int GetSize() const 
-  {
-     return indices_.size();
-  }
-  int AtStart() const 
-  { 
-    return at_start_;
-  }
-  
-  int AtEnd() const 
-  { 
-    return at_end_;
-  }  
-  const NodeEntry& operator [](int index) const 
-  {
-    assert(index>=0 && index<static_cast<int>(indices_.size()));    
-    return trace_.GetList(list_index_)[indices_[index]];
-  }
-  NodeEntry& operator [](int index)
-  {
-    assert(index>=0 && index<static_cast<int>(indices_.size()));    
-    return trace_.GetList(list_index_)[indices_[index]];
-  }  
-  NodeListSubset& operator=(const NodeListSubset& rhs);    
-private:
-  BackboneTrace&    trace_;
-  int               list_index_;
-protected:
-  std::vector<int>  indices_;
-  int               at_start_;
-  int               at_end_;
-};
-
-/// \brief a subset of the trace
-class DLLEXPORT_OST_GFX TraceSubset {
-public:
-  TraceSubset(BackboneTrace& trace, const mol::EntityView& view, int n);
-  TraceSubset(BackboneTrace& trace, int n);
-  
-  const NodeListSubset& operator[](int index) const
-  {
-    return lists_[index];
-  }
-  
-  NodeListSubset& operator[](int index)
-  {
-    return lists_[index];
-  }
-  
-  int GetSize() const
-  {
-    return lists_.size();
-  }
-  void SetOvershoot(int n) { overshoot_=n; }
-  int GetOvershoot() const { return overshoot_; }
-  TraceSubset& operator=(const TraceSubset& rhs);  
-  void Update(const mol::EntityView& view);
-private:
-  void NodeListStart(NodeListSubset& nl, int c);
-  void NodeListEnd(NodeListSubset& nl, int c, int s);
-  BackboneTrace& trace_;
-  std::vector<NodeListSubset> lists_;
-  int overshoot_;
 };
 
 }}}
diff --git a/modules/gfx/src/impl/calc_ambient.cc b/modules/gfx/src/impl/calc_ambient.cc
deleted file mode 100644
index 82d9ecd6235547fb0526f40535dad4a838267514..0000000000000000000000000000000000000000
--- a/modules/gfx/src/impl/calc_ambient.cc
+++ /dev/null
@@ -1,360 +0,0 @@
-//------------------------------------------------------------------------------
-// This file is part of the OpenStructure project <www.openstructure.org>
-//
-// Copyright (C) 2008-2010 by the OpenStructure authors
-//
-// This library 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 3.0 of the License, or (at your option)
-// any later version.
-// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-//------------------------------------------------------------------------------
-
-/*
-  Author: Ansgar Philippsen
-*/
-
-#include <map>
-#include <vector>
-#include <limits>
-
-#include <ost/geom/geom.hh>
-#include <ost/gfx/vertex_array.hh>
-
-#include "calc_ambient.hh"
-
-using namespace ost;
-using namespace ost::gfx;
-
-namespace {
-
-  typedef IndexedVertexArray::EntryList EntryList;
-  typedef IndexedVertexArray::IndexList IndexList;
-  
-  geom::Vec3 abs(const geom::Vec3& v) {
-    geom::Vec3 nrvo(std::abs(v[0]),std::abs(v[1]),std::abs(v[2]));
-    return nrvo;
-  }
-
-  std::pair<geom::Vec3, geom::Vec3> calc_limits(const EntryList& elist)
-  {
-    geom::Vec3 minc(std::numeric_limits<float>::max(),
-                    std::numeric_limits<float>::max(),
-                    std::numeric_limits<float>::max());
-    geom::Vec3 maxc(-std::numeric_limits<float>::max(),
-                    -std::numeric_limits<float>::max(),
-                    -std::numeric_limits<float>::max());
-
-    for(EntryList::const_iterator it=elist.begin();it!=elist.end();++it) {
-#if OST_DOUBLE_PRECISION
-      minc[0]=std::min(static_cast<double>(it->v[0]),minc[0]);
-      minc[1]=std::min(static_cast<double>(it->v[1]),minc[1]);
-      minc[2]=std::min(static_cast<double>(it->v[2]),minc[2]);
-      maxc[0]=std::max(static_cast<double>(it->v[0]),maxc[0]);
-      maxc[1]=std::max(static_cast<double>(it->v[1]),maxc[1]);
-      maxc[2]=std::max(static_cast<double>(it->v[2]),maxc[2]);
-#else
-      minc[0]=std::min(it->v[0],minc[0]);
-      minc[1]=std::min(it->v[1],minc[1]);
-      minc[2]=std::min(it->v[2],minc[2]);
-      maxc[0]=std::max(it->v[0],maxc[0]);
-      maxc[1]=std::max(it->v[1],maxc[1]);
-      maxc[2]=std::max(it->v[2],maxc[2]);
-#endif
-    }
-    return std::make_pair(minc,maxc);
-  }
-
-  struct CIndex { 
-    CIndex(): u(0),v(0),w(0) {}
-    CIndex(long uu, long vv, long ww): u(uu), v(vv), w(ww) {}
-    long u,v,w;
-    bool operator<(const CIndex& rhs) const {
-      return u==rhs.u ? (v==rhs.v ? w<rhs.w : v<rhs.v) : u<rhs.u;
-    }
-  };
-
-  struct CEntry {
-    CEntry(): id(0), type(0) {}
-    CEntry(unsigned int ii, const geom::Vec3& vv1, const geom::Vec3& vv2, const geom::Vec3& vv3, const geom::Vec4& cc):
-      id(ii), type(3), 
-      v0(1.0f/3.0f*(vv1+vv2+vv3)), 
-      v1(vv1), v2(vv2), v3(vv3), v4(), 
-      n(geom::Normalize(geom::Cross(v1-v2,v1-v3))),
-      c(cc) {}
-    CEntry(unsigned int ii, const geom::Vec3& vv1, const geom::Vec3& vv2, const geom::Vec3& vv3, const geom::Vec3& vv4, const geom::Vec4& cc):
-      id(ii), type(3), 
-      v0(1.0f/4.0f*(vv1+vv2+vv3+vv4)), 
-      v1(vv1), v2(vv2), v3(vv3), v4(vv4),
-      n(geom::Normalize(geom::Cross(v1-v2,v1-v3))),
-      c(cc) {}
-
-    unsigned int id;   // original entry id
-    unsigned int type; // type 
-    geom::Vec3 v0;     // center position
-    geom::Vec3 v1;     // edge positions
-    geom::Vec3 v2;     // edge positions
-    geom::Vec3 v3;     // edge positions
-    geom::Vec3 v4;     // edge positions
-    geom::Vec3 n;      // face normal
-    geom::Vec4 c;      // average color
-  };
-
-  struct RayEntry {
-    RayEntry(): v(), d2(0.0), c() {}
-    RayEntry(const geom::Vec3& vv, float dd): v(vv), d2(dd), c() {}
-    geom::Vec3 v;
-    float d2;
-    geom::Vec4 c;
-    bool hit;
-    bool back;
-  };
-
-  typedef std::vector<CEntry> CList;
-  typedef std::map<CIndex,CList > CMap;
-
-  class AmbientOcclusionBuilder {
-  public:
-    AmbientOcclusionBuilder(IndexedVertexArray& va):
-      va_(va), cmap_(), bsize_(5.0), weight_(0.5), cutoff_(bsize_), rays_(), density_(20) 
-    {
-      float delta=2.0*M_PI/static_cast<float>(density_);
-      for(unsigned int s=0;s<density_/2;++s) {
-        float a=s*delta;
-        float z=std::cos(a);
-        float x=std::sin(a);
-        unsigned int tmp_subdiv=static_cast<unsigned int>(round(2.0*M_PI*std::abs(x)/delta));
-        if(tmp_subdiv==0) {
-          rays_.push_back(RayEntry(geom::Vec3(0.0,0.0,z/std::abs(z)),cutoff_*cutoff_));
-        } else {
-          float tmp_delta=2.0*M_PI/static_cast<float>(tmp_subdiv);
-          for(unsigned int t=0;t<tmp_subdiv;++t) {
-            float b=t*tmp_delta;
-            rays_.push_back(RayEntry(geom::Normalize(geom::Vec3(x*std::cos(b),x*std::sin(b),z)),cutoff_*cutoff_));
-          }
-        }
-      }
-    }
-
-    CIndex coord_to_index(const geom::Vec3& v) 
-    {
-      return CIndex(static_cast<int>(floor(v[0]/bsize_)),
-                    static_cast<int>(floor(v[1]/bsize_)),
-                    static_cast<int>(floor(v[2]/bsize_)));
-    }
-    
-    void build_cmap() {
-      const EntryList& elist = va_.GetEntries();
-      const IndexList& tlist = va_.GetTriIndices();
-      const IndexList& qlist = va_.GetQuadIndices();
-
-      cmap_.clear();
-      float inv3 = 1.0f/3.0;
-      for(unsigned int c=0;c<tlist.size();c+=3) {
-        geom::Vec4 c0(elist[tlist[c+0]].c);
-        geom::Vec4 c1(elist[tlist[c+1]].c);
-        geom::Vec4 c2(elist[tlist[c+2]].c);
-        CEntry ce = add_to_cmap(c,geom::Vec3(elist[tlist[c+0]].v),geom::Vec3(elist[tlist[c+1]].v),geom::Vec3(elist[tlist[c+2]].v),inv3*(c0+c1+c2));
-        //std::cerr << c << " " << ce.n << " ";
-        //std::cerr << geom::Vec3(elist[tlist[c+0]].n) << " ";
-        //std::cerr << geom::Vec3(elist[tlist[c+1]].n) << " ";
-        //std::cerr << geom::Vec3(elist[tlist[c+2]].n) << std::endl;
-      }
-      float inv4 = 1.0f/4.0;
-      for(unsigned int c=0;c<qlist.size();c+=4) {
-        geom::Vec4 c0(elist[qlist[c+0]].c);
-        geom::Vec4 c1(elist[qlist[c+1]].c);
-        geom::Vec4 c2(elist[qlist[c+2]].c);
-        geom::Vec4 c3(elist[qlist[c+3]].c);
-        add_to_cmap(c,geom::Vec3(elist[qlist[c+0]].v),geom::Vec3(elist[qlist[c+1]].v),geom::Vec3(elist[qlist[c+2]].v),geom::Vec3(elist[qlist[c+3]].v),inv4*(c0+c1+c2+c3));
-      }
-    }
-    
-    CEntry add_to_cmap(unsigned int id, const geom::Vec3& v1, const geom::Vec3& v2, const geom::Vec3& v3, const geom::Vec4& c) 
-    {
-      CEntry ce(id,v1,v2,v3,c);
-      CIndex cindex=coord_to_index(ce.v0);
-      CMap::iterator it=cmap_.find(cindex);
-      if(it==cmap_.end()) {
-        std::vector<CEntry> tmplist(1);
-        tmplist[0]=ce;
-        cmap_[cindex]=tmplist;
-      } else {
-        it->second.push_back(ce);
-      }
-      return ce;
-    }
-
-    CEntry add_to_cmap(unsigned int id, const geom::Vec3& v1, const geom::Vec3& v2, const geom::Vec3& v3, const geom::Vec3& v4, const geom::Vec4& c) 
-    {
-      CEntry ce(id,v1,v2,v3,v4,c);
-      CIndex cindex=coord_to_index(ce.v0);
-      CMap::iterator it=cmap_.find(cindex);
-      if(it==cmap_.end()) {
-        std::vector<CEntry> tmplist(1);
-        tmplist[0]=ce;
-        cmap_[cindex]=tmplist;
-      } else {
-        it->second.push_back(ce);
-      }
-      return ce;
-    }
-
-    void accumulate(const CIndex& cindex, const CEntry& ce)
-    {
-      float cutoff2=cutoff_*cutoff_;
-      CMap::iterator mit=cmap_.find(cindex);
-      if(mit==cmap_.end()) return;
-      for(std::vector<CEntry>::const_iterator eit=mit->second.begin();eit!=mit->second.end();++eit) {
-        geom::Vec3 dir0=(eit->v0-ce.v0); // vector from reference entry to current entry
-        float l2=geom::Length2(dir0);
-        if(l2>cutoff2 || l2<0.01) continue;
-
-        dir0=geom::Normalize(dir0);
-
-        if(geom::Dot(dir0,ce.n)<1e-6) continue;
-
-        // largest opening angle from reference entry to corners
-        float a0=1.0;
-        if(eit->type==3) {
-          a0 = (geom::Dot(dir0,geom::Normalize(eit->v1-ce.v0))+
-                geom::Dot(dir0,geom::Normalize(eit->v2-ce.v0))+
-                geom::Dot(dir0,geom::Normalize(eit->v3-ce.v0)))/3.0;
-        } else if(eit->type==4) {
-          a0 = (geom::Dot(dir0,geom::Normalize(eit->v1-ce.v0))+
-                geom::Dot(dir0,geom::Normalize(eit->v2-ce.v0))+
-                geom::Dot(dir0,geom::Normalize(eit->v3-ce.v0))+
-                geom::Dot(dir0,geom::Normalize(eit->v4-ce.v0)))/4.0;
-        }
-
-        for(std::vector<RayEntry>::iterator rit=rays_.begin();rit!=rays_.end();++rit) {
-          if(rit->back) continue;
-          if(geom::Dot(ce.n,rit->v)<1e-6) {
-            rit->back=true;
-            continue;
-          }
-          if(geom::Dot(dir0,rit->v)<a0) continue;
-          if(rit->d2<l2) continue;
-          rit->d2=l2;
-          rit->c=eit->c;
-          rit->hit=true;
-        }
-      }
-    }
-
-    void calc_all() {
-      const EntryList& elist = va_.GetEntries();
-      const IndexList& tlist = va_.GetTriIndices();
-      const IndexList& qlist = va_.GetQuadIndices();
-      float cutoff2=cutoff_*cutoff_;
-      float isig2 = 1.0/(2.0*2.0*cutoff_/3.0*cutoff_/3.0);
-
-      std::vector<std::pair<geom::Vec4, int> > entry_accum(elist.size());
-      
-      for(CMap::iterator mit=cmap_.begin();mit!=cmap_.end();++mit) {
-        for(CList::iterator lit=mit->second.begin();lit!=mit->second.end();++lit) {
-          // reset rays
-          for(std::vector<RayEntry>::iterator rit=rays_.begin();rit!=rays_.end();++rit) {
-            rit->d2=cutoff2;
-            rit->hit=false;
-            rit->back=false;
-          }
-          // visit all 27 quadrants
-          for(int w=-1;w<=1;++w) {
-            for(int v=-1;v<=1;++v) {
-              for(int u=-1;u<=1;++u) {
-                accumulate(CIndex(mit->first.u+u,mit->first.v+v,mit->first.w+w),*lit);
-              }
-            }
-          }
-
-          // sum up ray contributions
-          float occl=0.0;
-          float occl_sum=0.0;
-          geom::Vec4 col(0.0,0.0,0.0,0.0);
-          float col_weight_sum=0.0;
-          for(std::vector<RayEntry>::iterator rit=rays_.begin();rit!=rays_.end();++rit) {
-            if(!rit->back) {
-              float ca=std::max(Real(0.0),geom::Dot(rit->v,lit->n));
-              occl_sum += ca;
-              if(!rit->hit) {
-                occl += ca;
-                float col_weight=exp(-rit->d2*isig2);
-                col[0] += col_weight*rit->c[0];
-                col[1] += col_weight*rit->c[1];
-                col[2] += col_weight*rit->c[2];
-                col_weight_sum+=col_weight;
-              }
-            }
-          }
-          if(occl_sum>0.0) occl/=occl_sum;
-          if(col_weight_sum>0.0) col/=col_weight_sum;
-
-          col[3]=occl;
-          if(lit->type==3) {
-            unsigned int litid=lit->id;
-            /*
-            entry_accum[tlist[litid+0]].first+=col;
-            entry_accum[tlist[litid+0]].second+=1;
-            entry_accum[tlist[litid+1]].first+=col;
-            entry_accum[tlist[litid+1]].second+=1;
-            entry_accum[tlist[litid+2]].first+=col;
-            entry_accum[tlist[litid+2]].second+=1;
-            */
-            std::pair<geom::Vec4,int>* e=&entry_accum[tlist[litid++]];
-            e->first+=col; ++e->second;
-            e=&entry_accum[tlist[litid++]];
-            e->first+=col; ++e->second;
-            e=&entry_accum[tlist[litid++]];
-            e->first+=col; ++e->second;
-          } else if(lit->type==4) {
-            unsigned int litid=lit->id;
-            std::pair<geom::Vec4,int>* e=&entry_accum[qlist[litid++]];
-            e->first+=col; ++e->second;
-            e=&entry_accum[qlist[litid++]];
-            e->first+=col; ++e->second;
-            e=&entry_accum[qlist[litid++]];
-            e->first+=col; ++e->second;
-            e=&entry_accum[qlist[litid++]];
-            e->first+=col; ++e->second;
-          }
-        }
-      }
-      for(unsigned int i=0;i<elist.size();++i) {
-        float fact = entry_accum[i].second==0 ? 1.0f : 1.0f/static_cast<float>(entry_accum[i].second);
-        va_.SetAmbientColor(i,Color(entry_accum[i].first[0]*fact,
-                                    entry_accum[i].first[1]*fact,
-                                    entry_accum[i].first[2]*fact,
-                                    entry_accum[i].first[3]*fact));
-      }
-    }
-    
-  private:
-    IndexedVertexArray& va_;
-    CMap cmap_;
-    float bsize_;
-    float weight_;
-    float cutoff_;
-    std::vector<RayEntry> rays_;
-    unsigned int density_;
-  };
-  
-} // ns
-
-
-
-void ost::gfx::CalcAmbientTerms(IndexedVertexArray& va)
-{
-  AmbientOcclusionBuilder aob(va);
-  LOG_DEBUG("building component map");
-  aob.build_cmap();
-  LOG_DEBUG("calculating ambient terms");
-  aob.calc_all();
-}
diff --git a/modules/gfx/src/impl/cartoon_renderer.cc b/modules/gfx/src/impl/cartoon_renderer.cc
index 08f0a0c3e5a1167a35d35a9712afc2f677505cc5..ce1a68676a6c470fcf760e05ef8ff38fdb1d650a 100644
--- a/modules/gfx/src/impl/cartoon_renderer.cc
+++ b/modules/gfx/src/impl/cartoon_renderer.cc
@@ -16,8 +16,17 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+/*
+   Author: Ansgar Philippsen
+*/
+
 #include "cartoon_renderer.hh"
 
+#include <Eigen/Core>
+#include <Eigen/Array>
+#include <Eigen/SVD>
+#include <Eigen/LU>
 
 #include <ost/gfx/entity.hh>
 #include <ost/gfx/impl/tabulated_trig.hh>
@@ -30,16 +39,11 @@ static const unsigned int MAX_ARC_DETAIL=12;
 
 using namespace impl;
 
-CartoonRenderer::CartoonRenderer(BackboneTrace& trace, bool force_tube): 
+CartoonRenderer::CartoonRenderer(BackboneTrace* trace, bool force_tube): 
   TraceRendererBase(trace, 3),   force_tube_(force_tube),
   options_(new CartoonRenderOptions(force_tube))
 {
-if(force_tube){
-  this->SetName("Smooth Tube");
-}
-else{
-  this->SetName("Helix & Strand Cartoon");
-}
+  this->SetName(force_tube ? "Smooth Tube" : "Helix & Strand Cartoon");
 }
 
 void CartoonRenderer::SetForceTube(bool force_tube)
@@ -47,75 +51,29 @@ void CartoonRenderer::SetForceTube(bool force_tube)
   force_tube_ = force_tube;
 }
 
-void CartoonRenderer::PrepareRendering(TraceSubset& subset, 
-                                       IndexedVertexArray& va,
-                                       SplineEntryListList& spline_list_list,
-                                       bool is_sel)
-{
-  int spline_detail=std::max((unsigned int) 1, options_->GetSplineDetail());
-  const Color& sel_clr=this->GetSelectionColor();
-  if(options_!=NULL){
-    va.Clear();
-    va.SetLighting(true);
-    va.SetCullFace(true);
-    va.SetColorMaterial(true);
-    va.SetMode(0x4);
-    va.SetPolyMode(options_->GetPolyMode());
-    spline_list_list.clear();
-    for (int node_list=0; node_list<subset.GetSize(); ++node_list) {
-      // first build the spline
-      Spline spl;
-      const NodeListSubset& nl=subset[node_list];
-      for (int i=0; i<nl.GetSize();++i) {      
-        int type=0;
-        const NodeEntry& entry=nl[i];
-        if(!force_tube_) {
-          mol::ResidueHandle resh = entry.atom.GetResidue();
-          mol::SecStructure sst=resh.GetSecStructure();
-          mol::ResidueHandle resh2 = resh.GetNext();
-          mol::SecStructure sst2=mol::SecStructure(mol::SecStructure::COIL);
-          if (resh2.IsValid()) {
-            sst2=resh2.GetSecStructure();
-          }
-          if(sst.IsHelical()) {
-            type=1;
-          } else if(sst.IsExtended()) {
-            if(!sst2.IsExtended()) {
-              type=3; // end of strand
-            } else {
-              type=2;
-            }
-          }
-        }
-        SplineEntry& ee = spl.AddEntry(entry.atom.GetPos(),entry.direction,
-                                       entry.normal, entry.rad, 
-                                       is_sel ? sel_clr : entry.color1, 
-                                       is_sel ? sel_clr : entry.color2, type);
-        ee.v1 = entry.v1;
-      }
-      spline_list_list.push_back(spl.Generate(spline_detail));
-      // now create the shape around the interpolated pathway
-    }
-    RebuildSplineObj(spline_list_list.back(), va, spline_list_list, subset, is_sel);    
-    va.SmoothNormals(options_->GetNormalSmoothFactor());
-  }  
-}
 void CartoonRenderer::PrepareRendering()
 {
   TraceRendererBase::PrepareRendering();
-  va_.Clear();
-  this->PrepareRendering(trace_subset_, va_, spline_list_list_, false);
-  if (this->HasSelection()) {
-    this->PrepareRendering(sel_subset_, sel_va_, sel_spline_list_list_, true);
-    sel_va_.SetColorMaterial(false);
+  if(state_>0) {
+    va_.Clear();
+    this->prepare_rendering(trace_subset_, va_, spline_list_list_);
+    rebuild_spline_obj(va_, spline_list_list_, false);
+  }
+  if (this->HasSelection() && (state_>0 || sel_state_>0)) {
+    sel_va_.Clear();
+    Color sel_color=GetSelectionColor();
+    rebuild_sel(spline_list_list_,sel_spline_list_list_,sel_color);
+    rebuild_spline_obj(sel_va_, sel_spline_list_list_, true);
+    sel_va_.SetColorMaterial(true);
     sel_va_.SetLighting(false);
+    sel_va_.SetMode(0x4);
+    sel_va_.SetPolyMode(options_->GetPolyMode());
+    sel_va_.SetOpacity(sel_color.Alpha());
   }
   sel_state_=0;
   state_=0;
 }
 
-void CartoonRenderer::Render(){}
-
 bool CartoonRenderer::CanSetOptions(RenderOptionsPtr& render_options)
 {
  return render_options.get()->GetRenderMode()==RenderMode::HSC;
@@ -131,95 +89,308 @@ RenderOptionsPtr CartoonRenderer::GetOptions()
  return options_;
 }
 
-void CartoonRenderer::RebuildSplineObj(const SplineEntryList& l, 
-                                       IndexedVertexArray& va,
-                                       SplineEntryListList& spline_list_list,
-                                       const TraceSubset& subset, bool is_sel)
+namespace {
+  typedef Eigen::Matrix<Real,3,1> EVec3;
+  typedef Eigen::Matrix<Real,3,3> EMat3;
+  typedef Eigen::Matrix<Real,1,3> ERVec3;
+  typedef Eigen::Matrix<Real,Eigen::Dynamic,Eigen::Dynamic> EMatX;
+  typedef Eigen::Matrix<Real,1,Eigen::Dynamic> ERVecX;
+
+  ERVec3 to_eigen(const geom::Vec3& v)
+  {
+    EVec3 nrvo=EVec3::Zero();
+    nrvo[0]=v[0]; nrvo[1]=v[1]; nrvo[2]=v[2];
+    return nrvo;
+  }
+  
+  std::pair<geom::Vec3,geom::Vec3> fit_helix(const std::vector<geom::Vec3>& points)
+  {
+    if(points.size()<4) {
+      return std::make_pair(points.front(),points.back());
+    }
+    geom::Vec3 cen(0.0,0.0,0.0);
+    for(unsigned int i=0;i<points.size();++i) cen+=points[i];
+    cen/=static_cast<float>(points.size());
+
+    EMatX A=EMatX::Zero(points.size(),3);
+    for(unsigned int i=0;i<points.size();++i) {
+      A.row(i)=to_eigen(points[i]-cen);
+    }
+
+    Eigen::SVD<EMatX> svd(A);
+    EMatX V=svd.matrixV();
+    geom::Vec3 ax(V(0,0),V(1,0),V(2,0));
+
+    geom::Vec3 p1=cen+ax*(-geom::Dot(cen,ax)+geom::Dot(points.front(),ax))/geom::Length2(ax);
+    geom::Vec3 p2=cen+ax*(-geom::Dot(cen,ax)+geom::Dot(points.back(),ax))/geom::Length2(ax);
+
+    return std::make_pair(p1,p2);
+  }
+  
+} // ns
+
+void CartoonRenderer::fudge_spline_obj(SplineEntryListList& olistlist)
 {
+  SplineEntryListList nlistlist;
+  SplineEntryList nlist;
+  
+  for(unsigned int llc=0;llc<olistlist.size();++llc) {
+    LOG_DEBUG("CartoonRenderer: fudging spline segment " << llc);
+    SplineEntryList olist = olistlist[llc];
+
+    if(!olist.empty()) {
+      olist.front().type=0;
+      olist.back().type=0;
+    }
+
+    for(unsigned int lc=0;lc<olist.size();++lc) {
+      if(olist.at(lc).type==1) {
+        if(options_->GetHelixMode()==1) {
+          // cylindrical helix
+          // collect all CA positions 
+          std::vector<geom::Vec3> points;
+          SplineEntry tmp_end(olist.at(lc));
+          unsigned int lstart=lc;
+          for(;lc<olist.size() && olist.at(lc).type==1;++lc) {
+            points.push_back(olist.at(lc).position);
+          }
+          unsigned int lend=lc-1;
+          if(lend-lstart<3) {
+            // this is a short helix, may as well not bother
+            for(unsigned int i=lstart;i<=lend;++i) {
+              nlist.push_back(olist[i]);
+              nlist.back().type=0;
+            }
+          } else {
+            // fit points to a cylinder
+            std::pair<geom::Vec3,geom::Vec3> cyl=fit_helix(points);
+
+            // extend the current spline to start of cyl
+            geom::Vec3 cyl_dir = geom::Normalize(cyl.second-cyl.first);
+            
+            if(lstart>0) {
+              SplineEntry tmp_end(olist[lstart]);
+              tmp_end.type=0;
+              tmp_end.position=cyl.first;
+              tmp_end.direction=cyl_dir;
+              tmp_end.color1=olist[lstart-1].color1;
+              tmp_end.color2=olist[lstart-1].color2;
+              tmp_end.normal=geom::Normalize(geom::Cross(cyl_dir,geom::Cross(tmp_end.normal,cyl_dir)));
+              if(geom::Dot(tmp_end.normal,olist[lstart].normal)<0.0) {
+                tmp_end.normal=-tmp_end.normal;
+              }
+              nlist.push_back(tmp_end);
+
+              // break nodelist
+              nlistlist.push_back(nlist);
+              nlist.clear();
+            }
+            
+            // make a two entry list with the cyl type
+            nlist.push_back(SplineEntry(cyl.first,geom::Vec3(),geom::Vec3(),0.0,
+                                        olist[lstart].color1,olist[lstart].color1,
+                                        6,olist[lstart].id));
+            nlist.push_back(SplineEntry(cyl.second,geom::Vec3(),geom::Vec3(),0.0,
+                                        olist[lend].color1,olist[lend].color1,
+                                        6,olist[lend].id));
+            nlistlist.push_back(nlist);
+            nlist.clear();
+            
+            if(lend+1<olist.size()) {
+              // and get going with an entry at the end of the cylinder
+              SplineEntry tmp_start(olist[lend]);
+              tmp_start.type=0;
+              tmp_start.position=cyl.second;
+              tmp_start.direction=cyl_dir;
+              tmp_start.color1=olist[lend+1].color1;
+              tmp_start.color2=olist[lend+1].color2;
+              tmp_start.normal=geom::Normalize(geom::Cross(cyl_dir,geom::Cross(tmp_start.normal,cyl_dir)));
+              if(geom::Dot(tmp_start.normal,olist[lstart].normal)<0.0) {
+                tmp_start.normal=-tmp_start.normal;
+              }
+              nlist.push_back(tmp_start);
+            }
+          }
+        } else { // helix mode 0
+          // just copy them over
+          for(;lc<olist.size() && olist.at(lc).type==1;++lc) {
+            nlist.push_back(olist.at(lc));
+          }
+        }
+      }
+      if(lc>=olist.size()) break;
+      // can't use else here in case the above routine advanced lc to end
+      if(olist.at(lc).type==2) {
+        // strand
+        unsigned int kstart=nlist.size();
+        unsigned int kend=kstart;
+        for(;lc<olist.size() && olist.at(lc).type==2;++lc,++kend) {
+          nlist.push_back(olist.at(lc));
+        }
+        if(kend-kstart<2) {
+          // dont bother with too short strands
+          for(unsigned int i=kstart;i<kend;++i) {
+            nlist.at(i).type=0;
+          }
+        } else {
+          kend-=1;
+          // these magic numbers are used in rebuild_spline_obj for proper arrow rendering
+          nlist.at(kend-1).type=3;
+          nlist.at(kend).type=5;
+          
+          if(options_->GetStrandMode()==1) {
+            // smooth the strands for mode 1
+            nlist.at(kstart).direction = geom::Normalize(nlist.at(kend).position-nlist.at(kstart).position);
+            nlist.at(kend).direction=nlist.at(kstart).direction;
+            float invf=1.0/static_cast<float>(kend-kstart);
+            for(unsigned int k=kstart;k<=kend;++k) {
+              float f = static_cast<float>(k-kstart)*invf;
+              nlist.at(k).position=nlist.at(kstart).position+f*(nlist.at(kend).position-nlist.at(kstart).position);
+              nlist.at(k).direction=nlist.at(kstart).direction;
+              geom::Vec3 tmpn=geom::Normalize(nlist.at(kstart).normal+f*(nlist.at(kend).normal-nlist.at(kstart).normal));
+              geom::Vec3 tmpx=geom::Normalize(geom::Cross(nlist.at(kstart).direction,tmpn));
+              nlist.at(k).normal=geom::Normalize(geom::Cross(tmpx,nlist.at(kstart).direction));
+            }
+          
+            // and break nodelist, re-starting at arrow tip, just for mode 1
+            if(lc+1<olist.size()) {
+              nlistlist.push_back(nlist);
+              nlist.clear();
+              nlist.push_back(nlistlist.back().back());
+              nlist.back().type=0;
+              nlist.back().color1=olist[lc+1].color1;
+              nlist.back().color2=olist[lc+1].color2;
+            }
+          }
+        }
+      }
+      if(lc<olist.size()) {
+        nlist.push_back(olist.at(lc));
+      }
+    }
+    if(!nlist.empty()) {
+      nlistlist.push_back(nlist);
+      nlist.clear();
+    }
+  }
+  olistlist.swap(nlistlist);
+}
+
+void CartoonRenderer::rebuild_spline_obj(IndexedVertexArray& va,
+                                         const SplineEntryListList& spline_list_list,
+                                         bool is_sel)
+{
+  LOG_DEBUG("CartoonRenderer: starting profile assembly");
   unsigned int detail = std::min(MAX_ARC_DETAIL,
                                  std::max(options_->GetArcDetail(),
                                  (unsigned int)1));
-  int spline_detail=std::max((unsigned int) 1, options_->GetSplineDetail());
   std::vector<TraceProfile> profiles;
   float factor=is_sel ? 0.2 : 0.0;
-  profiles.push_back(GetCircProfile(detail,
-				    options_->GetTubeRadius()*options_->GetTubeRatio()+factor,
-				    options_->GetTubeRadius()+factor, 
-				    options_->GetTubeProfileType(),
-				    1.0)); // tube
+  profiles.push_back(get_circ_profile(detail,
+                                    options_->GetTubeRadius()*options_->GetTubeRatio()+factor,
+                                    options_->GetTubeRadius()+factor, 
+                                    options_->GetTubeProfileType(),
+                                    1.0)); // profile 0 = tube
   if (!force_tube_) {
-    profiles.push_back(GetCircProfile(detail,
-				      options_->GetHelixWidth()+factor,
-				      options_->GetHelixThickness()+factor,
-				      options_->GetHelixProfileType(),
-				      options_->GetHelixEcc())); // helix
-    profiles.push_back(GetCircProfile(detail,
-				      options_->GetStrandWidth()+factor,
-				      options_->GetStrandThickness()+factor,
-				      options_->GetStrandProfileType(),
-				      options_->GetStrandEcc())); // strand
-    profiles.push_back(GetCircProfile(detail,
-				      0.1*options_->GetStrandWidth()+factor,
-				      options_->GetStrandThickness()+factor,
-				      options_->GetTubeProfileType(),
-				      1.0)); // arrow end, tube profile
-    profiles.push_back(GetCircProfile(detail,
-				      1.7*options_->GetStrandWidth()+factor,
-				      1.1*options_->GetStrandThickness()+factor,
-				      options_->GetStrandProfileType(),
-				      options_->GetStrandEcc())); // arrow start
+    profiles.push_back(get_circ_profile(detail,
+                                      options_->GetHelixWidth()+factor,
+                                      options_->GetHelixThickness()+factor,
+                                      options_->GetHelixProfileType(),
+                                      options_->GetHelixEcc())); // profile 1 = helix
+    profiles.push_back(get_circ_profile(detail,
+                                      options_->GetStrandWidth()+factor,
+                                      options_->GetStrandThickness()+factor,
+                                      options_->GetStrandProfileType(),
+                                      options_->GetStrandEcc())); // profile 2 = strand
+    profiles.push_back(profiles.back()); // profile 3==2, strand
+    
+    profiles.push_back(get_circ_profile(detail,
+                                      1.7*options_->GetStrandWidth()+factor,
+                                      1.1*options_->GetStrandThickness()+factor,
+                                      options_->GetStrandProfileType(),
+                                      options_->GetStrandEcc())); // profile 4 = arrow start
+    profiles.push_back(get_circ_profile(detail,
+                                      0.01*options_->GetStrandWidth()+factor,
+                                      1.1*options_->GetStrandThickness()+factor,
+                                      options_->GetStrandProfileType(),
+                                      options_->GetStrandEcc())); // profile 5 = arrow end
+
   }
 
   // iterate over all spline segments
-  for(SplineEntryListList::iterator it=spline_list_list.begin();
+  
+#if !defined(NDEBUG)
+  unsigned int tmp_count=0;
+#endif
+  for(SplineEntryListList::const_iterator it=spline_list_list.begin();
       it<spline_list_list.end();++it) {
     /*
       for each spline segment, transform the profile according to the
       normal and direction and assemble it together with the last
       transformed profile into a graphical segment
     */
-    SplineEntryList& slist=*it;
-    const NodeListSubset& nl=subset[it-spline_list_list.begin()];
-    int sit=0, send=slist.size()-spline_detail+1;
-    if (nl.AtStart()>0) {
-      sit+=nl.AtStart()*spline_detail-spline_detail/2;
-    }
-    if (nl.AtEnd()>0) {
-      send-=nl.AtEnd()*spline_detail-spline_detail/2;
+    SplineEntryList slist=*it;
+    if(slist.empty()) continue;
+    LOG_DEBUG("CartoonRenderer: assembling fragment " << tmp_count << " with " << slist.size() << " spline segments");
+
+    if(slist.size()==2 && slist[0].type==6) {
+      // make a cylinder
+      va.AddCylinder(CylinderPrim(slist[0].position,slist[1].position,
+				  options_->GetHelixWidth(),
+				  slist[0].color1,slist[1].color1),
+		     options_->GetArcDetail(),true);
+      continue;
     }
-    TraceProfile tprof1=TransformAndAddProfile(profiles,slist[sit],va);
-    CapProfile(tprof1,slist[sit],true,va);
+
+    TraceProfile tprof1=transform_and_add_profile(profiles,slist[0],va);
+    cap_profile(tprof1,slist[0],true,va);
     TraceProfile tprof2;
-    SplineEntry& last_se=slist[send-1];
-    for (int sc=sit+1; sc<send; ++sc) {
-      if(slist[sc-1].type==2 && slist[sc].type==3) {
-        // arrow on last strand segment
-        // type1 is already set to 4 (Spline::Generate),
-        // hence just insert single bridging profile
-        SplineEntry se(slist[sc]);
-        se.type=last_se.type;
-        se.type1=last_se.type1;
-        se.type2=last_se.type2;
-        tprof2=TransformAndAddProfile(profiles,se, va);
-        AssembleProfile(tprof1,tprof2,va);
-        tprof1=tprof2;
-        tprof2=TransformAndAddProfile(profiles,slist[sc], va);
-        last_se=slist[sc];
+    size_t sc=1;
+    size_t psize=tprof1.size()-1;
+    double psized=static_cast<double>(psize);
+    float of=static_cast<float>(psize)/(2.0*M_PI);
+    for (; sc<slist.size(); ++sc) {
+      size_t offset=0;
+      if(slist.at(sc).type==0) {
+        geom::Vec3 dir=slist.at(sc).position-slist.at(sc-1).position;
+        double ang=-geom::SignedAngle(geom::Cross(slist.at(sc-1).normal,dir),
+                                      geom::Cross(slist.at(sc).normal,dir),
+                                      dir);
+        offset=psize+static_cast<size_t>(round(ang*of)+psized);
+      }
+      if(slist.at(sc).type==3) {
+        if(slist.at(sc-1).type!=3) {
+          // boundary to arrow
+          SplineEntry se(slist[sc]);
+          tprof2=transform_and_add_profile(profiles,se, va);
+          assemble_profile(tprof1,tprof2,va,offset);
+          tprof1=tprof2;
+          se.type=2;
+          se.type1=4;
+          se.type2=4;
+          tprof2=transform_and_add_profile(profiles,se, va);
+        } else {
+          SplineEntry se(slist.at(sc));
+          se.type1=4;
+          if(options_->GetStrandMode()==1) se.type2=5;
+          tprof2=transform_and_add_profile(profiles,se, va);
+        }
       } else {
-        tprof2=TransformAndAddProfile(profiles,slist[sc], va);
+        tprof2=transform_and_add_profile(profiles,slist.at(sc), va);
       }
-      AssembleProfile(tprof1,tprof2,va);
+      assemble_profile(tprof1,tprof2,va,offset);
       tprof1=tprof2;
-      last_se=slist[sc];
     }
-    CapProfile(tprof1,slist[send-1],false,va);
+    cap_profile(tprof1,slist.at(sc-1),false,va);
   }
 }
 
-
-
-TraceProfile CartoonRenderer::TransformAndAddProfile(const std::vector<TraceProfile>& profiles, const SplineEntry& se, IndexedVertexArray& va)
+TraceProfile CartoonRenderer::transform_and_add_profile(const std::vector<TraceProfile>& profiles,
+                                                        const SplineEntry& se,
+                                                        IndexedVertexArray& va)
 {
+  assert(se.type1>=0 && se.type1<=5);
+  assert(se.type2>=0 && se.type2<=5);
   TraceProfile prof1 = profiles[se.type1];
   TraceProfile prof2 = profiles[se.type2];
 
@@ -235,15 +406,25 @@ TraceProfile CartoonRenderer::TransformAndAddProfile(const std::vector<TraceProf
                   norm[2],orth[2],dir[2]);
 
   // assemble profile with custom coloring
-  TraceProfile tf_prof(prof1.size());
+
+  /*
+    N+1 is used here because the first point
+    needs to be duplicated for texture
+    coordinate assignment to work properly
+  */
+  TraceProfile tf_prof(prof1.size()+1);
+
+
   unsigned int half=prof1.size()/2;
   unsigned int seg=prof1.size()/16;
-  for(unsigned int c=0;c<prof1.size();++c) {
-    geom::Vec3 vec=rmat*se.rad*prof1[c].v;
-    geom::Vec3 norm=rmat*prof1[c].n;
+  for(unsigned int c=0;c<prof1.size()+1;++c) {
+    // use cc everywhere except for the texture coordinate calculation
+    int cc=c%prof1.size();
+    geom::Vec3 vec=rmat*se.rad*prof1[cc].v;
+    geom::Vec3 norm=rmat*prof1[cc].n;
     if(fuse_flag) {
-      geom::Vec3 vec2=rmat*se.rad*prof2[c].v;
-      geom::Vec3 norm2=rmat*prof2[c].n;
+      geom::Vec3 vec2=rmat*se.rad*prof2[cc].v;
+      geom::Vec3 norm2=rmat*prof2[cc].n;
       vec=se.position+(1.0f-se.frac)*vec+se.frac*vec2;
       norm=Normalize((1.0f-se.frac)*norm+se.frac*norm2);
     } else {
@@ -261,44 +442,46 @@ TraceProfile CartoonRenderer::TransformAndAddProfile(const std::vector<TraceProf
     } else if(se.type==2 || se.type==3) {
       if(c<=seg || (c>=half-seg && c<=half+seg) || c>=prof1.size()-seg) col=se.color2;
     }
-    tf_prof[c].id=va.Add(vec,norm, col);
+    // c is used instead of cc to get 1.0 for the last point
+    float tx=static_cast<float>(c)/static_cast<float>(prof1.size());
+    float ty=se.running_length;
+    tf_prof[c].id=va.Add(vec,norm,col,geom::Vec2(tx,ty));
   }
   return tf_prof;
 }
 
-void CartoonRenderer::AssembleProfile(const TraceProfile& prof1,
-                                      const TraceProfile& prof2, 
-                                      IndexedVertexArray& va)
-{
-  // determine rotational offset with a heuristic routine
-  int best_off=0;
-#if 0
-  uint i1=0;
-  uint i2=prof1.size()/4;
-  uint i3=prof1.size()/2;
-  uint i4=std::min(prof1.size()-1,size_t(i2+i3));
-  float best_val = Dot(prof1[i1].n,prof2[i1].n)+
-                    Dot(prof1[i2].n,prof2[i2].n)+
-                    Dot(prof1[i3].n,prof2[i3].n)+
-                    Dot(prof1[i4].n,prof2[i4].n);
-
-  for(unsigned int oo=1;oo<prof1.size();++oo) {
-    float val = Dot(prof1[i1].n,prof2[oo].n)+
-                 Dot(prof1[i2].n,prof2[(oo+i2)%prof1.size()].n)+
-                 Dot(prof1[i3].n,prof2[(oo+i3)%prof1.size()].n)+
-                 Dot(prof1[i4].n,prof2[(oo+i4)%prof1.size()].n);
-    if(val>best_val) {
-      best_val=val;
-      best_off=oo;
-    }
+namespace {
+
+  float spread(const geom::Vec3& v1, geom::Vec3& v2, geom::Vec3& v3, geom::Vec3& v4)
+  {
+    return geom::Dot(geom::Normalize(geom::Cross(geom::Normalize(v3-v1),geom::Normalize(v2-v1))),
+		     geom::Normalize(geom::Cross(geom::Normalize(v3-v4),geom::Normalize(v2-v4))));
   }
-#endif
 
-  // assume both profiles have the same size
-  for(unsigned int i1=0;i1<prof1.size();++i1) {
-    unsigned int i2=(i1+1)%prof1.size();
-    unsigned int i3=(i1+best_off)%prof1.size();
-    unsigned int i4=(i1+best_off+1)%prof1.size();
+}
+
+void CartoonRenderer::assemble_profile(const TraceProfile& prof1,
+                                       const TraceProfile& prof2, 
+                                       IndexedVertexArray& va,
+                                       size_t offset)
+{
+  /*
+    the wrap around algorithm used here needs to take into account
+    that the TraceProfile has a duplicate entry for prof*[0] and
+    prof*[N-1], which fall onto the same point except and have
+    the same normal but a different texture coordinate. Hence
+    size()-1
+  */
+  size_t size=prof1.size()-1;
+  // now assemble the triangles
+  for(unsigned int i1=0;i1<size;++i1) {
+    size_t i2=(i1+1)%(size);
+    size_t i3=(i1+offset)%(size);
+    size_t i4=(i1+offset+1)%(size);
+
+    // wrap around correction for proper texture coordinates
+    i2 = (i2==0) ? size : i2;
+    i4 = (i4==0) ? size : i4;
 
 #if 1
     va.AddTri(prof1[i1].id,prof1[i2].id,prof2[i3].id);
@@ -309,18 +492,21 @@ void CartoonRenderer::AssembleProfile(const TraceProfile& prof1,
   }
 }
 
-void CartoonRenderer::CapProfile(const impl::TraceProfile& p,
-                                 const impl::SplineEntry& se,
-                                 bool flipn, IndexedVertexArray& va)
+void CartoonRenderer::cap_profile(const impl::TraceProfile& p,
+                                  const impl::SplineEntry& se,
+                                  bool flipn, IndexedVertexArray& va)
 {
   geom::Vec3 norm=flipn ? -se.direction : se.direction;
-  VertexID pi0 = va.Add(se.position,norm, se.color1);
+  VertexID pi0 = va.Add(se.position,norm, se.color1,geom::Vec2(0.5,0.5));
   std::vector<VertexID> vertices(p.size());
+  float fac=2.0*M_PI/static_cast<float>(p.size()-1);
   for(unsigned int i=0;i<p.size();++i) {
-    vertices[i]=va.Add(p[i].v,norm,se.color1);
+    float aa=fac*static_cast<float>(i%(p.size()-1));
+    vertices[i]=va.Add(p[i].v,norm,se.color1,geom::Vec2(0.5*cos(aa)+0.5,0.5*sin(aa)+0.5));
   }
-  for(unsigned int i1=0;i1<p.size();++i1) {
-    unsigned int i2=(i1+1)%p.size();
+  // taking first/last duplication into account again (see assemble_profile)
+  for(unsigned int i1=0;i1<p.size()-1;++i1) {
+    unsigned int i2=i1+1;
     if(flipn) {
       va.AddTri(pi0,vertices[i2],vertices[i1]);
     } else {
@@ -405,9 +591,9 @@ namespace {
       prof[3*detail+i]=TraceProfileEntry(geom::Vec3(py,-px,0),geom::Vec3());
     }
   }
-}
+} // anon ns
 
-  TraceProfile CartoonRenderer::GetCircProfile(unsigned int detail, float rx, float ry, unsigned int type, float ecc)
+TraceProfile CartoonRenderer::get_circ_profile(unsigned int detail, float rx, float ry, unsigned int type, float ecc)
 {
   unsigned int d4=detail*4;
   TraceProfile prof(d4);
@@ -434,15 +620,80 @@ namespace {
   for(unsigned int i=0;i<d4;++i) {
     unsigned int p1=(d4+i-1)%d4;
     unsigned int p2=(i+1)%d4;
-    float dx=prof[p2].v[0]-prof[p1].v[0];
-    float dy=prof[p2].v[1]-prof[p1].v[1];
-    prof[i].n=geom::Normalize(geom::Vec3(dy,-dx,0.0));
+    float f1=geom::Length2(prof[p1].v-prof[i].v);
+    float f2=geom::Length2(prof[p2].v-prof[i].v);
+    geom::Vec3 s = f2*(prof[p2].v-prof[i].v)-f1*(prof[p1].v-prof[i].v);
+    prof[i].n=geom::Normalize(geom::Vec3(s[1],-s[0],0.0));
   }
   return prof;
 }
 
-CartoonRenderer::~CartoonRenderer() {}
+void CartoonRenderer::prepare_rendering(const BackboneTrace& subset, 
+                                       IndexedVertexArray& va,
+                                       SplineEntryListList& spline_list_list)
+{
+  if(options_==NULL) {
+    LOG_DEBUG("CartoonRenderer: NULL options, not creating objects");
+  }
 
-}
+  va.Clear();
+  va.SetLighting(true);
+  va.SetCullFace(true);
+  va.SetColorMaterial(true);
+  va.SetMode(0x4);
+  va.SetPolyMode(options_->GetPolyMode());
 
+  LOG_DEBUG("CartoonRenderer: starting object build");
+  int spline_detail=std::max((unsigned int) 1, options_->GetSplineDetail());
+  SplineEntryListList tmp_sll;
+  for (int node_list=0; node_list<subset.GetListCount(); ++node_list) {
+    LOG_DEBUG("CartoonRenderer: collecting spline entries for node list " << node_list);
+    // first build the spline
+    SplineEntryList spl;
+    const NodeEntryList& nl=subset.GetList(node_list);
+    for (unsigned int i=0; i<nl.size();++i) {
+      int type=0;
+      const NodeEntry& entry=nl[i];
+      if(!force_tube_) {
+        mol::ResidueHandle resh = entry.atom.GetResidue();
+        mol::SecStructure sst=resh.GetSecStructure();
+        if(sst.IsHelical()) {
+          type=1;
+        } else if(sst.IsExtended()) {
+          type=2;
+        }
+      }
+      SplineEntry ee(entry.atom.GetPos(),entry.direction,
+		     entry.normal, entry.rad, 
+		     entry.color1, 
+		     entry.color2,
+		     type, entry.id);
+      ee.v1 = entry.v1;
+      spl.push_back(ee);
+    }
+    LOG_DEBUG("CartoonRenderer: found " << spl.size() << " entries");
+    if(!spl.empty()) {
+      tmp_sll.push_back(spl);
+    }
+  }
+  if(!force_tube_) {
+    LOG_DEBUG("CartoonRenderer: adjusting spline-entry-list lists for various modes");
+    fudge_spline_obj(tmp_sll);
+  }
+  spline_list_list.clear();
+#if !defined(NDEBUG)
+  unsigned int tmp_count=0;
+#endif
+  for(SplineEntryListList::const_iterator sit=tmp_sll.begin();sit!=tmp_sll.end();++sit) {
+    if((sit->size()==2) && (sit->at(0).type==6)) {
+      // don't intpol cylinders
+      spline_list_list.push_back(*sit);
+    } else {
+      LOG_DEBUG("CartoonRenderer: generating full spline for spline-entry-list " << tmp_count++);
+      spline_list_list.push_back(Spline::Generate(*sit,spline_detail,options_->GetColorBlendMode()));
+    }
+  }
 }
+
+
+}} // ns
diff --git a/modules/gfx/src/impl/cartoon_renderer.hh b/modules/gfx/src/impl/cartoon_renderer.hh
index ff9097e5c5f2bee0c04ac945aeb0ded32c4d26ca..c7f726c47bfb550353b12b7813a8282b6e00bc23 100644
--- a/modules/gfx/src/impl/cartoon_renderer.hh
+++ b/modules/gfx/src/impl/cartoon_renderer.hh
@@ -16,6 +16,11 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+/*
+   Author: Ansgar Philippsen
+*/
+
 #ifndef OST_GFX_CARTOON_RENDERER_HH
 #define OST_GFX_CARTOON_RENDERER_HH
 
@@ -34,42 +39,42 @@ namespace ost { namespace gfx { namespace impl {
 /// \internal
 class DLLEXPORT_OST_GFX CartoonRenderer: public TraceRendererBase {
 public:
-  CartoonRenderer(BackboneTrace& trace, bool force_tube=false);
+  CartoonRenderer(BackboneTrace* trace, bool force_tube=false);
 
   virtual void PrepareRendering();
-  virtual void Render();
 
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
   virtual void SetOptions(RenderOptionsPtr& render_options);
   virtual RenderOptionsPtr GetOptions();
 
-
   virtual void SetForceTube(bool force_tube);
-
-
-  virtual ~CartoonRenderer();
   
 private:
-  void RebuildSplineObj(const SplineEntryList& l, IndexedVertexArray& va,
-                        SplineEntryListList& spline_list_list,
-                        const TraceSubset& subset, bool is_sel);
+  void prepare_rendering(const BackboneTrace&,
+                         IndexedVertexArray&, 
+                         SplineEntryListList&);
+
+  void fudge_spline_obj(SplineEntryListList&);
+
+  void rebuild_spline_obj(IndexedVertexArray&,
+                          const SplineEntryListList&,
+                          bool);
   
-  void CapProfile(const impl::TraceProfile& p, 
-                  const impl::SplineEntry& se, 
-                  bool flipn, IndexedVertexArray& va);
+  void cap_profile(const impl::TraceProfile&, 
+                   const impl::SplineEntry&, 
+                   bool,
+                   IndexedVertexArray&);
                   
-  void AssembleProfile(const TraceProfile& prof1,
-                       const TraceProfile& prof2, 
-                       IndexedVertexArray& va);
-
-  TraceProfile TransformAndAddProfile(const std::vector<TraceProfile>& profiles, 
-                                      const SplineEntry& se, 
-                                      IndexedVertexArray& va);
+  void assemble_profile(const TraceProfile&,
+                        const TraceProfile&, 
+                        IndexedVertexArray&,
+                        size_t);
 
-  void PrepareRendering(TraceSubset& subset, IndexedVertexArray& va, 
-                        SplineEntryListList& spline_list_list, bool is_sel);
+  TraceProfile transform_and_add_profile(const std::vector<TraceProfile>&, 
+                                         const SplineEntry&, 
+                                         IndexedVertexArray&);
 
-  TraceProfile GetCircProfile(unsigned int detail, float rx, float ry, unsigned int type, float ecc);
+  TraceProfile get_circ_profile(unsigned int detail, float rx, float ry, unsigned int type, float ecc);
 
   bool force_tube_;
   CartoonRenderOptionsPtr options_;
diff --git a/modules/gfx/src/impl/connect_renderer_base.hh b/modules/gfx/src/impl/connect_renderer_base.hh
index 78b730fc18c5bc56cf5b0edd3a7df89fda2d2d6e..1c88950fff335dc19b90d5b80a6d298f1096ada7 100644
--- a/modules/gfx/src/impl/connect_renderer_base.hh
+++ b/modules/gfx/src/impl/connect_renderer_base.hh
@@ -60,7 +60,7 @@ protected:
   float GetFixedPickRadius() const { return pick_radius_; }
 
 protected:
- float     pick_radius_;
+  float     pick_radius_;
   GfxView  view_;
   GfxView  sel_view_;
 };
diff --git a/modules/gfx/src/impl/cpk_renderer.cc b/modules/gfx/src/impl/cpk_renderer.cc
index fc3b2b916170cc0e5dc16e2ea9f3a0b425fb6cdb..47bec0384791053608b15f6b6587c955d99e89a1 100644
--- a/modules/gfx/src/impl/cpk_renderer.cc
+++ b/modules/gfx/src/impl/cpk_renderer.cc
@@ -74,8 +74,8 @@ void CPKRenderer::Render(RenderPass pass)
 {
   if(options_!=NULL){
 #if OST_SHADER_SUPPORT_ENABLED
-    if(options_->GetCPKMode()==1 || options_->GetCPKMode()==2) {
-      this->RenderCPK2();
+    if(pass==STANDARD_RENDER_PASS && (options_->GetSphereMode()==1 || options_->GetSphereMode()==2)) {
+      this->Render3DSprites();
       return;
     }
 #endif
@@ -86,6 +86,7 @@ void CPKRenderer::Render(RenderPass pass)
 
 void CPKRenderer::RenderPov(PovState& pov, const std::string& name)
 {
+  if(view_.atom_map.empty()) return;
   pov.write_merge_or_union(name);
   
   for (AtomEntryMap::const_iterator it=view_.atom_map.begin();it!=view_.atom_map.end();++it) {
@@ -110,78 +111,11 @@ RenderOptionsPtr CPKRenderer::GetOptions(){
  return options_;
 }
 
-std::vector<impl::AtomEntry*> CPKRenderer::CPKOcclusion()
-{
-
-  std::vector<impl::AtomEntry*> aelist;
-
-#if OST_SHADER_SUPPORT_ENABLED
-  static const float isq2 = 1.0/sqrt(2.0);
-  geom::Mat3 irot=geom::Transpose(Scene::Instance().GetTransform().GetRot());
-  geom::Vec3 cx=irot*geom::Vec3(isq2,0.0,0.0);
-  geom::Vec3 cy=irot*geom::Vec3(0.0,isq2,0.0);
-
-  Shader::Instance().PushProgram();
-  Shader::Instance().Activate("");
-
-  glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  glDisable(GL_LIGHTING);
-  glDisable(GL_CULL_FACE);
-  glDisable(GL_FOG);
-  glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
-
-  glBegin(GL_QUADS);
-  for(AtomEntryMap::const_iterator it=view_.atom_map.begin();
-      it!=view_.atom_map.end();++it) {
-    geom::Vec3 pos = it->second.atom.GetPos();
-    float rad = it->second.vdwr;
-    glVertex3v((pos-rad*cx-rad*cy).Data());
-    glVertex3v((pos-rad*cx+rad*cy).Data());
-    glVertex3v((pos+rad*cx+rad*cy).Data());
-    glVertex3v((pos+rad*cx-rad*cy).Data());
-  }
-  glEnd();
-
-  cx=irot*geom::Vec3(1.0,0.0,0.0);
-  cy=irot*geom::Vec3(0.0,1.0,0.0);
-
-  glDepthMask(GL_FALSE);
-
-  uint query_id;
-  glGenQueries(1,&query_id);
-
-  for(AtomEntryMap::iterator it=view_.atom_map.begin();
-      it!=view_.atom_map.end();++it) {
-    geom::Vec3 pos = it->second.atom.GetPos();
-    float rad = it->second.vdwr;
-    glBeginQuery(GL_SAMPLES_PASSED, query_id);
-    glBegin(GL_QUADS);
-    glVertex3v((pos-rad*cx-rad*cy).Data());
-    glVertex3v((pos-rad*cx+rad*cy).Data());
-    glVertex3v((pos+rad*cx+rad*cy).Data());
-    glVertex3v((pos+rad*cx-rad*cy).Data());
-    glEnd();
-    glEndQuery(GL_SAMPLES_PASSED);
-    GLint samples=0;
-    glGetQueryObjectiv(query_id,GL_QUERY_RESULT,&samples);
-    if(samples>0) aelist.push_back(&it->second);
-  }
-
-  glDeleteQueries(1,&query_id);
-
-  glPopAttrib();
-
-  Shader::Instance().PopProgram();
-#endif
-
-  return aelist;
-}
-
 namespace {
 
-void RenderCPK2InnerLoop(const AtomEntry* ae, const geom::Vec3& cx, 
-                         const geom::Vec3& cy, const geom::Vec3& cz, 
-                         GLdouble* gl_mmat, GLdouble* gl_pmat, GLint* gl_vp)
+void Render3DSpritesInnerLoop(const AtomEntry* ae, const geom::Vec3& cx, 
+			      const geom::Vec3& cy, const geom::Vec3& cz, 
+			      GLdouble* gl_mmat, GLdouble* gl_pmat, GLint* gl_vp)
 {
   geom::Vec3 pos = ae->atom.GetPos();
   float rad = ae->vdwr;
@@ -206,7 +140,7 @@ void RenderCPK2InnerLoop(const AtomEntry* ae, const geom::Vec3& cx,
 
 }
 
-void CPKRenderer::RenderCPK2()
+void CPKRenderer::Render3DSprites()
 {
 #if OST_SHADER_SUPPORT_ENABLED
   if(options_!=NULL){
@@ -215,16 +149,13 @@ void CPKRenderer::RenderCPK2()
     geom::Vec3 cy=irot*geom::Vec3(0.0,1.0,0.0);
     geom::Vec3 cz=irot*geom::Vec3(0.0,0.0,1.0);
 
-    std::vector<AtomEntry*> aelist;
-    if(options_->GetCPKMode()==2) {
-      aelist = CPKOcclusion();
-    }
-
+    uint write_normals = Shader::Instance().GetCurrentName()=="dumpnorm" ? 1 : 0;
     Shader::Instance().PushProgram();
     Shader::Instance().Activate("fast_sphere");
     Shader::Instance().UpdateState();
+    glUniform1i(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"write_normals"),write_normals);
 
-    glPushAttrib(GL_ENABLE_BIT);
+    glPushAttrib(GL_ALL_ATTRIB_BITS);
     glDisable(GL_LIGHTING);
     glDisable(GL_CULL_FACE);
 
@@ -236,19 +167,12 @@ void CPKRenderer::RenderCPK2()
 
     glBegin(GL_QUADS);
 
-    if(options_->GetCPKMode()==2) {
-      for(std::vector<AtomEntry*>::const_iterator it=aelist.begin();it!=aelist.end();++it) {
-        RenderCPK2InnerLoop(*it,cx,cy,cz,gl_mmat,gl_pmat,gl_vp);
-      }
-    } else {
-      for(AtomEntryMap::const_iterator it=view_.atom_map.begin();it!=view_.atom_map.end();++it) {
-        RenderCPK2InnerLoop(&it->second,cx,cy,cz,gl_mmat,gl_pmat,gl_vp);
-      }
+    for(AtomEntryMap::const_iterator it=view_.atom_map.begin();it!=view_.atom_map.end();++it) {
+      Render3DSpritesInnerLoop(&it->second,cx,cy,cz,gl_mmat,gl_pmat,gl_vp);
     }
 
     glEnd();
     glPopAttrib();
-    glPopMatrix();
 
     Shader::Instance().PopProgram();
     Shader::Instance().UpdateState();
@@ -256,51 +180,4 @@ void CPKRenderer::RenderCPK2()
 #endif
 }
 
-void CPKRenderer::RenderCPK3()
-{
-#if OST_SHADER_SUPPORT_ENABLED
-  if(options_!= NULL){
-    std::vector<AtomEntry*> aelist = CPKOcclusion();
-
-    IndexedVertexArray cpk_va;
-    detail::PrebuildSphereEntry pre=detail::GetPrebuildSphere(options_->GetSphereDetail());
-    GLuint dlist;
-    dlist = glGenLists(1);
-    glNewList(dlist,GL_COMPILE);
-    glBegin(GL_TRIANGLES);
-    for(uint c=0;c<pre.ilist.size();c+=3) {
-      geom::Vec3 v0 = pre.vlist[pre.ilist[c+0]];
-      geom::Vec3 v1 = pre.vlist[pre.ilist[c+1]];
-      geom::Vec3 v2 = pre.vlist[pre.ilist[c+2]];
-      glNormal3v(v0.Data());
-      glVertex3v(v0.Data());
-      glNormal3v(v1.Data());
-      glVertex3v(v1.Data());
-      glNormal3v(v2.Data());
-      glVertex3v(v2.Data());
-    }
-    glEnd();
-    glEndList();
-
-    glEnable(GL_NORMALIZE);
-
-    for(std::vector<AtomEntry*>::const_iterator it=aelist.begin();it!=aelist.end();++it) {
-      geom::Vec3 pos = (*it)->atom.GetPos();
-      float rad = (*it)->vdwr;
-      glPushMatrix();
-      glColor3fv((*it)->color);
-      glTranslated(pos[0],pos[1],pos[2]);
-      glScaled(rad,rad,rad);
-      glCallList(dlist);
-      glPopMatrix();
-    }
-    glDisable(GL_NORMALIZE);
-  }
-#endif
-}
-
-CPKRenderer::~CPKRenderer() {
-
-}
-
 }}}
diff --git a/modules/gfx/src/impl/cpk_renderer.hh b/modules/gfx/src/impl/cpk_renderer.hh
index 81372f2d022127c94df0dfff1cd189cc5ae4a3c4..241602b88aef133f722751339e14cbf79ebb9e15 100644
--- a/modules/gfx/src/impl/cpk_renderer.hh
+++ b/modules/gfx/src/impl/cpk_renderer.hh
@@ -37,19 +37,15 @@ public:
   
   virtual void RenderPov(PovState& pov, const std::string& name);
 
-  virtual void Render(RenderPass pass=STANDARD_RENDER_PASS);
+  virtual void Render(RenderPass pass);
 
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
   virtual void SetOptions(RenderOptionsPtr& render_options);
   virtual RenderOptionsPtr GetOptions();
 
-  virtual ~CPKRenderer();
-
 private:
   void PrepareRendering(GfxView& view, IndexedVertexArray& va, bool is_sel);
-  std::vector<impl::AtomEntry*> CPKOcclusion();
-  void RenderCPK2();
-  void RenderCPK3();
+  void Render3DSprites();
 
   CPKRenderOptionsPtr options_;
 };
diff --git a/modules/gfx/src/impl/custom_renderer.cc b/modules/gfx/src/impl/custom_renderer.cc
index f8303fbedd3b486e14d40ef01f3b2c8f3aa4c32c..c9e2a2319ea70f3b4c51181ec688c4c964a35da3 100644
--- a/modules/gfx/src/impl/custom_renderer.cc
+++ b/modules/gfx/src/impl/custom_renderer.cc
@@ -79,6 +79,7 @@ void CustomRenderer::PrepareRendering(GfxView& view,
 
 void CustomRenderer::RenderPov(PovState& pov, const std::string& name)
 {
+  if(view_.atom_map.empty() && view_.bond_list.empty()) return;
   pov.write_merge_or_union(name);
   
   for (AtomEntryMap::const_iterator it=view_.atom_map.begin();it!=view_.atom_map.end();++it) {
diff --git a/modules/gfx/src/impl/debug_renderer.cc b/modules/gfx/src/impl/debug_renderer.cc
index 918117400b0b4a1e2039590e4739cbcfd26aa611..bd8f883f03174ce7807165ecf9deea8e251c9c8f 100644
--- a/modules/gfx/src/impl/debug_renderer.cc
+++ b/modules/gfx/src/impl/debug_renderer.cc
@@ -33,7 +33,7 @@ namespace gfx {
 using namespace impl;
 using namespace mol;
 
-DebugRenderer::DebugRenderer(BackboneTrace& trace): 
+DebugRenderer::DebugRenderer(BackboneTrace* trace): 
   TraceRendererBase(trace, 2), options_(new SlineRenderOptions()) {
   this->SetName("Debug");
 }
@@ -51,7 +51,7 @@ void DebugRenderer::PrepareRendering()
 
   for(NodeEntryListList::const_iterator ll_it=node_list_list_->begin();ll_it!=node_list_list_->end();++ll_it) {
 
-    Spline spl;
+    SplineEntryList spl;
     for(NodeEntryList::const_iterator it=(*ll_it).begin();it!=(*ll_it).end();++it) {
       int type=0;
       ResidueHandle resh = it->atom.GetResidue();
@@ -62,12 +62,13 @@ void DebugRenderer::PrepareRendering()
         type=2;
       }
 
-      SplineEntry& ee = spl.AddEntry(it->atom.GetPos(),it->direction,it->normal,
-                                     it->rad,it->color1,it->color2,type);
+      SplineEntry ee(it->atom.GetPos(),it->direction,it->normal,
+                     it->rad,it->color1,it->color2,type,it->id);
       ee.v1 = it->v1;
+      spl.push_back(ee);
     }
 
-    SplineEntryList sel = spl.Generate(std::max((unsigned int) 1,options_->GetSplineDetail()));
+    SplineEntryList sel = Spline::Generate(spl,std::max((unsigned int) 1,options_->GetSplineDetail()));
 
     SplineEntryList::const_iterator sit = sel.begin();
     geom::Vec3 ap = sit->position;
@@ -103,8 +104,6 @@ void DebugRenderer::PrepareRendering()
 #endif
 }
 
-void DebugRenderer::Render(){}
-
 bool DebugRenderer::CanSetOptions(RenderOptionsPtr& render_options){
  return render_options.get()->GetRenderMode()==RenderMode::SLINE;
 }
diff --git a/modules/gfx/src/impl/debug_renderer.hh b/modules/gfx/src/impl/debug_renderer.hh
index 206f592ddb3b7bcc4006d2a620f0a41488525e26..499a5d18c51703f5fcc3dca832a07d14adbaf398 100644
--- a/modules/gfx/src/impl/debug_renderer.hh
+++ b/modules/gfx/src/impl/debug_renderer.hh
@@ -30,10 +30,9 @@ namespace ost { namespace gfx { namespace impl {
 
 class DLLEXPORT_OST_GFX DebugRenderer: public TraceRendererBase {
 public:
-  DebugRenderer(BackboneTrace& trace);
+  DebugRenderer(BackboneTrace* trace);
 
   virtual void PrepareRendering();
-  virtual void Render();
 
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
   virtual void SetOptions(RenderOptionsPtr& render_options);
diff --git a/modules/gfx/src/impl/entity_detail.cc b/modules/gfx/src/impl/entity_detail.cc
index 572de5bb7e2b995fba33d204cf3e7745110a42f5..55fab9f53d8b7553dbb1d8bd4fa20ed3ea6327a2 100644
--- a/modules/gfx/src/impl/entity_detail.cc
+++ b/modules/gfx/src/impl/entity_detail.cc
@@ -16,19 +16,148 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+#include <ost/gfx/gl_helper.hh>
+#include <ost/gfx/scene.hh>
+#include <ost/gfx/color.hh>
+
 #include "entity_detail.hh"
 
+
 namespace ost { 
 
 using namespace mol;
 
 namespace gfx { namespace impl {
 
-  namespace {
+namespace {
+
+static const float default_radius=0.28;
+
+struct BlurQuadEntry
+{
+  float zdist;
+  geom::Vec3 p1,p2,p3,p4;
+  gfx::Color c1,c2,c3,c4;
+};
+
+struct BlurQuadEntryLess
+{
+  bool operator()(const BlurQuadEntry& e1, const BlurQuadEntry& e2)
+  {
+    // provides back-to-front sorting
+    return e1.zdist<e2.zdist;
+  }
+};
+
+} // anon ns
+
+void DoRenderBlur(BondEntryList& bl, float bf1, float bf2)
+{
+  // add blur for this particular orientation!
+  // don't use vertex array, but on-the-fly oriented and z-sorted quads
+  mol::Transform tf = Scene::Instance().GetTransform();
+
+  std::vector<BlurQuadEntry> bql;
+  for (BondEntryList::iterator it=bl.begin(); it!=bl.end();++it) {
+
+    if(!it->atom1 || !it->atom2) continue;
+
+    const geom::Vec3 p0=tf.Apply(it->atom1->atom.GetPos());
+    const geom::Vec3 p2=tf.Apply(it->atom2->atom.GetPos());
+    geom::Vec3 p1=(p0+p2)*0.5;
+
+    const geom::Vec3 q0=tf.Apply(it->pp1);
+    const geom::Vec3 q2=tf.Apply(it->pp2);
+    geom::Vec3 q1=(q0+q2)*0.5;
+
+    float ll0 = geom::Length2(p0-q0);
+    float ll1 = geom::Length2(p1-q1);
+    float ll2 = geom::Length2(p2-q2);
+
+    if(ll0<1e-2 && ll1<1e-2 && ll2<1e-2) continue;
+
+    float x0 = exp(-bf1*ll0);
+    float x1 = exp(-bf1*ll1);
+    float x2 = exp(-bf1*ll2);
+
+    BlurQuadEntry bqe;
+
+    bqe.zdist=0.25*(p0[2]+p2[2]+q0[2]+q2[2]);
+
+    // first half
+    bqe.p1 = p0;
+    bqe.p2 = p1;
+    bqe.p3 = q0;
+    bqe.p4 = q1;
+    bqe.c1 = it->atom1->color;
+    bqe.c2 = it->atom1->color;
+    bqe.c3 = it->atom1->color;
+    bqe.c4 = it->atom1->color;
+    bqe.c1[3] = x0;
+    bqe.c2[3] = x1;
+    bqe.c3[3]=x0*bf2;
+    bqe.c4[3]=x1*bf2;
+
+    bql.push_back(bqe);
+
+    // second half
+    bqe.p1 = p1;
+    bqe.p2 = p2;
+    bqe.p3 = q1;
+    bqe.p4 = q2;
+    bqe.c1 = it->atom2->color;
+    bqe.c2 = it->atom2->color;
+    bqe.c3 = it->atom2->color;
+    bqe.c4 = it->atom2->color;
+    bqe.c1[3] = x1;
+    bqe.c2[3] = x2;
+    bqe.c3[3]=x1*bf2;
+    bqe.c4[3]=x2*bf2;
+
+    bql.push_back(bqe);
+  }
+
+  std::sort(bql.begin(),bql.end(),BlurQuadEntryLess());
+
+  glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_LIGHTING_BIT);
+  glDisable(GL_LIGHTING);
+  glDisable(GL_CULL_FACE);
+  glDepthFunc(GL_LESS);
+  glDepthMask(GL_FALSE);
+  glMatrixMode(GL_MODELVIEW);
+  glPushMatrix();
+  glLoadIdentity();
+  glBegin(GL_QUADS);
+  glNormal3f(0.0,0.0,0.0);
+  for (std::vector<BlurQuadEntry>::const_iterator it=bql.begin();
+       it!=bql.end();++it) {
+    glColor4fv(it->c1);
+    glVertex3v(it->p1.Data());
+    glColor4fv(it->c2);
+    glVertex3v(it->p2.Data());
+    glColor4fv(it->c4);
+    glVertex3v(it->p4.Data());
+    glColor4fv(it->c3);
+    glVertex3v(it->p3.Data());
+  }
 
-    static const float default_radius=0.28;
+  glEnd();
+  glPopMatrix();
+  glPopAttrib();
+}
 
+void DoBlurSnapshot(BondEntryList& bl)
+{
+  for (BondEntryList::iterator it=bl.begin();
+       it!=bl.end();++it) {
+    if(it->atom1 && it->atom2) {
+      it->pp1=it->atom1->atom.GetPos();
+      it->pp2=it->atom2->atom.GetPos();
+    }
   }
+}
+
 
 void GfxView::Clear() 
 {
@@ -43,9 +172,9 @@ void GfxView::AddAtom(const AtomView& av)
   AtomEntry ae(a,default_radius,
                a.GetRadius(),
                GfxObj::Ele2Color(a.GetElement()));
-  atom_map[a.GetHandle().GetHashCode()]=ae;
+  atom_map[a.GetHashCode()]=ae;
   if(av.GetBondCount()==0) {
-    orphan_atom_list.push_back(a.GetHandle().GetHashCode());
+    orphan_atom_list.push_back(a.GetHashCode());
   }
 }
 
@@ -87,85 +216,41 @@ void GfxView::AddBond(const BondHandle& b)
 }
 
 
-void SplineEntry::ToQuat()
-{
-  // assert orthonormal system
-  // TODO: this seems broken
-  geom::Vec3 dir = geom::Normalize(direction);
-  geom::Vec3 norm0 = geom::Normalize(normal);
-  geom::Vec3 norm2 = geom::Cross(dir,norm0);
-  geom::Vec3 norm1 = geom::Cross(norm2,dir);
-  geom::Mat3 rmat(dir[0],norm1[0],norm2[0],
-                  dir[1],norm1[1],norm2[1],
-                  dir[2],norm1[2],norm2[2]);
-  
-  geom::Quat quat(rmat);
-  quat_value[0]=quat.w;
-  quat_value[1]=quat.x;
-  quat_value[2]=quat.y;
-  quat_value[3]=quat.z;
-}
-
-void SplineEntry::FromQuat() 
-{
-  /* 
-     assert orthornormal system since direction was
-     probably adjusted for curvature
-  */
-  // TODO: this seems broken
-  geom::Quat quat(quat_value[0],quat_value[1],quat_value[2],quat_value[3]);
-  geom::Mat3 rmat = quat.ToRotationMatrix();
-  geom::Vec3 norm0 = geom::Normalize(geom::Vec3(rmat(0,1),rmat(1,1),rmat(2,1)));
-  geom::Vec3 dir = geom::Normalize(direction);
-  geom::Vec3 norm2 = geom::Normalize(geom::Cross(dir,norm0));
-  normal = geom::Normalize(geom::Cross(norm2,dir));
-}
-
 ////////////////////////////
 
 
-Spline::Spline():
-  entry_list_()
-{}
-
-
-SplineEntry& Spline::AddEntry(const geom::Vec3& pos, const geom::Vec3& dir, const geom::Vec3& normal, float rad, const Color& c1, const Color& c2, int type)
-{
-  entry_list_.push_back(SplineEntry(pos,
-                                    geom::Normalize(dir),
-                                    geom::Normalize(normal),
-                                    rad,c1,c2,type));
-  entry_list_.back().ToQuat();
-  return entry_list_.back();
-}
-
 static int bsplineGen(float *x,float *y, int n, float yp1, float ypn, float *y2);
 static int bsplineGet(float *xa, float *ya, float *y2a, int n, float x, float *y);
 
 #define SPLINE_ENTRY_INTERPOLATE(COMPONENT)             \
     for(int c=0;c<size;++c) {                           \
-      yc[c]=entry_list_[c]. COMPONENT ;                 \
+      yc[c]=entry_list.at(c). COMPONENT ;		\
     }                                                   \
     bsplineGen(xp,yp,size,1.0e30,1.0e30,y2p);           \
-    for(int c=0;c<size;++c) {                           \
+    for(int c=0;c<size-1;++c) {                         \
       for(int d=0;d<nsub;++d) {                         \
         float u=static_cast<float>(c*nsub+d)*i_nsub;    \
         float v=0.0;                                    \
         bsplineGet(xp,yp,y2p,size,u,&v);                \
-        sublist[c*nsub+d]. COMPONENT = v;               \
+        sublist.at(c*nsub+d). COMPONENT = v;		\
       }                                                 \
+      float u=static_cast<float>((size-1)*nsub)*i_nsub;	\
+      float v=0.0;                                      \
+      bsplineGet(xp,yp,y2p,size,u,&v);                  \
+      sublist.at((size-1)*nsub). COMPONENT = v;		\
     }                                                   
 
-SplineEntryList Spline::Generate(int nsub) const
+SplineEntryList Spline::Generate(const SplineEntryList& entry_list, int nsub, uint color_blend_mode)
 {
   if(nsub<=0) {
-    return entry_list_;
+    return entry_list;
   }
-  int size=entry_list_.size();
-  if (size==0) {
-    return entry_list_;
+  int size=entry_list.size();
+  if (size<2) {
+    return entry_list;
   }
-  int ipsize=(size)*nsub;
+  // we want to go to the last point, but not beyond
+  int ipsize=(size-1)*nsub+1;
   float i_nsub=1.0/static_cast<float>(nsub);
   std::vector<float> xc(size);
   std::vector<float> yc(size);
@@ -181,127 +266,127 @@ SplineEntryList Spline::Generate(int nsub) const
     xc[c]=static_cast<float>(c);
   }
 
+  LOG_DEBUG("SplineGenerate: interpolating spline entry components");
+  
   // create sublist with enough entries
   SplineEntryList sublist(ipsize);
 
-  // interpolate internal quaternion and color
-  for(int k=0;k<4;++k) {
-    SPLINE_ENTRY_INTERPOLATE(quat_value[k]);
-    SPLINE_ENTRY_INTERPOLATE(color1[k]);
-    SPLINE_ENTRY_INTERPOLATE(color2[k]);
+  // interpolate color
+  if(color_blend_mode==0) {
+    for(int k=0;k<4;++k) {
+      SPLINE_ENTRY_INTERPOLATE(color1[k]);
+      SPLINE_ENTRY_INTERPOLATE(color2[k]);
+    }
+  } else {
+    for(int c=0;c<size-1;++c) {
+      for(int k=0;k<4;++k) {
+        int d=0;
+        for(;d<nsub/2;++d) {
+          sublist.at(c*nsub+d).color1[k]=entry_list[c].color1[k];
+          sublist.at(c*nsub+d).color2[k]=entry_list[c].color2[k];
+        }
+        for(;d<nsub;++d) {
+          sublist.at(c*nsub+d).color1[k]=entry_list[c+1].color1[k];
+          sublist.at(c*nsub+d).color2[k]=entry_list[c+1].color2[k];
+        }
+      }
+    }
   }
 
+  // interpolate position and helper vectors
   for(int k=0;k<3;++k) {
     SPLINE_ENTRY_INTERPOLATE(position[k]);
-    //SPLINE_ENTRY_INTERPOLATE(v0[k]);
-    SPLINE_ENTRY_INTERPOLATE(v1[k]);
-    //SPLINE_ENTRY_INTERPOLATE(v2[k]);
+    SPLINE_ENTRY_INTERPOLATE(normal[k]);
   }
 
   SPLINE_ENTRY_INTERPOLATE(rad);
 
-  // assign direction and normal
-  // entity trace has the same algorithm
-
-  geom::Vec3 p0 = sublist[0].position;
-  geom::Vec3 p1 = sublist[1].position;
-  geom::Vec3 p2 = sublist[2].position;
-  // normal of 0 is set at the end
-  sublist[0].direction=geom::Normalize(p1-p0);
-  sublist[0].v1=geom::Normalize(sublist[0].v1);
-  geom::Vec3 orth = geom::Cross(sublist[0].direction,sublist[0].v1);
-  sublist[0].v0 = geom::Normalize(geom::Cross(orth,sublist[0].direction));
+  LOG_DEBUG("SplineGenerate: assigning direction and normal components");
 
-  // reference normal to avoid twisting
-  //geom::Vec3 nref=geom::Normalize(geom::Cross(p0-p1,p2-p1));
+  // assign direction and then re-assign normal
+  geom::Vec3 p0 = sublist.at(0).position;
+  geom::Vec3 p1 = sublist.at(1).position;
+  geom::Vec3 p2 = sublist.size()>2 ? sublist.at(2).position : p1+p1-p0;
+  sublist.at(0).direction=geom::Normalize(p1-p0);
   unsigned int i=1;
   for(;i<sublist.size()-1;++i) {
     geom::Vec3 p10 = p0-p1;
     geom::Vec3 p12 = p2-p1;
-    // correction for perfectly aligned consecutive directions
-    if(p10==-p12 || p10==p12) p12+=geom::Vec3(0.001,0.001,0.001);
-    sublist[i].normal=geom::Normalize(geom::Cross(p10,p12));
-    // paranoid error checking due to occasional roundoff troubles
-    float cosw = geom::Dot(geom::Normalize(p10),geom::Normalize(p12));
-    cosw = std::min(float(1.0),std::max(float(-1.0),cosw));
-    float omega=0.5*acos(cosw);
-    orth=geom::AxisRotation(sublist[i].normal, -omega)*p12;
-    sublist[i].direction=geom::Normalize(geom::Cross(sublist[i].normal,orth));
-    // twist avoidance
-    sublist[i].v1=geom::Normalize(sublist[i].v1);
-    orth = geom::Cross(sublist[i].direction,sublist[i].v1);
-    sublist[i].v0 = geom::Normalize(geom::Cross(orth,sublist[i].direction));
-    if(geom::Dot(sublist[i-1].v0,sublist[i].v0)<0.0) {
-      sublist[i].v0=-sublist[i].v0;
-      //sublist[i].nflip = !sublist[i].nflip;
-    }
-
-    // avoid twisting
-    //if(geom::Dot(sublist[i].normal,nref)<0.0) sublist[i].normal=-sublist[i].normal;
-    //nref=sublist[i].normal;
-    // skip over shift for the last iteration
+    geom::Vec3 dir=geom::Normalize(p2-p0);
+    sublist.at(i).direction=dir;
+    geom::Vec3 orth=geom::Normalize(geom::Cross(dir,sublist[i].normal));
+    geom::Vec3 norm=geom::Normalize(geom::Cross(orth,dir));
+    sublist[i].normal=norm;
     if(i==sublist.size()-2) break;
     // shift to i+1 for next iteration
-    p0 = sublist[i].position;
-    p1 = sublist[i+1].position;
-    p2 = sublist[i+2].position;
+    p0 = sublist.at(i).position;
+    p1 = sublist.at(i+1).position;
+    p2 = sublist.at(i+2).position;
   }
-  // assign remaining ones
-  sublist[0].normal=sublist[1].normal;
+  sublist[0].normal=sublist[0].normal;
   sublist[i+1].direction=geom::Normalize(p2-p1);
   sublist[i+1].normal=sublist[i].normal;
-  sublist[i+1].v1=geom::Normalize(sublist[i+1].v1);
-  orth = geom::Cross(sublist[i+1].direction,sublist[i+1].v1);
-  sublist[i+1].v0 = geom::Normalize(geom::Cross(orth,sublist[i+1].direction));
-
-  // hack
-  // TODO: merge this with above routine
-  for(unsigned int i=0;i<sublist.size()-1;++i) {
-    sublist[i].normal = sublist[i].v0;
-  }
 
+
+  LOG_DEBUG("SplineGenerate: assigning non-interpolated entry components");
   // finally the non-interpolated type
   // with some tweaks for proper strand rendering
-  for(int c=0;c<size;++c) {
+  // part of this probably belongs into cartoon renderer
+  for(int c=0;c<size-1;++c) {
+    int type1=entry_list[c].type;
+    int type2=entry_list[std::min(c+1,size-1)].type;
     for(int d=0;d<nsub;++d) {
-      sublist[c*nsub+d].type=entry_list_[c].type;
-      int type1=entry_list_[c].type;
-      int type2=entry_list_[std::min(c+1,size-1)].type;
-      //int type0=entry_list_[std::max(0,c-1)].type;
-      if(type1==2 && type2==3) {
-        type1=2;
-        type2=2;
-      } else if(type1==3) {
-        type1=4;
-        // uncommenting this causes the strand arrows
-        // to blend into a tip instead of the n+1
-        // profile - gives visual artefacts
-        //type2=3;
-      }
-      sublist[c*nsub+d].type1=type1;
-      sublist[c*nsub+d].type2=type2;
-      sublist[c*nsub+d].frac=float(d)/float(nsub);
+      sublist.at(c*nsub+d).type=entry_list[c].type;
+      sublist.at(c*nsub+d).type1=type1;
+      sublist.at(c*nsub+d).type2=type2;
+      float frac=float(d)/float(nsub);
+      sublist.at(c*nsub+d).frac=frac;
     }
-  }                                                   
+  }
+  int type1=entry_list.back().type;
+  int type2=type1;
+  sublist.back().type=entry_list.back().type;
+  sublist.back().type1=type1;
+  sublist.back().type2=type2;
+  sublist.back().frac=0.0;
+
+  float insub=1.0/static_cast<float>(nsub);
+  for(size_t c=0;c<sublist.size();++c) {
+    sublist[c].running_length=static_cast<float>(c)*insub;
+  }
+
+  // the id for selections, shifted by one half
+  for(int c=0;c<size-1;++c) {
+    int d=0;
+    for(;d<nsub/2;++d) {
+      sublist.at(c*nsub+d).id=entry_list[c].id;
+    }
+    for(;d<nsub;++d) {
+      sublist.at(c*nsub+d).id=entry_list[c+1].id;
+    }
+  }
+  sublist.back().id=entry_list.back().id;
 
   // the nflip flags for helices for correct inside/outside assignment
-  int c=0;
+  // this probably belongs into cartoon renderer
+  LOG_DEBUG("SplineGenerate: setting nflip flags for helices");
+  unsigned int c=0;
   bool nflip=false;
-  while(c<nsub*size-1) {
+  while(c<sublist.size()-1) {
     int cstart=c;
-    if(sublist[c].type==1 && sublist[c+1].type==1) {
-      geom::Vec3 n = geom::Normalize(geom::Cross(sublist[c].normal,
-                                                 sublist[c].direction));
-      geom::Vec3 p0 = sublist[c].position+n;
-      geom::Vec3 q0 = sublist[c].position-n;
+    if(sublist.at(c).type==1 && sublist.at(c+1).type==1) {
+      geom::Vec3 n = geom::Normalize(geom::Cross(sublist.at(c).normal,
+                                                 sublist.at(c).direction));
+      geom::Vec3 p0 = sublist.at(c).position+n;
+      geom::Vec3 q0 = sublist.at(c).position-n;
       float psum=0.0;
       float qsum=0.0;
       ++c;
-      while(c<nsub*size && sublist[c].type==1) {
-        n = geom::Normalize(geom::Cross(sublist[c].normal,
-                                        sublist[c].direction));
-        geom::Vec3 p1 = sublist[c].position+n;
-        geom::Vec3 q1 = sublist[c].position-n;
+      while(c<sublist.size() && sublist.at(c).type==1) {
+        n = geom::Normalize(geom::Cross(sublist.at(c).normal,
+                                        sublist.at(c).direction));
+        geom::Vec3 p1 = sublist.at(c).position+n;
+        geom::Vec3 q1 = sublist.at(c).position-n;
         psum+=Length(p1-p0);
         qsum+=Length(q1-q0);
         p0=p1;
@@ -310,8 +395,8 @@ SplineEntryList Spline::Generate(int nsub) const
       }
       
       nflip = qsum>psum;
-      for(int cc=cstart;cc<c;++cc) {
-        sublist[cc].nflip=nflip;
+      for(unsigned int cc=cstart;cc<c;++cc) {
+        sublist.at(cc).nflip=nflip;
       }
     } else {
       ++c;
@@ -319,6 +404,8 @@ SplineEntryList Spline::Generate(int nsub) const
   }
   sublist.back().nflip=nflip;
 
+  LOG_DEBUG("SplineGenerate: done");
+
   // done
   return sublist;
 }
diff --git a/modules/gfx/src/impl/entity_detail.hh b/modules/gfx/src/impl/entity_detail.hh
index 7cf19d622fda4ad015caca9d3643cbb152f4793e..2ae0a848f14c3e7c711f67dc31e436969a4a22d0 100644
--- a/modules/gfx/src/impl/entity_detail.hh
+++ b/modules/gfx/src/impl/entity_detail.hh
@@ -70,6 +70,9 @@ struct DLLEXPORT_OST_GFX BondEntry
 
 typedef std::vector<BondEntry> BondEntryList;
 
+void DoRenderBlur(BondEntryList& bl, float bf1, float bf2);
+void DoBlurSnapshot(BondEntryList& bl);
+
 class DLLEXPORT_OST_GFX GfxView {
 public:
   void Clear();
@@ -90,6 +93,7 @@ struct DLLEXPORT_OST_GFX NodeEntry {
   float rad;
   geom::Vec3 v0,v1,v2; // helper vectors
   bool nflip;
+  int id;
 };
 
 typedef std::vector<NodeEntry> NodeEntryList;
@@ -115,7 +119,16 @@ struct DLLEXPORT_OST_GFX SplineEntry {
     color1(1.0,1.0,1.0,1.0),
     color2(1.0,1.0,1.0,1.0),
     rad(1.0),
-    type(0)
+    type(0),
+    type1(0),
+    type2(0),
+    frac(0.0),
+    running_length(0.0),
+    v0(1.0,0.0,0.0),
+    v1(0.0,1.0,0.0),
+    v2(0.0,0.0,1.0),
+    nflip(false),
+    id(-1)
   {
   }
   SplineEntry(const geom::Vec3& p, 
@@ -123,25 +136,21 @@ struct DLLEXPORT_OST_GFX SplineEntry {
               const geom::Vec3& n,
               float r,
               const Color& c1, const Color& c2,
-              int t):
+              unsigned int t, int i):
     position(p),direction(d),normal(n),color1(c1),color2(c2),rad(r),type(t),
-    type1(t),type2(t),frac(0.0),v0(),v1(),v2(),nflip(false)
+    type1(t),type2(t),frac(0.0),running_length(0.0),v0(),v1(),v2(),nflip(false),id(i)
   {
   }
 
-  void ToQuat();
-
-  void FromQuat();
-
   geom::Vec3 position,direction,normal;
   Color color1, color2;
-  float quat_value[4];
   float rad;
-  int type;
-  int type1, type2;
-  float frac;
+  unsigned int type;
+  unsigned int type1, type2;
+  float frac,running_length;
   geom::Vec3 v0,v1,v2; // helper vectors
   bool nflip;
+  int id;
 };
   
 typedef std::vector<SplineEntry> SplineEntryList;
@@ -149,20 +158,7 @@ typedef std::vector<SplineEntryList> SplineEntryListList;
 
 class DLLEXPORT_OST_GFX Spline {
 public:
-
-public:
-  // ctor
-  Spline();
-
-  // add entry at a given position, with direction and normal vectors
-  SplineEntry& AddEntry(const geom::Vec3& pos, const geom::Vec3& dir, 
-                        const geom::Vec3& normal, float r, const Color& col1, 
-                        const Color& col2, int type);
-
-  SplineEntryList Generate(int nsub) const;
-
-private:
-  SplineEntryList entry_list_;
+  static SplineEntryList Generate(const SplineEntryList& entry_list,int nsub,uint color_blend_mode=0);
 };
 
 }}} // ns
diff --git a/modules/gfx/src/impl/entity_renderer.hh b/modules/gfx/src/impl/entity_renderer.hh
index ba54403ef0a2a1c618d7359400e51d9d2ecfabb5..4b467c011087587a76a2b56343faacd240a527b4 100644
--- a/modules/gfx/src/impl/entity_renderer.hh
+++ b/modules/gfx/src/impl/entity_renderer.hh
@@ -24,8 +24,8 @@
 */
 
 
-#if defined(GetProp)
-#undef GetProp
+#if defined(GetAtomProps)
+#undef GetAtomProps
 #endif
 #include <vector>
 
@@ -56,11 +56,11 @@
 namespace ost { namespace gfx { namespace impl {
 
 typedef enum {
-  DIRTY_VIEW   =1,
-  DIRTY_VA     =2
+  DIRTY_VIEW   = 0x1,
+  DIRTY_VA     = 0x2
 } DirtyFlag;
 
-typedef char DirtyFlags;
+typedef unsigned int DirtyFlags;
 
 /// \internal
 class DLLEXPORT_OST_GFX EntityRenderer {
@@ -118,7 +118,7 @@ public:
   /// 
   /// The rendering buffers and vertex arrays should be prepared in 
   /// PrepareRendering()
-  virtual void Render(RenderPass pass=STANDARD_RENDER_PASS);
+  virtual void Render(RenderPass pass);
   
   ///\brief povray rendering call
   virtual void RenderPov(PovState& pov, const std::string& name);
@@ -160,6 +160,8 @@ public:
   void FlagPositionsDirty();
 
   void Debug(unsigned int flags);
+
+  IndexedVertexArray& VA() {return va_;}
 protected:
   virtual void SetName(const String& name);
 
@@ -178,12 +180,13 @@ protected:
   DirtyFlags            sel_state_;
   DirtyFlags            state_;
   unsigned int          debug_flags_;
+  float                 opacity_;
 };
 
 //Simplify color ops
 struct ByElementGetCol {
   Color ColorOfAtom(mol::AtomHandle& atom) const{
-    return GfxObj::Ele2Color(atom.GetAtomProps().element);
+    return GfxObj::Ele2Color(atom.GetElement());
   }
 };
 
diff --git a/modules/gfx/src/impl/glx_offscreen_buffer.cc b/modules/gfx/src/impl/glx_offscreen_buffer.cc
index 0956667657532d09e3caf8bf1e80dc7625ebd163..1edb5773f663d36151e846ed3ce1bd08900bed66 100644
--- a/modules/gfx/src/impl/glx_offscreen_buffer.cc
+++ b/modules/gfx/src/impl/glx_offscreen_buffer.cc
@@ -107,7 +107,9 @@ OffscreenBuffer::OffscreenBuffer(unsigned int width, unsigned int height, const
 OffscreenBuffer::~OffscreenBuffer()
 {
   if(valid_) {
+    LOG_DEBUG("offscreen buffer: glXDestroyContext()");
     glXDestroyContext(dpy_, context_);
+    LOG_DEBUG("offscreen buffer: glXDestroyPbuffer()");
     glXDestroyPbuffer(dpy_, pbuffer_);
   }
 }
diff --git a/modules/gfx/src/impl/line_trace_renderer.cc b/modules/gfx/src/impl/line_trace_renderer.cc
index b0279b71f0f274f101757c0e2c321fc102e4c3e2..3e89af0cdb2678c545f18738e15e4be718d317e3 100644
--- a/modules/gfx/src/impl/line_trace_renderer.cc
+++ b/modules/gfx/src/impl/line_trace_renderer.cc
@@ -17,15 +17,45 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 
+/*
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #include "line_trace_renderer.hh"
 #include <ost/gfx/entity.hh>
 
 namespace ost { namespace gfx { namespace impl {
 
-LineTraceRenderer::LineTraceRenderer(BackboneTrace& trace): 
-  TraceRendererBase(trace, 1), options_(new LineTraceRenderOptions())
+namespace {
+
+void add_atom_and_bond(mol::AtomHandle atom1,mol::AtomHandle atom2, AtomEntryMap& amap, BondEntryList& blist)
+{
+  AtomEntry ae1(atom1,0.0,0.0,Color(1,1,1));
+  amap[atom1.GetHashCode()]=ae1;
+  AtomEntry ae2(atom2,0.0,0.0,Color(1,1,1));
+  amap[atom2.GetHashCode()]=ae2;
+  blist.push_back(BondEntry(mol::BondHandle(),0.0f,
+                            &amap[atom1.GetHashCode()],
+                            &amap[atom2.GetHashCode()]));
+}
+
+}
+
+
+LineTraceRenderer::LineTraceRenderer(BackboneTrace* trace): 
+  TraceRendererBase(trace, 1), 
+  options_(new LineTraceRenderOptions()),
+  amap_(),
+  blist_()
 {
   this->SetName("Fast Trace");
+
+  for (int node_list=0; node_list<trace->GetListCount(); ++node_list) {
+    const NodeEntryList& nl=trace->GetList(node_list);
+    for (unsigned int i=0; i<nl.size()-1;++i) {
+      add_atom_and_bond(nl[i].atom,nl[i+1].atom,amap_,blist_);
+    }
+  }
 }
 
 void LineTraceRenderer::PrepareRendering() 
@@ -36,15 +66,15 @@ void LineTraceRenderer::PrepareRendering()
   sel_va_.Clear();
   sel_va_.SetOutlineWidth(options_->GetLineWidth()+3.0);
   if (this->HasSelection()) {
-    this->PrepareRendering(sel_subset_, sel_va_, true);
+    //this->PrepareRendering(sel_subset_, sel_va_, true);
+    this->PrepareRendering(trace_subset_, sel_va_, true);
     sel_va_.SetLineWidth(options_->GetLineWidth()+4.0);    
   }
 }
 
-void LineTraceRenderer::PrepareRendering(TraceSubset& trace_subset,
+void LineTraceRenderer::PrepareRendering(const BackboneTrace& trace_subset,
                                          IndexedVertexArray& va, bool is_sel)
 {
-
   const Color& sel_clr=this->GetSelectionColor();
   if(options_!=NULL){
     va.Clear();
@@ -56,52 +86,52 @@ void LineTraceRenderer::PrepareRendering(TraceSubset& trace_subset,
     va.SetLineWidth(options_->GetLineWidth());
     va.SetPointSize(options_->GetLineWidth());
     va.SetAALines(options_->GetAALines());
-    for (int node_list=0; node_list<trace_subset.GetSize(); ++node_list) {
-      const NodeListSubset& nl=trace_subset[node_list];
-
-      if (nl.GetSize()==2) {
-        VertexID p0, p1;
-        if (nl.AtStart()==0) {
-          p0=va.Add(nl[0].atom.GetPos(), geom::Vec3(),
-                    is_sel ? sel_clr : nl[0].color1);
-          p1=va.Add((nl[0].atom.GetPos()+nl[1].atom.GetPos())/2, 
-                    geom::Vec3(), is_sel ? sel_clr : nl[1].color1);
-        } else {
-          p0=va.Add((nl[0].atom.GetPos()+nl[1].atom.GetPos())/2, 
-                    geom::Vec3(), is_sel ? sel_clr : nl[0].color1);
-          p1=va.Add(nl[1].atom.GetPos(), 
-                    geom::Vec3(), is_sel ? sel_clr : nl[1].color1);
+    if(is_sel) {
+      for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+        const NodeEntryList& nl=trace_subset.GetList(node_list);
+        if(nl.size()<1) continue;
+        for(unsigned int i=0;i<nl.size();++i) {
+          const NodeEntry& entry=nl[i];
+          if(sel_.FindAtom(entry.atom).IsValid()) {
+            geom::Vec3 apos = entry.atom.GetPos();
+            VertexID p0=va.Add(apos, geom::Vec3(),sel_clr);
+            if(i>0) {
+              VertexID p1 =va.Add(apos+0.5*(nl[i-1].atom.GetPos()-apos), geom::Vec3(), sel_clr);
+              va.AddLine(p0, p1);
+            }
+            if(i<nl.size()-1) {
+              VertexID p1 =va.Add(apos+0.5*(nl[i+1].atom.GetPos()-apos), geom::Vec3(), sel_clr);
+              va.AddLine(p0, p1);
+            }
+          }
         }
-        va.AddLine(p0, p1);        
-        continue;
-      }
-      if (nl.GetSize()<3) {
-        continue;
-      }
-      VertexID p0;      
-      if (nl.AtStart()==0) {
-        p0=va.Add(nl[0].atom.GetPos(), geom::Vec3(),
-                  is_sel ? sel_clr : nl[0].color1);
-      } else {
-        p0=va.Add((nl[0].atom.GetPos()+nl[1].atom.GetPos())/2, 
-                  geom::Vec3(), is_sel ? sel_clr : nl[0].color1);
-      }
-      for (int i=1; i<nl.GetSize()-1;++i) {
-        const NodeEntry& entry=nl[i];
-        VertexID p1 =va.Add(entry.atom.GetPos(), geom::Vec3(), 
-                            is_sel ? sel_clr : entry.color1);
-        va.AddLine(p0, p1);
-        p0=p1;
       }
-      const NodeEntry& entry=nl[nl.GetSize()-1];      
-      if (nl.AtEnd()==0) {
+    } else {
+      for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+        const NodeEntryList& nl=trace_subset.GetList(node_list);
+        
+        if (nl.size()<2) continue;
+        
+        VertexID p0=va.Add(nl[0].atom.GetPos(), geom::Vec3(),
+                           nl[0].color1);
+        for (unsigned int i=1; i<nl.size()-1;++i) {
+          const NodeEntry& entry=nl[i];
+          VertexID p1 =va.Add(entry.atom.GetPos(), geom::Vec3(), 
+                              entry.color1);
+          va.AddLine(p0, p1);
+          p0=p1;
+#if 0
+          VertexID p2 =va.Add(entry.atom.GetPos()+entry.direction, geom::Vec3(), 
+                              Color(1,0,0));
+          VertexID p3 =va.Add(entry.atom.GetPos()+entry.normal, geom::Vec3(), 
+                              Color(0,1,1));
+          va.AddLine(p0,p2);
+          va.AddLine(p0,p3);
+#endif
+        }
+        const NodeEntry& entry=nl.back();
         VertexID p1 =va.Add(entry.atom.GetPos(), geom::Vec3(), 
-                            is_sel ? sel_clr : entry.color1);
-        va.AddLine(p0, p1);                            
-      } else {
-        geom::Vec3 p=(entry.atom.GetPos()+nl[nl.GetSize()-2].atom.GetPos())*0.5;
-        VertexID p1 =va.Add(p, geom::Vec3(), 
-                            is_sel ? sel_clr : entry.color1);
+                            entry.color1);
         va.AddLine(p0, p1);
       }
     }
@@ -110,11 +140,6 @@ void LineTraceRenderer::PrepareRendering(TraceSubset& trace_subset,
   state_=0;
 }
 
-void LineTraceRenderer::Render()
-{
-
-}
-
 bool LineTraceRenderer::CanSetOptions(RenderOptionsPtr& render_options)
 {
  return render_options.get()->GetRenderMode()==RenderMode::LINE_TRACE;
diff --git a/modules/gfx/src/impl/line_trace_renderer.hh b/modules/gfx/src/impl/line_trace_renderer.hh
index d4b904e0fa478286e1bcb7f47e677f6772051344..ce42fc004dd6c70b444c04d7bea50d751dedb330 100644
--- a/modules/gfx/src/impl/line_trace_renderer.hh
+++ b/modules/gfx/src/impl/line_trace_renderer.hh
@@ -16,6 +16,11 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+/*
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #ifndef OST_GFX_IMPL_LINE_TRACE_RENDERER_HH
 #define OST_GFX_IMPL_LINE_TRACE_RENDERER_HH
 
@@ -36,12 +41,11 @@ using namespace impl;
 /// \internal
 class DLLEXPORT_OST_GFX LineTraceRenderer: public TraceRendererBase {
 public:
-  LineTraceRenderer(BackboneTrace& trace);
+  LineTraceRenderer(BackboneTrace* trace);
 
   virtual void PrepareRendering();
-  virtual void PrepareRendering(TraceSubset& trace_subset, 
+  virtual void PrepareRendering(const BackboneTrace& trace_subset, 
                                 IndexedVertexArray& va, bool is_sel);
-  virtual void Render();
 
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
   virtual void SetOptions(RenderOptionsPtr& render_options);
@@ -49,8 +53,12 @@ public:
 
   virtual ~LineTraceRenderer();
 
+  BondEntryList& GetBondEntryList() {return blist_;}
+
 private:
   LineTraceRenderOptionsPtr  options_;
+  AtomEntryMap amap_;   // for blur rendering
+  BondEntryList blist_; // dito
 };
 
 }}}
diff --git a/modules/gfx/src/impl/scene_fx.cc b/modules/gfx/src/impl/scene_fx.cc
new file mode 100644
index 0000000000000000000000000000000000000000..f47e997ae081a06f7e95277c229a372c1e50cb32
--- /dev/null
+++ b/modules/gfx/src/impl/scene_fx.cc
@@ -0,0 +1,738 @@
+#include <boost/random.hpp>
+
+#include "scene_fx.hh"
+
+#include <ost/log.hh>
+
+#include <ost/gfx/gfx_node.hh>
+#include <ost/gfx/shader.hh>
+#include <ost/gfx/scene.hh>
+
+#if !GL_VERSION_3_0
+#warning using OpenGL 2.0 interface
+#endif
+
+namespace ost { namespace gfx { namespace impl {
+
+namespace {
+  boost::mt19937 RandomGenerator(time(NULL));
+  boost::uniform_01<boost::mt19937> UniformRandom(RandomGenerator);
+}
+
+SceneFX& SceneFX::Instance()
+{
+  static SceneFX inst;
+  return inst;
+}
+
+SceneFX::SceneFX():
+  shadow_flag(false),
+  shadow_quality(1),
+  shadow_weight(1.0),
+  depth_dark_flag(false),
+  depth_dark_factor(1.0),
+  amb_occl_flag(false),
+  amb_occl_factor(1.0),
+  amb_occl_mode(1),
+  amb_occl_quality(1),
+  use_beacon(false),
+  beacon(),
+  scene_tex_id_(),
+  depth_tex_id_(),
+  shadow_tex_id_(),
+  shadow_tex_mat_(),
+  occl_tex_id_(),
+  dark_tex_id_(),
+  norm_tex_id_(),
+  kernel_tex_id_(),
+  kernel_size_(0),
+  kernel2_tex_id_(),
+  kernel2_size_(0),
+  scene_tex2_id_(),
+  norm_tex2_id_(),
+  scene_fb_(),
+  scene_rb_(),
+  depth_rb_(),
+  use_fb_(false)
+{}
+
+SceneFX::~SceneFX()
+{}
+
+void SceneFX::Setup()
+{
+  if(!OST_GL_VERSION_2_0) return;
+  LOG_DEBUG("SceneFX: setup");
+
+  glGenTextures(1,&scene_tex_id_);
+  glGenTextures(1,&depth_tex_id_);
+  glGenTextures(1,&shadow_tex_id_);
+  glGenTextures(1,&occl_tex_id_);
+  glGenTextures(1,&dark_tex_id_);
+  glGenTextures(1,&norm_tex_id_);
+  glGenTextures(1,&kernel_tex_id_);
+  glGenTextures(1,&kernel2_tex_id_);
+
+#if GL_VERSION_3_0
+  glGenFramebuffers(1,&scene_fb_);
+  glGenRenderbuffers(1,&scene_rb_);
+  glGenRenderbuffers(1,&depth_rb_);
+#else
+  glGenFramebuffersEXT(1,&scene_fb_);
+  glGenRenderbuffersEXT(1,&scene_rb_);
+  glGenRenderbuffersEXT(1,&depth_rb_);
+#endif
+  glGenTextures(1,&scene_tex2_id_);
+  glGenTextures(1,&norm_tex2_id_);
+
+  glBindTexture(GL_TEXTURE_2D, scene_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, depth_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, shadow_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, occl_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, dark_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, norm_tex_id_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_1D, kernel_tex_id_);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  std::vector<GLfloat> tmp;
+  for(int u=-20;u<=20;++u) {
+    for(int v=-20;v<=20;++v) {
+      if(UniformRandom()<0.1) {
+        // norm to 1
+        float x = static_cast<float>(u+20)*0.025;
+        float y = static_cast<float>(v+20)*0.025;
+        tmp.push_back(x);
+        tmp.push_back(y);
+        tmp.push_back(0.0);
+        tmp.push_back(0.0);
+      }
+    }
+  }
+
+  kernel_size_=tmp.size()/4;
+  glTexImage1D(GL_TEXTURE_1D,0,4,kernel_size_,0,GL_RGBA, GL_FLOAT, &tmp[0]);
+
+  glBindTexture(GL_TEXTURE_1D, kernel2_tex_id_);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  
+  // depth darkening kernel
+  tmp.clear();
+  for(int u=-5;u<=5;++u) {
+    for(int v=-5;v<=5;++v) {
+      if(UniformRandom()<0.5) {
+        // norm to -1 ... 1
+        float x = static_cast<float>(u)*0.2;
+        float y = static_cast<float>(v)*0.2;
+        // gaussian kernel with sigma
+        float v = exp((-x*x-y*y)*0.5);
+        // norml to 0 ... 1
+        tmp.push_back(x*0.5+0.5);
+        tmp.push_back(y*0.5+0.5);
+        tmp.push_back(v);
+        tmp.push_back(0.0);
+      }
+    }
+  }
+
+  kernel2_size_=tmp.size()/4;
+  glTexImage1D(GL_TEXTURE_1D,0,4,kernel2_size_,0,GL_RGBA, GL_FLOAT, &tmp[0]);
+}
+
+void SceneFX::Resize(unsigned int w, unsigned int h)
+{
+#if 0
+  glBindTexture(GL_TEXTURE_2D, scene_tex2_id_);
+  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
+  glBindTexture(GL_TEXTURE_2D, norm_tex2_id_);
+  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
+  glBindTexture(GL_TEXTURE_2D, 0);
+
+  glBindFramebuffer(GL_FRAMEBUFFER, scene_fb_);
+
+  glBindRenderbuffer(GL_RENDERBUFFER, depth_rb_);
+  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,w,h);
+  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb_);
+  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, scene_tex2_id_, 0);
+  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, norm_tex2_id_, 0);
+
+  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+
+  if(status!=GL_FRAMEBUFFER_COMPLETE) {
+    use_fb_=false;
+    LOG_VERBOSE("SceneFX: framebuffer error code " << status);
+  } else {
+    use_fb_=true;
+  }
+
+  glBindRenderbuffer(GL_RENDERBUFFER, 0);
+  glBindFramebuffer(GL_FRAMEBUFFER, 0);
+#endif
+}
+
+void SceneFX::Preprocess() 
+{
+  if(!OST_GL_VERSION_2_0) return;
+  if(use_fb_) {
+#if GL_VERSION_3_0
+    glBindFramebuffer(GL_FRAMEBUFFER, scene_fb_);
+#else
+    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, scene_fb_);
+#endif
+  }
+}
+
+void SceneFX::Postprocess()
+{
+  if(!OST_GL_VERSION_2_0) return;
+  if(use_fb_) {
+#if GL_VERSION_3_0
+    glBindFramebuffer(GL_FRAMEBUFFER, 0);
+#else
+    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+#endif
+  }
+
+  if(!shadow_flag && !amb_occl_flag && !depth_dark_flag && !use_beacon) {
+    // no postprocessing is needed
+    return;
+  }
+
+  Viewport vp=Scene::Instance().GetViewport();
+
+  if(!use_fb_) {
+    // grab color buffer
+    glBindTexture(GL_TEXTURE_2D, scene_tex_id_);
+    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, vp.x, vp.y, vp.width, vp.height, 0);
+    // and depth buffer
+    glBindTexture(GL_TEXTURE_2D, depth_tex_id_);
+    glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, vp.x, vp.y, vp.width, vp.height, 0);
+
+    if(amb_occl_flag) {
+      // now for the normal buffer hack if the framebuffer stuff failed
+      Shader::Instance().PushProgram();
+      Shader::Instance().Activate("dumpnorm");
+      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+      Scene::Instance().GetRootNode()->RenderGL(STANDARD_RENDER_PASS);
+      glBindTexture(GL_TEXTURE_2D, norm_tex_id_);
+      glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, vp.x, vp.y, vp.width, vp.height, 0);
+      Shader::Instance().PopProgram();
+    }
+  }
+
+  if(shadow_flag) {
+    prep_shadow_map();
+  }
+  if(amb_occl_flag) {
+    prep_amb_occlusion();
+  }
+  if(depth_dark_flag) {
+    prep_depth_darkening();
+  }
+
+  Shader::Instance().PushProgram();
+  glEnable(GL_TEXTURE_2D);
+  glEnable(GL_TEXTURE_1D);
+  Shader::Instance().Activate("scenefx");
+  GLuint cpr=Shader::Instance().GetCurrentProgram();
+  glActiveTexture(GL_TEXTURE1);
+  glBindTexture(GL_TEXTURE_2D,depth_tex_id_);
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D,scene_tex_id_);
+
+  glUniform1i(glGetUniformLocation(cpr,"scene_map"),0);
+  glUniform1i(glGetUniformLocation(cpr,"depth_map"),1);
+
+  glUniform2f(glGetUniformLocation(cpr,"i_vp"),
+              1.0/static_cast<float>(vp.width),
+              1.0/static_cast<float>(vp.height));
+
+  if(shadow_flag) {
+    glActiveTexture(GL_TEXTURE2);
+    glBindTexture(GL_TEXTURE_2D,shadow_tex_id_);
+    glMatrixMode(GL_TEXTURE);
+    glPushMatrix();
+    glLoadTransposeMatrix(shadow_tex_mat_.Data());
+    glMatrixMode(GL_MODELVIEW);
+    glActiveTexture(GL_TEXTURE0);
+    glUniform1i(glGetUniformLocation(cpr,"shadow_flag"),1);
+    glUniform1i(glGetUniformLocation(cpr,"shadow_map"),2);
+    glUniform1f(glGetUniformLocation(cpr,"shadow_depth_bias"),0.008);
+    glUniform1f(glGetUniformLocation(cpr,"shadow_epsilon"),0.002);
+    glUniform1f(glGetUniformLocation(cpr,"shadow_multiplier"),0.4);
+    glUniform1f(glGetUniformLocation(cpr,"shadow_weight"),shadow_weight);
+
+  } else {
+    glUniform1i(glGetUniformLocation(cpr,"shadow_flag"),0);
+  }
+  if(amb_occl_flag) {
+    glActiveTexture(GL_TEXTURE3);
+    glBindTexture(GL_TEXTURE_2D,occl_tex_id_);
+    glActiveTexture(GL_TEXTURE0);
+    glUniform1i(glGetUniformLocation(cpr,"occl_flag"),1);
+    glUniform1i(glGetUniformLocation(cpr,"occl_map"),3);
+    glUniform1f(glGetUniformLocation(cpr,"occl_mult"),amb_occl_factor);
+  } else {
+    glUniform1i(glGetUniformLocation(cpr,"occl_flag"),0);
+  }
+
+  if(depth_dark_flag) {
+    glActiveTexture(GL_TEXTURE4);
+    glBindTexture(GL_TEXTURE_2D,dark_tex_id_);
+    glActiveTexture(GL_TEXTURE0);
+    glUniform1i(glGetUniformLocation(cpr,"dark_flag"),1);
+    glUniform1i(glGetUniformLocation(cpr,"dark_map"),4);
+    glUniform1f(glGetUniformLocation(cpr,"dark_mult"),depth_dark_factor);
+  } else {
+    glUniform1i(glGetUniformLocation(cpr,"dark_flag"),0);
+  }
+
+  if(use_beacon) {
+    prep_beacon();
+  }
+
+  draw_screen_quad(vp.width,vp.height);
+
+  if(shadow_flag) {
+    glActiveTexture(GL_TEXTURE2);
+    glMatrixMode(GL_TEXTURE);
+    glPopMatrix();
+    glMatrixMode(GL_MODELVIEW);
+    glActiveTexture(GL_TEXTURE0);
+  }
+
+  if(use_beacon) {
+    draw_beacon();
+  }
+
+  glDisable(GL_TEXTURE_1D);
+  glDisable(GL_TEXTURE_2D);
+  Shader::Instance().PopProgram();
+}
+
+void SceneFX::DrawTex(unsigned int w, unsigned int h, GLuint texid)
+{
+  if(!OST_GL_VERSION_2_0) return;
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("");
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D, texid);
+
+  draw_screen_quad(w,h);
+
+  Shader::Instance().PopProgram();
+}
+
+void SceneFX::prep_shadow_map()
+{
+  GLint smap_size=256 * (1+shadow_quality);
+
+#if GL_VERSION_3_0
+  glBindFramebuffer(GL_FRAMEBUFFER, scene_fb_);
+  glBindRenderbuffer(GL_RENDERBUFFER, scene_rb_);
+  glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA,smap_size,smap_size);
+  glBindRenderbuffer(GL_RENDERBUFFER, depth_rb_);
+  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,smap_size,smap_size);
+  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, scene_rb_);
+  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb_);
+  
+  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+  
+  if(status!=GL_FRAMEBUFFER_COMPLETE) {
+    LOG_DEBUG("fbo switch for shadow mapping failed, using fallback");
+    glBindRenderbuffer(GL_RENDERBUFFER, 0);
+    glBindFramebuffer(GL_FRAMEBUFFER, 0);
+    smap_size=512;
+  }
+#else
+  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, scene_fb_);
+  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, scene_rb_);
+  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_RGBA,smap_size,smap_size);
+  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb_);
+  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT,smap_size,smap_size);
+  glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, scene_rb_);
+  glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb_);
+  
+  GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+  
+  if(status!=GL_FRAMEBUFFER_COMPLETE_EXT) {
+    LOG_DEBUG("fbo switch for shadow mapping failed, using fallback");
+    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
+    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+    smap_size=512;
+  }
+#endif
+
+  // modelview transform for the lightsource pov
+  mol::Transform ltrans(Scene::Instance().GetTransform());
+  ltrans.SetRot(Scene::Instance().GetLightRot()*ltrans.GetRot());
+
+  // calculate encompassing box for ortho projection
+  geom::AlignedCuboid bb=Scene::Instance().GetBoundingBox(ltrans);
+  geom::Vec3 tmin=bb.GetMin();
+  geom::Vec3 tmax=bb.GetMax();
+
+  // save overall gl settings
+  glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT);
+  // maximize rendering for depth-only information
+  glDisable(GL_LIGHTING);
+  glDisable(GL_FOG);
+  glDisable(GL_COLOR_MATERIAL);
+  glDisable(GL_NORMALIZE);
+  //glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
+
+  // render scene with only depth components
+  // seen from the light's perspective
+  glViewport(0,0,smap_size,smap_size);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+  glMatrixMode(GL_PROJECTION);
+  glPushMatrix();
+  glLoadIdentity();
+  glOrtho(tmin[0],tmax[0],tmin[1],tmax[1],-tmax[2],-tmin[2]);
+  //glFrustum(tmin[0],tmax[0],tmin[1],tmax[1],-tmax[2],-tmin[2]);
+  float glpmat[16];
+  glGetv(GL_PROJECTION_MATRIX, glpmat);
+  geom::Mat4 pmat(geom::Transpose(geom::Mat4(glpmat)));
+
+  glMatrixMode(GL_MODELVIEW);
+  glPushMatrix();
+  glLoadIdentity();
+  glMultMatrix(ltrans.GetTransposedMatrix().Data());
+
+  // only render non-transparent objects for the shadow map
+  Scene::Instance().GetRootNode()->RenderGL(STANDARD_RENDER_PASS);
+
+  // now get the shadow map
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D, shadow_tex_id_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 0,0, smap_size,smap_size, 0);
+
+  // restore settings
+  glPopMatrix();
+  glMatrixMode(GL_PROJECTION);
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+
+  glPopAttrib();
+  //glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
+
+#if GL_VERSION_3_0
+  glBindRenderbuffer(GL_RENDERBUFFER, 0);
+  glBindFramebuffer(GL_FRAMEBUFFER, 0);
+#else
+  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
+  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+#endif
+
+  // set up appropriate texture matrix
+  geom::Mat4 bias(0.5,0.0,0.0,0.5,
+                  0.0,0.5,0.0,0.5,
+                  0.0,0.0,0.5,0.5,
+                  0.0,0.0,0.0,1.0);
+  //shadow_tex_mat_ = bias*pmat*ltrans.GetMatrix();
+  glGetv(GL_PROJECTION_MATRIX, glpmat);
+  geom::Mat4 pmat2(geom::Transpose(geom::Mat4(glpmat)));
+  /*
+    given the normalized coordinates in scenefx, the camera projection and modelview transformation
+    are first reverted, and then the light modelview and projection are applied, resulting (with the
+    bias) in the proper 2D lookup into the shadow map
+  */
+  shadow_tex_mat_ = bias*pmat*ltrans.GetMatrix()*geom::Invert(Scene::Instance().GetTransform().GetMatrix())*geom::Invert(pmat2);
+}
+
+void SceneFX::prep_amb_occlusion()
+{
+  Viewport vp=Scene::Instance().GetViewport();
+
+  uint qf=1;
+  if(amb_occl_quality==0) {qf=4;}
+  else if(amb_occl_quality==1) {qf=2;}
+  uint width=vp.width/qf;
+  uint height=vp.height/qf;
+
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("amboccl");
+  GLuint cpr=Shader::Instance().GetCurrentProgram();
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D,depth_tex_id_);
+  glActiveTexture(GL_TEXTURE1);
+  glBindTexture(GL_TEXTURE_2D,norm_tex_id_);
+  glActiveTexture(GL_TEXTURE2);
+  glBindTexture(GL_TEXTURE_1D,kernel_tex_id_);
+  glActiveTexture(GL_TEXTURE0);
+  glUniform1i(glGetUniformLocation(cpr,"depth_map"),0);
+  glUniform1i(glGetUniformLocation(cpr,"norm_map"),1);
+  glUniform1i(glGetUniformLocation(cpr,"kernel"),2);
+  glUniform1f(glGetUniformLocation(cpr,"step"),1.0/static_cast<float>(kernel_size_));
+  glUniform2f(glGetUniformLocation(cpr,"i_vp"),1.0/static_cast<float>(width),1.0/static_cast<float>(height));
+  glUniform1i(glGetUniformLocation(cpr,"mode"),amb_occl_mode);
+  double pm[16];
+  glGetDoublev(GL_PROJECTION_MATRIX,pm);
+  glUniform4f(glGetUniformLocation(cpr,"abcd"),pm[0],pm[5],pm[10],pm[14]);
+
+  glMatrixMode(GL_TEXTURE);
+  glPushMatrix();
+  geom::Mat4 ipm(geom::Transpose(geom::Invert(geom::Transpose(geom::Mat4(pm)))));
+  glLoadMatrix(ipm.Data());
+  glMatrixMode(GL_MODELVIEW);
+
+  // set up viewport filling quad to run the fragment shader
+  draw_screen_quad(width,height);
+
+  glMatrixMode(GL_TEXTURE);
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D, occl_tex_id_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0,0, width, height, 0);
+  Shader::Instance().PopProgram();
+}
+
+void SceneFX::prep_depth_darkening()
+{
+  Viewport vp=Scene::Instance().GetViewport();
+
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("convolute1");
+  GLuint cpr=Shader::Instance().GetCurrentProgram();
+  // assign tex units
+  glActiveTexture(GL_TEXTURE1);
+  glBindTexture(GL_TEXTURE_2D,depth_tex_id_);
+  glActiveTexture(GL_TEXTURE2);
+  glBindTexture(GL_TEXTURE_1D,kernel2_tex_id_);
+  glActiveTexture(GL_TEXTURE0);
+
+  glUniform1i(glGetUniformLocation(cpr,"data"),1);
+  glUniform1i(glGetUniformLocation(cpr,"kernel"),2);
+  glUniform1f(glGetUniformLocation(cpr,"step"),1.0/static_cast<float>(kernel2_size_));
+  glUniform2f(glGetUniformLocation(cpr,"i_vp"),1.0/static_cast<float>(vp.width),1.0/static_cast<float>(vp.height));
+
+  // set up viewport filling quad to run the fragment shader
+  draw_screen_quad(vp.width/2,vp.height/2);
+
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D, dark_tex_id_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0,0,vp.width/2, vp.height/2, 0);
+
+  Shader::Instance().PopProgram();
+}
+
+void SceneFX::draw_screen_quad(unsigned int w, unsigned int h) 
+{
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
+  
+  // setup
+  glDisable(GL_DEPTH_TEST);
+  glDisable(GL_LIGHTING);
+  glDisable(GL_COLOR_MATERIAL);
+  glDisable(GL_FOG);
+  glDisable(GL_CULL_FACE);
+  glDisable(GL_BLEND);
+  glDisable(GL_LINE_SMOOTH);
+  glDisable(GL_POINT_SMOOTH);
+  glShadeModel(GL_FLAT);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  glViewport(0,0,w,h);
+  glMatrixMode(GL_PROJECTION);
+  glPushMatrix();
+  glLoadIdentity();
+  glOrtho(0,1,0,1,-1,1);
+  glMatrixMode(GL_MODELVIEW);
+  glPushMatrix();
+  glLoadIdentity();
+  glEnable(GL_TEXTURE_2D);
+  glActiveTexture(GL_TEXTURE0);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+  // draw
+  glColor3f(1.0,0.0,1.0);
+  glBegin(GL_QUADS);
+  glTexCoord2f(0.0,0.0);
+  glVertex2f(0.0,0.0);
+  glTexCoord2f(0.0,1.0);
+  glVertex2f(0.0,1.0);
+  glTexCoord2f(1.0,1.0);
+  glVertex2f(1.0,1.0);
+  glTexCoord2f(1.0,0.0);
+  glVertex2f(1.0,0.0);
+  glEnd();
+  
+  // restore settings
+  glMatrixMode(GL_PROJECTION);
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+  glPopMatrix();
+  glPopAttrib();
+}
+
+void SceneFX::prep_beacon()
+{
+  glMatrixMode(GL_PROJECTION);
+  glPushMatrix();
+  glLoadIdentity();
+  Scene::Instance().stereo_projection(0);
+  GLdouble glpmat[16];
+  glGetDoublev(GL_PROJECTION_MATRIX, glpmat);
+  geom::Mat4 pmat(geom::Transpose(geom::Mat4(glpmat)));
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+  geom::Mat4 mmat=Scene::Instance().GetTransform().GetTransposedMatrix();
+  GLdouble glmmat[16];
+  for(int i=0;i<16;++i) glmmat[i]=static_cast<GLdouble>(mmat.Data()[i]);
+  GLint glvp[4];
+  glGetIntegerv(GL_VIEWPORT,glvp);
+
+  double res[3];
+  gluUnProject(beacon.wx,beacon.wy,0.0,
+	       glmmat,glpmat,glvp,
+	       &res[0],&res[1],&res[2]);
+  beacon.p0=geom::Vec3(res[0],res[1],res[2]);
+  gluUnProject(beacon.wx,beacon.wy,1.0,
+	       glmmat,glpmat,glvp,
+	       &res[0],&res[1],&res[2]);
+  beacon.p1=geom::Vec3(res[0],res[1],res[2]);
+
+  glGetv(GL_PROJECTION_MATRIX, glpmat);
+  geom::Mat4 pmat2(geom::Transpose(geom::Mat4(glpmat)));
+  beacon.mat = geom::Invert(Scene::Instance().GetTransform().GetMatrix())*geom::Invert(pmat2);
+}
+
+void SceneFX::draw_beacon()
+{
+  Viewport vp=Scene::Instance().GetViewport();
+  float iw=1.0/static_cast<float>(vp.width);
+  float ih=1.0/static_cast<float>(vp.height);
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("beacon");
+  uint cpr=Shader::Instance().GetCurrentProgram();
+
+  float rad=0.6;
+  float delta = rad/(std::max<float>(1.0,Scene::Instance().znear_) * Scene::Instance().aspect_ratio_ * std::tan(Scene::Instance().fov_*M_PI/360.0))/iw;
+  geom::Vec2 q0(beacon.wx-delta,beacon.wy-delta);
+  geom::Vec2 q1(beacon.wx-delta,beacon.wy+delta);
+  geom::Vec2 q2(beacon.wx+delta,beacon.wy+delta);
+  geom::Vec2 q3(beacon.wx+delta,beacon.wy-delta);
+
+  glActiveTexture(GL_TEXTURE1);
+  glBindTexture(GL_TEXTURE_2D,depth_tex_id_);
+  glMatrixMode(GL_TEXTURE);
+  glPushMatrix();
+  glLoadTransposeMatrix(beacon.mat.Data());
+  glActiveTexture(GL_TEXTURE0);
+  glUniform1i(glGetUniformLocation(cpr,"depth_map"),1);
+  glUniform3f(glGetUniformLocation(cpr,"pos"),beacon.p0[0],beacon.p0[1],beacon.p0[2]);
+  geom::Vec3 dir=beacon.p1-beacon.p0;
+  glUniform3f(glGetUniformLocation(cpr,"dir"),dir[0],dir[1],dir[2]);
+  glUniform1f(glGetUniformLocation(cpr,"len"),geom::Length(dir));
+  glUniform1f(glGetUniformLocation(cpr,"rad"),rad);
+
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
+  glMatrixMode(GL_PROJECTION);
+  glPushMatrix();
+  glLoadIdentity();
+  glOrtho(0,vp.width,0,vp.height,-1,1);
+  glMatrixMode(GL_MODELVIEW);
+  glPushMatrix();
+  glLoadIdentity();
+  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+  glEnable(GL_BLEND);
+  glDisable(GL_DEPTH_TEST);
+  glDisable(GL_LIGHTING);
+  glDisable(GL_COLOR_MATERIAL);
+  glDisable(GL_FOG);
+  glDisable(GL_CULL_FACE);
+  glDisable(GL_LINE_SMOOTH);
+  glDisable(GL_POINT_SMOOTH);
+  glShadeModel(GL_FLAT);
+  glViewport(0,0,vp.width,vp.height);
+  glEnable(GL_TEXTURE_2D);
+  glColor3f(1.0,0.0,1.0);
+  glBegin(GL_QUADS);
+  glTexCoord2f(iw*q0[0],ih*q0[1]);
+  glVertex2f(q0[0],q0[1]);
+  glTexCoord2f(iw*q1[0],ih*q1[1]);
+  glVertex2f(q1[0],q1[1]);
+  glTexCoord2f(iw*q2[0],ih*q2[1]);
+  glVertex2f(q2[0],q2[1]);
+  glTexCoord2f(iw*q3[0],ih*q3[1]);
+  glVertex2f(q3[0],q3[1]);
+  glEnd();
+  glActiveTexture(GL_TEXTURE1);
+  glMatrixMode(GL_TEXTURE);
+  glPopMatrix();
+  glActiveTexture(GL_TEXTURE0);
+  glMatrixMode(GL_PROJECTION);
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+  glPopMatrix();
+  glPopAttrib();
+  Shader::Instance().PopProgram();
+}
+
+void SceneFX::screenblur4()
+{
+  Viewport vp=Scene::Instance().GetViewport();
+  glBindTexture(GL_TEXTURE_2D, scene_tex_id_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, vp.x, vp.y, vp.width, vp.height, 0);
+  glBindTexture(GL_TEXTURE_2D, depth_tex_id_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, vp.x, vp.y, vp.width, vp.height, 0);
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("screenblur4");
+  GLuint cpr=Shader::Instance().GetCurrentProgram();
+  glActiveTexture(GL_TEXTURE1);
+  glBindTexture(GL_TEXTURE_2D,depth_tex_id_);
+  glActiveTexture(GL_TEXTURE0);
+  glBindTexture(GL_TEXTURE_2D,scene_tex_id_);
+  glUniform1i(glGetUniformLocation(cpr,"scene_map"),0);
+  glUniform1i(glGetUniformLocation(cpr,"depth_map"),1);
+  glUniform2f(glGetUniformLocation(cpr,"i_vp"),
+              1.0/static_cast<float>(vp.width),
+              1.0/static_cast<float>(vp.height));
+  glUniform1f(glGetUniformLocation(cpr,"depth_cutoff"),0.5);
+  draw_screen_quad(vp.width,vp.height);
+  Shader::Instance().PopProgram();
+}
+
+}}} // ns
diff --git a/modules/gfx/src/impl/scene_fx.hh b/modules/gfx/src/impl/scene_fx.hh
new file mode 100644
index 0000000000000000000000000000000000000000..49961c340139796df3fea2253c1215c1c2c4d8b3
--- /dev/null
+++ b/modules/gfx/src/impl/scene_fx.hh
@@ -0,0 +1,107 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#ifndef OST_SCENE_FX_HH
+#define OST_SCENE_FX_HH
+
+#include <ost/gfx/gl_helper.hh>
+#include <ost/geom/geom.hh>
+
+/*
+  low level code for scene shading effects
+
+  Author: Ansgar Philippsen
+*/
+
+namespace ost { namespace gfx { 
+
+class Scene;
+
+namespace impl {
+
+struct Beacon {
+  float wx, wy;
+  geom::Vec3 p0,p1;
+  geom::Mat4 mat;
+};
+
+class SceneFX {
+  friend class ::ost::gfx::Scene;
+public:
+  ~SceneFX();
+  static SceneFX& Instance();
+
+  void Setup();
+
+  void Resize(unsigned int w, unsigned int h);
+  
+  void Preprocess();
+  // assumes scene has been drawn in the active framebuffer
+  void Postprocess();
+
+  void DrawTex(unsigned int w, unsigned int h, GLuint texid);
+
+  bool shadow_flag;
+  int shadow_quality;
+  float shadow_weight;
+  bool depth_dark_flag;
+  float depth_dark_factor;
+  bool amb_occl_flag;
+  float amb_occl_factor;
+  uint amb_occl_mode;
+  uint amb_occl_quality;
+  bool use_beacon;
+  Beacon beacon;
+
+private:
+  SceneFX();
+  SceneFX(const SceneFX&) {}
+  SceneFX& operator=(const SceneFX&) {return *this;}
+
+  void screenblur4();
+  void prep_shadow_map();
+  void prep_depth_darkening();
+  void prep_amb_occlusion();
+  void draw_screen_quad(uint w, uint h);
+  void prep_beacon();
+  void draw_beacon();
+
+  GLuint scene_tex_id_;
+  GLuint depth_tex_id_;
+  GLuint shadow_tex_id_;
+  geom::Mat4 shadow_tex_mat_;
+  GLuint occl_tex_id_;
+  GLuint dark_tex_id_;
+  GLuint norm_tex_id_;
+  GLuint kernel_tex_id_;
+  uint kernel_size_;
+  GLuint kernel2_tex_id_;
+  uint kernel2_size_;
+
+  GLuint scene_tex2_id_;
+  GLuint norm_tex2_id_;
+  GLuint scene_fb_;
+  GLuint scene_rb_;
+  GLuint depth_rb_;
+
+  bool use_fb_;
+};
+
+}}} // ns
+
+#endif
diff --git a/modules/gfx/src/impl/simple_renderer.cc b/modules/gfx/src/impl/simple_renderer.cc
index bfb30d3133648b5216a4916c006a17daea51ee56..a6684e5f9fcb7894453fcde0e265c647cbe101d5 100644
--- a/modules/gfx/src/impl/simple_renderer.cc
+++ b/modules/gfx/src/impl/simple_renderer.cc
@@ -30,25 +30,6 @@
 namespace ost { namespace gfx { namespace impl {
 
 
-namespace {
-
-struct BlurQuadEntry
-{
-  float zdist;
-  geom::Vec3 p1,p2,p3,p4;
-  Color c1,c2,c3,c4;
-};
-
-struct BlurQuadEntryLess
-{
-  bool operator()(const BlurQuadEntry& e1, const BlurQuadEntry& e2)
-  {
-    // provides back-to-front sorting
-    return e1.zdist<e2.zdist;
-  }
-};
-
-}
   
 SimpleRenderer::SimpleRenderer(): options_(new SimpleRenderOptions()) 
 {
@@ -200,124 +181,14 @@ void SimpleRenderer::PrepareRendering(GfxView& view, IndexedVertexArray& va)
   }  
 }
 
-void SimpleRenderer::RenderBlur()
-{
-  // add blur for this particular orientation!
-  // don't use vertex array, but on-the-fly oriented and z-sorted quads
-  mol::Transform tf = Scene::Instance().GetTransform();
-
-  std::vector<BlurQuadEntry> bql;
-  const std::pair<Real, Real>& bf=options_->GetBlurFactors();
-  for (BondEntryList::iterator it=view_.bond_list.begin();
-       it!=view_.bond_list.end();++it) {
-
-    const geom::Vec3 p0=tf.Apply(it->bond.GetFirst().GetPos());
-    const geom::Vec3 p2=tf.Apply(it->bond.GetSecond().GetPos());
-    geom::Vec3 p1=(p0+p2)*0.5;
-
-    const geom::Vec3 q0=tf.Apply(it->pp1);
-    const geom::Vec3 q2=tf.Apply(it->pp2);
-    geom::Vec3 q1=(q0+q2)*0.5;
-
-    float ll0 = geom::Length2(p0-q0);
-    float ll1 = geom::Length2(p1-q1);
-    float ll2 = geom::Length2(p2-q2);
-
-    if(ll0<1e-2 && ll1<1e-2 && ll2<1e-2) continue;
-
-    float x0 = exp(-bf.first*ll0);
-    float x1 = exp(-bf.first*ll1);
-    float x2 = exp(-bf.first*ll2);
-
-    BlurQuadEntry bqe;
-
-    bqe.zdist=0.25*(p0[2]+p2[2]+q0[2]+q2[2]);
-
-    // first half
-    bqe.p1 = p0;
-    bqe.p2 = p1;
-    bqe.p3 = q0;
-    bqe.p4 = q1;
-    bqe.c1 = it->atom1->color;
-    bqe.c2 = it->atom1->color;
-    bqe.c3 = it->atom1->color;
-    bqe.c4 = it->atom1->color;
-    bqe.c1[3] = x0;
-    bqe.c2[3] = x1;
-    bqe.c3[3]=x0*bf.second;
-    bqe.c4[3]=x1*bf.second;
-
-    bql.push_back(bqe);
-
-    // first half
-    bqe.p1 = p1;
-    bqe.p2 = p2;
-    bqe.p3 = q1;
-    bqe.p4 = q2;
-    bqe.c1 = it->atom2->color;
-    bqe.c2 = it->atom2->color;
-    bqe.c3 = it->atom2->color;
-    bqe.c4 = it->atom2->color;
-    bqe.c1[3] = x1;
-    bqe.c2[3] = x2;
-    bqe.c3[3]=x1*bf.second;
-    bqe.c4[3]=x2*bf.second;
-
-    bql.push_back(bqe);
-  }
-
-  std::sort(bql.begin(),bql.end(),BlurQuadEntryLess());
-
-  glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT);
-  glDisable(GL_LIGHTING);
-  glDisable(GL_CULL_FACE);
-  glDepthFunc(GL_LESS);
-  glDepthMask(GL_FALSE);
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
-  glBegin(GL_QUADS);
-  glNormal3f(0.0,0.0,0.0);
-  for (std::vector<BlurQuadEntry>::const_iterator it=bql.begin();
-       it!=bql.end();++it) {
-    glColor4fv(it->c1);
-    glVertex3v(it->p1.Data());
-    glColor4fv(it->c2);
-    glVertex3v(it->p2.Data());
-    glColor4fv(it->c4);
-    glVertex3v(it->p4.Data());
-    glColor4fv(it->c3);
-    glVertex3v(it->p3.Data());
-  }
-
-  glEnd();
-  glPopMatrix();
-  glPopAttrib();
-}
-
-void SimpleRenderer::BlurSnapshot()
+BondEntryList& SimpleRenderer::GetBondEntryList()
 {
-  for (BondEntryList::iterator it=view_.bond_list.begin();
-       it!=view_.bond_list.end();++it) {
-    it->pp1=it->atom1->atom.GetPos();
-    it->pp2=it->atom2->atom.GetPos();
-  }
-}
-void SimpleRenderer::Render(RenderPass pass)
-{
-  ConnectRendererBase::Render(pass);
-  if (pass==STANDARD_RENDER_PASS && options_->GetBlurFlag()) {
-    this->RenderBlur();
-  }
-}
-
-SimpleRenderer::~SimpleRenderer() 
-{
-
+  return view_.bond_list;
 }
 
 void SimpleRenderer::RenderPov(PovState& pov, const std::string& name)
 {
+  if(view_.atom_map.empty() && view_.bond_list.empty()) return;
   pov.write_merge_or_union(name);
   
   for (AtomEntryMap::const_iterator it=view_.atom_map.begin();
diff --git a/modules/gfx/src/impl/simple_renderer.hh b/modules/gfx/src/impl/simple_renderer.hh
index 78038ffe543780b5d92389866d142c105cbcd8ba..41b801cbd6721d4a57309edf271c80f6d7dbb8e3 100644
--- a/modules/gfx/src/impl/simple_renderer.hh
+++ b/modules/gfx/src/impl/simple_renderer.hh
@@ -43,12 +43,10 @@ public:
   virtual void SetOptions(RenderOptionsPtr& render_options);
   virtual RenderOptionsPtr GetOptions();
   
-  virtual void Render(RenderPass pass);
-  virtual ~SimpleRenderer();
   virtual void RenderPov(PovState& pov, const std::string& name);
-  void BlurSnapshot();
+
+  BondEntryList& GetBondEntryList();
 private:
-  void RenderBlur();
   void PrepareRendering(GfxView& view, IndexedVertexArray& va);
   geom::Vec3 GetDoubleBondPlane(mol::BondHandle b);
   void GetBondPartnerNormal(geom::Vec3& vec, int& n, geom::Vec3& bond_vec,
diff --git a/modules/gfx/src/impl/sline_renderer.cc b/modules/gfx/src/impl/sline_renderer.cc
index 6d1fe022dd2f56dcad4b6245f89c57df79632b3a..c3655f34cdc7bca0700b6fdcb1ace416ec0e7f5b 100644
--- a/modules/gfx/src/impl/sline_renderer.cc
+++ b/modules/gfx/src/impl/sline_renderer.cc
@@ -16,80 +16,26 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+/*
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #include "sline_renderer.hh"
 
 #include <ost/gfx/entity.hh>
 
 namespace ost { namespace gfx { namespace impl {
 
-SlineRenderer::SlineRenderer(BackboneTrace& trace): 
-  TraceRendererBase(trace, 3), options_(new SlineRenderOptions()) 
+SlineRenderer::SlineRenderer(BackboneTrace* trace): 
+  TraceRendererBase(trace, 3), 
+  options_(new SlineRenderOptions()),
+  spline_list_list_(),
+  sel_spline_list_list_()
 {
   this->SetName("Fast Spline");
 }
 
-void SlineRenderer::PrepareRendering()
-{
-  TraceRendererBase::PrepareRendering();
-  va_.Clear();
-  this->PrepareRendering(trace_subset_, va_, false);
-  sel_va_.Clear();
-  if (this->HasSelection()) {
-    this->PrepareRendering(sel_subset_, sel_va_, true);
-    sel_va_.SetLineWidth(options_->GetLineWidth()+3.0);    
-  }
-}
-
-void SlineRenderer::PrepareRendering(TraceSubset& trace_subset, 
-                                     IndexedVertexArray& va, bool is_sel)
-{
-  const Color& sel_clr=this->GetSelectionColor();
-  
-  int spline_detail=std::max((unsigned int) 1, options_->GetSplineDetail());
-  if(options_!=NULL){
-    va.Clear();
-    va.SetLighting(false);
-    va.SetCullFace(false);
-    va.SetColorMaterial(false);
-    va.SetMode(0x2);
-    va.SetTwoSided(true);
-    va.SetLineWidth(options_->GetLineWidth());
-    va.SetPointSize(options_->GetLineWidth());
-    va.SetAALines(options_->GetAALines());
-    for (int node_list=0; node_list<trace_subset.GetSize(); ++node_list) {
-      // first build the spline
-      Spline spl;
-      const NodeListSubset& nl=trace_subset[node_list];
-      assert(nl.GetSize() && "node list subset with zero eles encountered!");
-      for (int i=0; i<nl.GetSize();++i) {
-        const NodeEntry& entry=nl[i];
-        SplineEntry& ee = spl.AddEntry(entry.atom.GetPos(), entry.direction,
-                                       entry.normal, entry.rad, 
-                                       is_sel ? sel_clr : entry.color1, 
-                                       is_sel ? sel_clr : entry.color2, 0);
-        ee.v1 = entry.v1;
-      }
-      SplineEntryList sel = spl.Generate(spline_detail);      
-      SplineEntryList::const_iterator sit=sel.begin(), 
-                                     send=sel.end()-spline_detail+1;
-      if (nl.AtStart()>0) {
-        sit+=nl.AtStart()*spline_detail-spline_detail/2;
-      }
-      if (nl.AtEnd()>0) {
-        send-=nl.AtEnd()*spline_detail-spline_detail/2;
-      }
-      VertexID p0=va.Add(sit->position, geom::Vec3(),sit->color1);
-      for (++sit; sit<send; ++sit) {
-        VertexID p1 = va.Add(sit->position, geom::Vec3(),sit->color1);
-        va.AddLine(p0,p1);
-        p0=p1;
-      }
-    }
-  }
-  sel_state_=0;
-  state_=0;
-}
-
 bool SlineRenderer::CanSetOptions(RenderOptionsPtr& render_options)
 {
  return render_options->GetRenderMode()==RenderMode::SLINE;
@@ -105,8 +51,84 @@ RenderOptionsPtr SlineRenderer::GetOptions()
  return options_;
 }
 
-SlineRenderer::~SlineRenderer() 
+void SlineRenderer::PrepareRendering()
 {
+  TraceRendererBase::PrepareRendering();
+  if(state_>0) {
+    prepare_rendering(trace_subset_, va_, spline_list_list_);
+    rebuild_spline_obj(va_, spline_list_list_, false);
+  }
+  if (this->HasSelection() && (state_>0 || sel_state_>0)) {
+    Color sel_color=GetSelectionColor();
+    rebuild_sel(spline_list_list_,sel_spline_list_list_,sel_color);
+    rebuild_spline_obj(sel_va_, sel_spline_list_list_, true);
+    va_.SetOpacity(sel_color.Alpha());
+  }
+  sel_state_=0;
+  state_=0;
+}
+
+void SlineRenderer::prepare_rendering(const BackboneTrace& subset, 
+                                      IndexedVertexArray& va,
+                                      SplineEntryListList& spline_list_list)
+{
+  if(options_==NULL) {
+    LOG_DEBUG("SlineRenderer: NULL options, not creating objects");
+  }
+
+  int spline_detail=std::max((unsigned int) 1, options_->GetSplineDetail());
+  SplineEntryListList tmp_sll;
+  for (int node_list=0; node_list<subset.GetListCount(); ++node_list) {
+    LOG_DEBUG("SplineRenderer: collecting spline entries for node list " << node_list);
+    // first build the spline
+    SplineEntryList spl;
+    const NodeEntryList& nl=subset.GetList(node_list);
+    for (unsigned int i=0; i<nl.size();++i) {
+      int type=0;
+      const NodeEntry& entry=nl[i];
+      SplineEntry ee(entry.atom.GetPos(),entry.direction,
+                     entry.normal, entry.rad, 
+                     entry.color1, 
+                     entry.color2,
+                     type, entry.id);
+      ee.v1 = entry.v1;
+      spl.push_back(ee);
+    }
+    LOG_DEBUG("SplineRenderer: found " << spl.size() << " entries");
+    if(!spl.empty()) {
+      tmp_sll.push_back(spl);
+    }
+  }
+  spline_list_list.clear();
+  for(SplineEntryListList::const_iterator sit=tmp_sll.begin();sit!=tmp_sll.end();++sit) {
+    spline_list_list.push_back(Spline::Generate(*sit,spline_detail));
+  }
+}
+
+void SlineRenderer::rebuild_spline_obj(IndexedVertexArray& va, const SplineEntryListList& spline_list_list, bool is_sel)
+{
+  va.Clear();
+  va.SetLighting(false);
+  va.SetCullFace(false);
+  va.SetColorMaterial(false);
+  va.SetMode(0x2);
+  va.SetTwoSided(true);
+  va.SetLineWidth(options_->GetLineWidth() + (is_sel ? 2.0 : 0.0));
+  va.SetPointSize(options_->GetLineWidth() + (is_sel ? 2.0 : 0.0));
+  va.SetAALines(options_->GetAALines());
+
+  for(SplineEntryListList::const_iterator it=spline_list_list.begin();
+      it<spline_list_list.end();++it) {
+    const SplineEntryList& slist=*it;
+
+    SplineEntryList::const_iterator sit=slist.begin();
+    VertexID p0=va.Add(sit->position, geom::Vec3(),sit->color1);
+    for (++sit; sit!=slist.end(); ++sit) {
+      VertexID p1 = va.Add(sit->position, geom::Vec3(),sit->color1);
+      va.AddLine(p0,p1);
+      p0=p1;
+    }
+  }
 
 }
 
diff --git a/modules/gfx/src/impl/sline_renderer.hh b/modules/gfx/src/impl/sline_renderer.hh
index b264fc4b61f99088f595c4e5df6bb42977b19a31..35c81bde9b69b868c5323397d89b40949195bc20 100644
--- a/modules/gfx/src/impl/sline_renderer.hh
+++ b/modules/gfx/src/impl/sline_renderer.hh
@@ -16,6 +16,11 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
+/*
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #ifndef OST_GFX_SLINE_RENDERER_HH
 #define OST_GFX_SLINE_RENDERER_HH
 
@@ -32,20 +37,20 @@ namespace ost { namespace gfx { namespace impl {
 /// \internal
 class DLLEXPORT_OST_GFX SlineRenderer: public TraceRendererBase {
 public:
-  SlineRenderer(BackboneTrace& trace);
+  SlineRenderer(BackboneTrace* trace);
 
   virtual void PrepareRendering();
-
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
   virtual void SetOptions(RenderOptionsPtr& render_options);
   virtual RenderOptionsPtr GetOptions();
 
-  virtual ~SlineRenderer();
-
 private:
-  void PrepareRendering(TraceSubset& subset, IndexedVertexArray& va, 
-                        bool is_sel);
+  void prepare_rendering(const BackboneTrace&, IndexedVertexArray&, SplineEntryListList&);
+  void rebuild_spline_obj(IndexedVertexArray&, const SplineEntryListList&, bool);
+
   SlineRenderOptionsPtr options_;
+  SplineEntryListList spline_list_list_;
+  SplineEntryListList sel_spline_list_list_;
 };
 
 }}}
diff --git a/modules/gfx/src/impl/trace_renderer.cc b/modules/gfx/src/impl/trace_renderer.cc
index 02f2d67527ec9e5ab419c8f47e335948fbe56557..a6b442ee63540e9dd9c20aa0615282a5d313e65d 100644
--- a/modules/gfx/src/impl/trace_renderer.cc
+++ b/modules/gfx/src/impl/trace_renderer.cc
@@ -17,6 +17,10 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 
+/*
+   Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #include <ost/gfx/entity.hh>
 #include <ost/gfx/povray.hh>
 
@@ -25,7 +29,7 @@
 
 namespace ost { namespace gfx { namespace impl {
 
-TraceRenderer::TraceRenderer(BackboneTrace& trace): 
+TraceRenderer::TraceRenderer(BackboneTrace* trace): 
   TraceRendererBase(trace, 1), options_(new TraceRenderOptions())
 {
   this->SetName("Trace");
@@ -38,16 +42,15 @@ void TraceRenderer::PrepareRendering()
   this->PrepareRendering(trace_subset_, va_, false);
   sel_va_.Clear();
   if (this->HasSelection()) {
-    this->PrepareRendering(sel_subset_, sel_va_, true);
+    //this->PrepareRendering(sel_subset_, sel_va_, true);
+    this->PrepareRendering(trace_subset_, sel_va_, true);
     sel_va_.SetLighting(false);
   }
 }
 
-#if 1
-void TraceRenderer::PrepareRendering(TraceSubset& trace_subset,
+void TraceRenderer::PrepareRendering(BackboneTrace& trace_subset,
                                      IndexedVertexArray& va, bool is_sel)
 {
-  float plus=is_sel ? 0.05: 0.0;
   const Color& sel_clr=this->GetSelectionColor();
   if(options_!=NULL){
     va.Clear();
@@ -55,199 +58,78 @@ void TraceRenderer::PrepareRendering(TraceSubset& trace_subset,
     va.SetCullFace(true);
     va.SetColorMaterial(true);
     va.SetTwoSided(false);
-    for (int node_list=0; node_list<trace_subset.GetSize(); ++node_list) {
-      const NodeListSubset& nl=trace_subset[node_list];
-      mol::AtomHandle a1=nl[0].atom;
-      va.AddSphere(SpherePrim(a1.GetPos(),
-                              options_->GetTubeRadius()+plus,
-                              is_sel ? sel_clr : nl[0].color1),
-                   options_->GetArcDetail());
-      for(int i=1;i<nl.GetSize();++i) {
-        mol::AtomHandle a2=nl[i].atom;
-        va.AddSphere(SpherePrim(a2.GetPos(),
-                                options_->GetTubeRadius()+plus,
-                                is_sel ? sel_clr : nl[i].color1),
+    if(is_sel) {
+      va.SetOpacity(GetSelectionColor().Alpha());
+      for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+        const NodeEntryList& nl=trace_subset.GetList(node_list);
+        for(unsigned int i=0;i<nl.size();++i) {
+          mol::AtomHandle ah=nl[i].atom;
+          if(sel_.FindAtom(ah).IsValid()) {
+            geom::Vec3 apos = ah.GetPos();
+            va.AddSphere(SpherePrim(apos,
+                                    options_->GetTubeRadius()+0.05,
+                                    sel_clr),
+                         options_->GetArcDetail());
+            if(i>0) {
+              va.AddCylinder(CylinderPrim(apos+0.5*(nl[i-1].atom.GetPos()-apos),
+                                          apos,
+                                          options_->GetTubeRadius()+0.05,
+                                          sel_clr),
+                             options_->GetArcDetail());
+            }
+            if(i<nl.size()-1) {
+              va.AddCylinder(CylinderPrim(apos,
+                                          apos+0.5*(nl[i+1].atom.GetPos()-apos),
+                                          options_->GetTubeRadius()+0.05,
+                                          sel_clr),
+                             options_->GetArcDetail());
+            }
+          }
+        }
+      }
+    } else {
+      for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+        const NodeEntryList& nl=trace_subset.GetList(node_list);
+        mol::AtomHandle a1=nl[0].atom;
+        va.AddSphere(SpherePrim(a1.GetPos(),
+                                options_->GetTubeRadius(),
+                                nl[0].color1),
                      options_->GetArcDetail());
-        const geom::Vec3& p0=a1.GetPos();
-        const geom::Vec3& p2=a2.GetPos();
-        geom::Vec3 p1=(p0+p2)*0.5;
-        va.AddCylinder(CylinderPrim(p0,p1,options_->GetTubeRadius()+plus,
-                                    is_sel ? sel_clr : nl[i-1].color1),
+        for(unsigned int i=1;i<nl.size();++i) {
+          mol::AtomHandle a2=nl[i].atom;
+          va.AddSphere(SpherePrim(a2.GetPos(),
+                                  options_->GetTubeRadius(),
+                                  nl[i].color1),
                        options_->GetArcDetail());
-        va.AddCylinder(CylinderPrim(p1,p2,options_->GetTubeRadius()+plus,
-                                    is_sel ? sel_clr : nl[i].color1),
-                       options_->GetArcDetail());
-        a1=a2;
-      }
-    }
-  }
-  sel_state_=0;
-  state_=0;
-}
-
-#else
-
-void TraceRenderer::PrepareRendering(TraceSubset& trace_subset,
-                                     IndexedVertexArray& va, bool is_sel)
-{
-  const Color& sel_clr=this->GetSelectionColor();
-  float radius=options_->GetTubeRadius();
-  if (is_sel) {
-    radius+=0.1;
-  }
-  int n=8*options_->GetArcDetail();
-  if(options_!=NULL) {
-    va.SetLighting(true);
-    va.SetCullFace(false);
-    for (int node_list=0; node_list<trace_subset.GetSize(); ++node_list) {
-      const NodeListSubset& nl=trace_subset[node_list];
-      geom::Vec3 cursor_pos;
-      geom::Mat3 cursor_ori;
-      if (nl.GetSize()==2) {
-        VertexID p0, p1;
-        if (nl.AtStart()==0) {
-          p0=va.Add(nl[0].atom.GetPos(), geom::Vec3(),
-                    is_sel ? sel_clr : nl[0].color1);
-          p1=va.Add((nl[0].atom.GetPos()+nl[1].atom.GetPos())/2, 
-                    geom::Vec3(), is_sel ? sel_clr : nl[1].color1);
-        } else {
-          p0=va.Add((nl[0].atom.GetPos()+nl[1].atom.GetPos())/2, 
-                    geom::Vec3(), is_sel ? sel_clr : nl[0].color1);
-          p1=va.Add(nl[1].atom.GetPos(), 
-                    geom::Vec3(), is_sel ? sel_clr : nl[1].color1);
+          const geom::Vec3& p0=a1.GetPos();
+          const geom::Vec3& p2=a2.GetPos();
+          geom::Vec3 p1=(p0+p2)*0.5;
+          va.AddCylinder(CylinderPrim(p0,p1,options_->GetTubeRadius(),nl[i-1].color1),
+                         options_->GetArcDetail());
+          va.AddCylinder(CylinderPrim(p1,p2,options_->GetTubeRadius(),nl[i].color1),
+                         options_->GetArcDetail());
+          a1=a2;
         }
-        va.AddLine(p0, p1);        
-        continue;
-      }
-      if (nl.GetSize()<3) {
-        continue;
-      }
-      VertexID p0;
-      geom::Vec3 z=geom::Normalize(nl[1].atom.GetPos()-nl[0].atom.GetPos());
-      geom::Vec3 y=geom::OrthogonalVector(z);
-      geom::Vec3 x=geom::Cross(y, z);
-      cursor_ori=geom::Mat3(x[0], y[0], z[0], x[1], y[1], z[1], 
-                            x[2], y[2], z[2]);    
-      if (nl.AtStart()==0) {
-        cursor_pos=nl[0].atom.GetPos();
-      } else {
-        cursor_pos=(nl[0].atom.GetPos()+nl[1].atom.GetPos())/2;
-      }
-      p0=this->AddCappedProfile(va, is_sel? sel_clr : nl[0].color1, 
-                                cursor_pos, cursor_ori, radius, true, n);
-      for (int i=1; i<nl.GetSize()-1;++i) {
-        const NodeEntry& entry=nl[i];
-        geom::Vec3 old_dir=geom::Normalize(entry.atom.GetPos()-cursor_pos);
-        cursor_pos=entry.atom.GetPos();
-
-        geom::Vec3 z=geom::Normalize(nl[i+1].atom.GetPos()-cursor_pos);
-        geom::Vec3 y=geom::Normalize(geom::Cross(z, cursor_ori.GetCol(0)));
-        geom::Vec3 x=geom::Normalize(geom::Cross(y, z));
-        geom::Vec3 iz=geom::Normalize(cursor_ori.GetCol(2)+z);
-
-        geom::Vec3 iy=geom::Normalize(geom::Cross(cursor_ori.GetCol(2), z));
-        geom::Vec3 ix=geom::Normalize(geom::Cross(iy, iz));
-
-        geom::Mat3 i_ori=geom::Mat3(ix[0], iy[0], iz[0], ix[1], iy[1], iz[1], 
-                                    ix[2], iy[2], iz[2]);                           
-        cursor_ori=geom::Mat3(x[0], y[0], z[0], x[1], y[1], z[1], 
-                              x[2], y[2], z[2]);
-        // TODO. The intersection of two cylinders is an ellipse. Use an 
-        //        elliptic profile instead of a circular profile.
-        VertexID p1=this->AddCircularProfile(va, is_sel ? sel_clr : entry.color1,
-                                             cursor_pos, i_ori, radius, n);
-        this->ConnectProfiles(p0, p1, n, old_dir, va);
-        p0=p1;
-      }
-      const NodeEntry& entry=nl[nl.GetSize()-1];      
-      if (nl.AtEnd()==0) {
-        cursor_pos=entry.atom.GetPos();
-      } else {
-        cursor_pos=(entry.atom.GetPos()+nl[nl.GetSize()-2].atom.GetPos())*0.5;
       }
-      VertexID p1 =this->AddCappedProfile(va, is_sel ? sel_clr : entry.color1, 
-                                          cursor_pos, cursor_ori, 
-                                          radius, false, n);
-      this->ConnectProfiles(p0, p1, n, cursor_ori.GetCol(2), va);      
     }
   }
   sel_state_=0;
   state_=0;
 }
-#endif
-
-VertexID TraceRenderer::AddCappedProfile(IndexedVertexArray& va, 
-                                         const Color& color,
-                                         const geom::Vec3& center, 
-                                         const geom::Mat3& ori, float radius, 
-                                         bool flip_normal,
-                                         int n)
-{
-   VertexID center_id=va.Add(center, geom::Vec3(), color);
-   VertexID first=this->AddCircularProfile(va, color, center, ori, radius, n);
-   for (int i=0; i<n; ++i) {
-     va.AddTriN(center_id, first+i, first+((i+1) % n));
-   }
-   return first;
-}
-
-VertexID TraceRenderer::AddCircularProfile(IndexedVertexArray& va, 
-                                           const Color& color,
-                                           const geom::Vec3& center, 
-                                           const geom::Mat3& ori, 
-                                           float radius, 
-                                           int n)
-{
-  float delta_angle=2*M_PI/n;
-  VertexID f=0;
-  geom::Vec3 normal=ori.GetRow(2);
-  for (int i=0; i<n; ++i) {
-    geom::Vec3 normal=ori*geom::Vec3(cos(i*delta_angle), 
-                                     sin(i*delta_angle), 0.0);
-    VertexID x=va.Add(center+normal*radius, normal, color);
-    if (i==0) {
-      f=x;
-    }
-  }
-  return f;
-}
-
-void TraceRenderer::ConnectProfiles(VertexID prof0, VertexID prof1, int n, 
-                                    const geom::Vec3& dir, 
-                                    IndexedVertexArray& va)
-{
-  // avoid twisting
-  int off=0;
-  float best=0.0;
-  geom::Vec3 pp=va.GetVert(prof0);
-  for (int i=0; i<n; ++i) {
-    geom::Vec3 dir2=geom::Normalize(va.GetVert(prof1+i)-pp);
-    float dot=fabs(geom::Dot(dir, dir2));
-    if (best<dot) {
-      best=dot;
-      off=i;
-    }
-  }
-  for (int i=0; i<n; ++i) {
-    VertexID i1=prof1+((i+off) % n), i2=prof1+((i+off+1) % n);
-    VertexID  i3=prof0+i, i4=prof0+((i+1)%n);
-    va.AddTriN(i1, i2, i3);
-    va.AddTriN(i2, i3, i4);
-  }
-}
 
 void TraceRenderer::RenderPov(PovState& pov, const std::string& name)
 {
+  if(trace_subset_.GetListCount()==0) return;
   pov.write_merge_or_union(name);
 
-  for (int node_list=0; node_list<trace_subset_.GetSize(); ++node_list) {
-    const NodeListSubset& nl=trace_subset_[node_list];
+  for (int node_list=0; node_list<trace_subset_.GetListCount(); ++node_list) {
+    const NodeEntryList& nl=trace_subset_.GetList(node_list);
 
     geom::Vec3 p0=nl[0].atom.GetPos();
     float rad0=0.2;
     Color col0=nl[0].color1;
     pov.write_sphere(p0,rad0,col0,name);
-    for (int i=1; i<nl.GetSize();++i) {
+    for (unsigned int i=1; i<nl.size();++i) {
       geom::Vec3 p1=nl[i].atom.GetPos();
       float rad1=0.2;
       Color col1=nl[i].color1;
@@ -264,11 +146,6 @@ void TraceRenderer::RenderPov(PovState& pov, const std::string& name)
   pov.inc() << " }\n";
 }
 
-void TraceRenderer::Render()
-{
-
-}
-
 bool TraceRenderer::CanSetOptions(RenderOptionsPtr& render_options)
 {
   return render_options.get()->GetRenderMode()==RenderMode::TRACE;
diff --git a/modules/gfx/src/impl/trace_renderer.hh b/modules/gfx/src/impl/trace_renderer.hh
index 77cb8d3daa3d1584b45d38ea125bc03f6181a470..e8f9cff3bd1f66650f797f7c29888553dd31371a 100644
--- a/modules/gfx/src/impl/trace_renderer.hh
+++ b/modules/gfx/src/impl/trace_renderer.hh
@@ -20,8 +20,9 @@
 #define OST_GFX_IMPL_TRACE_RENDERER_HH
 
 /*
-   Author: Marco Biasini
- */
+   Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #include <ost/gfx/impl/backbone_trace.hh>
 #include <ost/gfx/impl/entity_detail.hh>
 #include <ost/gfx/impl/trace_renderer_base.hh>
@@ -37,12 +38,12 @@ using namespace impl;
 /// \internal
 class DLLEXPORT_OST_GFX TraceRenderer: public TraceRendererBase {
 public:
-  TraceRenderer(BackboneTrace& trace);
+  TraceRenderer(BackboneTrace* trace);
 
   virtual void PrepareRendering();
-  virtual void PrepareRendering(TraceSubset& trace_subset, 
+  virtual void PrepareRendering(BackboneTrace& trace_subset, 
                                 IndexedVertexArray& va, bool is_sel);
-  virtual void Render();
+
   virtual void RenderPov(PovState& pov, const std::string& name);
 
   virtual bool CanSetOptions(RenderOptionsPtr& render_options);
@@ -51,14 +52,6 @@ public:
 
   virtual ~TraceRenderer();
 private:
-  VertexID AddCappedProfile(IndexedVertexArray& va, const Color& color,
-                            const geom::Vec3& center, const geom::Mat3& ori, 
-                            float radius, bool flip_normal, int n);
-  VertexID AddCircularProfile(IndexedVertexArray& va, const Color& color,
-                              const geom::Vec3& center, const geom::Mat3& ori,
-                              float radius, int n);
-  void ConnectProfiles(VertexID prof1, VertexID prof2, int n, 
-                       const geom::Vec3& dir, IndexedVertexArray& va);
   TraceRenderOptionsPtr  options_;
 };
 
diff --git a/modules/gfx/src/impl/trace_renderer_base.cc b/modules/gfx/src/impl/trace_renderer_base.cc
index 51c9c35d361abfd97021b550a7403b77ad3c725a..a63720b20c5105aaa051be4b8d4ee313bc8fe682 100644
--- a/modules/gfx/src/impl/trace_renderer_base.cc
+++ b/modules/gfx/src/impl/trace_renderer_base.cc
@@ -17,6 +17,10 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 
+/*
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
+
 #include <ost/gfx/scene.hh>
 
 #include "trace_renderer_base.hh"
@@ -34,25 +38,32 @@ void set_node_entry_color(NodeEntry& e, ColorMask mask,
 }
 
 template <typename T1>
-inline void apply_color_op(TraceRendererBase* rend, 
-                           TraceSubset& trace_subset, T1 get_col, 
-                           const ColorOp& op)
+inline void apply_color_op(TraceRendererBase* rend, BackboneTrace& trace_subset, T1 get_col, const ColorOp& op)
 {
   rend->UpdateViews();
   ColorMask mask = op.GetMask();
   mol::EntityView view;
   if(op.IsSelectionOnly()){
-    view = rend->GetEffectiveView().Select(op.GetSelection(),op.GetSelectionFlags());
+    mol::Query q(op.GetSelection());
+    for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+      NodeEntryList& nl=trace_subset.GetList(node_list);
+      for (unsigned int i=0; i<nl.size();++i) {
+        if (q.IsAtomSelected(nl[i].atom)) {
+          Color clr =get_col.ColorOfAtom(nl[i].atom);
+          set_node_entry_color(nl[i],mask,clr);
+        }
+      }
+    }
   }
   else{
-    view = op.GetView();
-  }
-  for (int node_list=0; node_list<trace_subset.GetSize(); ++node_list) {
-    NodeListSubset& nl=trace_subset[node_list];
-    for (int i=0; i<nl.GetSize();++i) {
-      if(view.FindAtom(nl[i].atom)){
-        Color clr =get_col.ColorOfAtom(nl[i].atom);
-        set_node_entry_color(nl[i],mask,clr);
+    mol::EntityView view = op.GetView();
+    for (int node_list=0; node_list<trace_subset.GetListCount(); ++node_list) {
+      NodeEntryList& nl=trace_subset.GetList(node_list);
+      for (unsigned int i=0; i<nl.size();++i) {
+        if(view.FindAtom(nl[i].atom)){
+          Color clr =get_col.ColorOfAtom(nl[i].atom);
+          set_node_entry_color(nl[i],mask,clr);
+        }
       }
     }
   }
@@ -61,57 +72,56 @@ inline void apply_color_op(TraceRendererBase* rend,
 
 } //ns
 
-TraceRendererBase::TraceRendererBase(BackboneTrace& trace, int n):
-  trace_(trace), trace_subset_(trace, n), sel_subset_(trace, n)
+TraceRendererBase::TraceRendererBase(BackboneTrace* trace, int n):
+  trace_(trace), trace_subset_(), sel_subset_()
 {
 }
 
 void TraceRendererBase::PrepareRendering()
 {
+  if (state_ & DIRTY_VA) {
+    trace_->OnUpdatedPositions();
+    trace_subset_.OnUpdatedPositions();
+    if(this->HasSelection()) sel_subset_.OnUpdatedPositions();
+    // don't clear DIRTY_VA flag - derived classed may depend on it
+  }
 }
 
 void TraceRendererBase::UpdateViews()
 {
   if (state_ & DIRTY_VIEW) {
     mol::EntityView view=this->GetEffectiveView();
-    trace_subset_.Update(view);
+    trace_subset_=trace_->CreateSubset(view);
     state_&=~DIRTY_VIEW;    
   }
   if (this->HasSelection() && (sel_state_ & DIRTY_VIEW)) {
-    sel_subset_.Update(sel_);
+    sel_subset_ = trace_->CreateSubset(sel_);
     sel_state_&=~DIRTY_VIEW;    
   }
 }
 
 geom::AlignedCuboid TraceRendererBase::GetBoundingBox() const
 {
-  geom::Vec3 mmin, mmax;
+  geom::Vec3 mmin(std::numeric_limits<float>::max(),
+		  std::numeric_limits<float>::max(),
+		  std::numeric_limits<float>::max());
+  geom::Vec3 mmax(-std::numeric_limits<float>::max(),
+		  -std::numeric_limits<float>::max(),
+		  -std::numeric_limits<float>::max());
+		  
   assert(!(state_ & DIRTY_VIEW));
-  bool empty=true;
-  for (int node_list=0; node_list<trace_subset_.GetSize(); ++node_list) {
-    // first build the spline
-    Spline spl;
-    const NodeListSubset& nl=trace_subset_[node_list];
-    for (int i=0; i<nl.GetSize();++i) {
+  for (int node_list=0; node_list<trace_subset_.GetListCount(); ++node_list) {
+    const NodeEntryList& nl=trace_subset_.GetList(node_list);
+    for (unsigned int i=0; i<nl.size();++i) {
       const NodeEntry& entry=nl[i];      
-      empty=false;
       geom::Vec3 p=entry.atom.GetPos();
-      if (node_list+i==0) {
-        mmin=p;
-        mmax=p;
-      } else {
-        mmin=geom::Min(mmin, p);
-        mmax=geom::Max(mmax, p);
-      }
+      mmin=geom::Min(mmin, p);
+      mmax=geom::Max(mmax, p);
     }
   }  
-  if (empty) {
-    throw Error("Can't calculate bounding box of empty renderer");
-  }
   return geom::AlignedCuboid(mmin, mmax);
 }
 
-
 void TraceRendererBase::Apply(const gfx::ByElementColorOp& op)
 {
   apply_color_op(this,trace_subset_,ByElementGetCol(),op);
@@ -146,16 +156,16 @@ void TraceRendererBase::Apply(const gfx::EntityViewColorOp& op)
 bool TraceRendererBase::HasDataToRender() const
 {
   assert(!(state_ & DIRTY_VIEW));
-  return this->trace_subset_.GetSize()>0;
+  return this->trace_subset_.GetListCount()>0;
 }
 
 void TraceRendererBase::set_node_colors(const Color& col, const mol::Query& q, 
                                         ColorMask mask)
 {
   this->UpdateViews();
-  for (int node_list=0; node_list<trace_subset_.GetSize(); ++node_list) {
-    NodeListSubset& nl=trace_subset_[node_list];
-    for (int i=0; i<nl.GetSize();++i) {
+  for (int node_list=0; node_list<trace_subset_.GetListCount(); ++node_list) {
+    NodeEntryList& nl=trace_subset_.GetList(node_list);
+    for (unsigned int i=0; i<nl.size();++i) {
       if(q.IsAtomSelected(nl[i].atom)) {
         set_node_entry_color(nl[i],mask,col);
       }
@@ -164,13 +174,6 @@ void TraceRendererBase::set_node_colors(const Color& col, const mol::Query& q,
   state_|=DIRTY_VA;  
 }
 
-void TraceRendererBase::set_node_entry_color(NodeEntry& e, ColorMask mask, 
-                                             const Color& c)
-{
-  if (mask & MAIN_COLOR) e.color1=c;
-  if (mask & DETAIL_COLOR) e.color2=c;
-}
-
 void TraceRendererBase::PickAtom(const geom::Line3& line, Real line_width,
                                  mol::AtomHandle& picked_atom)
 {
@@ -184,9 +187,9 @@ void TraceRendererBase::PickAtom(const geom::Line3& line, Real line_width,
   }
 
   mol::AtomHandle atom;
-  for (int node_list=0; node_list<trace_subset_.GetSize(); ++node_list) {
-    NodeListSubset& nl=trace_subset_[node_list];
-    for (int i=0; i<nl.GetSize();++i) {
+  for (int node_list=0; node_list<trace_subset_.GetListCount(); ++node_list) {
+    NodeEntryList& nl=trace_subset_.GetList(node_list);
+    for (unsigned int i=0; i<nl.size();++i) {
       geom::Vec3 p=nl[i].atom.GetPos();
       float dist = geom::Distance(line, p);
       if(dist<=max_dist) {
@@ -218,5 +221,53 @@ void TraceRendererBase::Apply(const gfx::MapHandleColorOp& op)
 }
 #endif
 
-}}}
+void TraceRendererBase::rebuild_sel(const SplineEntryListList& spline_list_list, 
+                                    SplineEntryListList& sel_spline_list_list,
+                                    const Color& sel_color)
+{
+  // extract spline segments from list_list that match 
+  // (via id) the selection subset
+  // first put all ids into a set for fast lookup
+  std::set<int> id_set;
+  for(int nlc=0;nlc<sel_subset_.GetListCount();++nlc) {
+    const NodeEntryList& nelist=sel_subset_.GetList(nlc);
+    for(NodeEntryList::const_iterator nit=nelist.begin();nit!=nelist.end();++nit) {
+      id_set.insert(nit->id);
+    }
+  }
+  // now find all matching spline segments
+  sel_spline_list_list.clear();
+  for(SplineEntryListList::const_iterator sit=spline_list_list.begin();sit!=spline_list_list.end();++sit) {
+    const SplineEntryList& slist=*sit;
+    SplineEntryList nlist;
+    unsigned int sc=0;
+    while(sc<slist.size()) {
+      int curr_id=slist.at(sc).id;
+      if(id_set.count(curr_id)>0) {
+        // if a match is found, add all until a new id is found
+        while(sc<slist.size() &&  slist.at(sc).id==curr_id) {
+          nlist.push_back(slist[sc++]);
+          // override with the selection color
+          nlist.back().color1=sel_color;
+          nlist.back().color2=sel_color;
+        }
+      } else {
+        // introduce break
+        if(!nlist.empty()) {
+          sel_spline_list_list.push_back(nlist);
+          nlist.clear();
+        }
+        // and advance to the next id
+        while(sc<slist.size() &&  slist.at(sc).id==curr_id) ++sc;
+      }
+    }
+    if(!nlist.empty()) {
+      sel_spline_list_list.push_back(nlist);
+      nlist.clear();
+    }
+  }
+}
+
+}}} // ns
+
 
diff --git a/modules/gfx/src/impl/trace_renderer_base.hh b/modules/gfx/src/impl/trace_renderer_base.hh
index b102e1cc2c78c5ad1f2881e8530f51fb21a1b205..bb8ef0515a1b43ece5b7c013a81474dddbf108b7 100644
--- a/modules/gfx/src/impl/trace_renderer_base.hh
+++ b/modules/gfx/src/impl/trace_renderer_base.hh
@@ -20,8 +20,8 @@
 #define OST_GFX_IMPL_TRACE_RENDERER_BASE_HH
 
 /*
-  Author: Marco Biasini
- */
+  Authors: Marco Biasini, Ansgar Philippsen
+*/
 
 #include <ost/gfx/module_config.hh>
 #include <ost/gfx/impl/entity_renderer.hh>
@@ -35,11 +35,11 @@ namespace ost { namespace gfx { namespace impl {
 ///     \ref "line trace" LineTraceRenderer and 
 ///     \ref "smooth trace" SlineRenderer.
 /// 
-/// The trace-based entity renderer share a  common instance of BackboneTrace 
-/// that encapulates a smoothed C-alpha trace.
+/// All trace-based entity renderers share a  common instance of BackboneTrace
+/// (which is held by gfx::Entity); it encapulates a smoothed C-alpha trace.
 class DLLEXPORT_OST_GFX TraceRendererBase : public EntityRenderer {
 public:
-  TraceRendererBase(BackboneTrace& trace, int overshoot);
+  TraceRendererBase(BackboneTrace* trace, int overshoot);
   
   virtual geom::AlignedCuboid GetBoundingBox() const;  
   
@@ -63,12 +63,14 @@ public:
 protected:
   
   void set_node_colors(const Color& c, const mol::Query& q, ColorMask mask);
-  void set_node_entry_color(NodeEntry& e, ColorMask mask, const Color& c);
-  
 
-  BackboneTrace& trace_;
-  TraceSubset    trace_subset_;
-  TraceSubset    sel_subset_;
+  void rebuild_sel(const SplineEntryListList& spline_list_list, 
+                   SplineEntryListList& sel_spline_list_list,
+                   const Color& sel_color);
+
+  BackboneTrace* trace_;
+  BackboneTrace trace_subset_;
+  BackboneTrace sel_subset_;
 };
 
 }}}
diff --git a/modules/gfx/src/map_iso.cc b/modules/gfx/src/map_iso.cc
index 1a9694663db465695d5f84ab8a3b95cacd8fbf0d..ce9729c18c006a237b96541a5cb33b977e016371 100644
--- a/modules/gfx/src/map_iso.cc
+++ b/modules/gfx/src/map_iso.cc
@@ -59,38 +59,6 @@ namespace ost {
 
 namespace gfx {
 
-MapIso::MapIso(const String& name, const img::MapHandle& mh, float level):
-  GfxObj(name),
-  original_mh_(mh),
-  downsampled_mh_(),
-  mh_(MapIso::DownsampleMap(mh)),
-  octree_(mh_),
-  stat_calculated_(false),
-  histogram_calculated_(false),
-  histogram_bin_count_(100),
-  level_(level),
-  normals_calculated_(false),
-  alg_(0),
-  smoothf_(0.2),
-  debug_octree_(false),
-  color_(Color::GREY)
-{
-  // TODO replace with def mat for this gfx obj type
-  if (mh_ != original_mh_) {
-    downsampled_mh_ = mh_;
-  }
-  octree_.Initialize();
-  SetMatAmb(Color(0,0,0));
-  SetMatDiff(Color(1,1,1));
-  SetMatSpec(Color(0.1,0.1,0.1));
-  SetMatShin(32);
-  mol::Transform tf=this->GetTF();
-  tf.SetCenter(this->GetCenter());
-  tf.SetTrans(this->GetCenter());
-  this->SetTF(tf);
-  Rebuild();
-}
-
 MapIso::MapIso(const String& name, const img::MapHandle& mh, 
                float level, uint a):
   GfxObj(name),
@@ -105,7 +73,7 @@ MapIso::MapIso(const String& name, const img::MapHandle& mh,
   normals_calculated_(false),
   alg_(a),
   debug_octree_(false),
-  color_(Color::GREY)  
+  color_(1.0,1.0,1.0)
 {
   // TODO replace with def mat for this gfx obj type
   if (mh_ != original_mh_) {
@@ -174,7 +142,7 @@ void MapIso::CustomPreRenderGL(bool flag)
   if(flag) {
     Rebuild();
   }
-  RefreshVA(va_);
+  //RefreshVA(va_);
 }
 
 namespace {
@@ -248,25 +216,17 @@ private:
 
 void MapIso::CustomRenderGL(RenderPass pass)
 {
-  switch (pass) {
-    case OPAQUE_RENDER_PASS:
-      glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-      va_.RenderGL();      
-      glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);      
-      break;
-    case STANDARD_RENDER_PASS:
-      va_.RenderGL();
-      if (debug_octree_) {
-        OctreeDebugger d(level_, mh_.IndexToCoord(img::Point(1,1,1))-
-                         mh_.IndexToCoord(img::Point(0,0,0)));
-        glPushAttrib(GL_ENABLE_BIT);
-        glDisable(GL_LIGHTING);
-        octree_.VisitDF(d);
-        glPopAttrib();
-      }
-      break;
-    case GLOW_RENDER_PASS:
-      return;
+  if(pass==STANDARD_RENDER_PASS) {
+    va_.RenderGL();
+    if (debug_octree_) {
+      OctreeDebugger d(level_,
+		       mh_.IndexToCoord(img::Point(1,1,1))-
+		       mh_.IndexToCoord(img::Point(0,0,0)));
+      glPushAttrib(GL_ENABLE_BIT);
+      glDisable(GL_LIGHTING);
+      octree_.VisitDF(d);
+      glPopAttrib();
+    }
   }
 }
 
diff --git a/modules/gfx/src/map_iso.hh b/modules/gfx/src/map_iso.hh
index 70319e7c7d310790d647d548902f1473da85f521..46923c7c7bc020b65015b5044dc47446f1d297c8 100644
--- a/modules/gfx/src/map_iso.hh
+++ b/modules/gfx/src/map_iso.hh
@@ -51,10 +51,7 @@ typedef boost::shared_ptr<MapIso> MapIsoP;
 /// \sa gfx::MapSlab
 class DLLEXPORT_OST_GFX MapIso: public GfxObj {
 public:
-  MapIso(const String& name, const img::MapHandle& mh,float level);
-
-  MapIso(const String& name, const img::MapHandle& mh,
-         float level, uint a);
+  MapIso(const String& name, const img::MapHandle& mh,float level, uint a=0);
 
   virtual geom::AlignedCuboid GetBoundingBox() const;
                              
diff --git a/modules/gfx/src/map_slab.cc b/modules/gfx/src/map_slab.cc
index 32da5912cf1a9fee1395c8f65e3e150c84e45670..3656eec4d716b69269167d4a16bdf52c727b2dd6 100644
--- a/modules/gfx/src/map_slab.cc
+++ b/modules/gfx/src/map_slab.cc
@@ -108,16 +108,9 @@ void MapSlab::CustomRenderGL(RenderPass pass)
 {
   if(rebuild_) rebuild_tex();
 
-  if(GetOpacity()<1.0) {
-    if(pass!=1) return;
-    glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
+  if(pass==STANDARD_RENDER_PASS) {
     render_slab();
-    glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
-  } else {
-    if(pass!=0) return;
   }
-
-  render_slab();
 }
 
 void MapSlab::CustomRenderPov(PovState& pov)
diff --git a/modules/gfx/src/map_slab.hh b/modules/gfx/src/map_slab.hh
index 3af06bd5ae3d59713dd39ffdcc0ff3f214cb42ac..d08ba2da57ae32bf7fb579c3ba37be2e1b37086b 100644
--- a/modules/gfx/src/map_slab.hh
+++ b/modules/gfx/src/map_slab.hh
@@ -29,9 +29,9 @@
 #include <ost/geom/geom.hh>
 
 #include <ost/img/map.hh>
-#include <ost/gfx/gl_include.hh>
 
 #include "gfx_object.hh"
+#include "glext_include.hh"
 
 namespace ost { namespace gfx {
 
diff --git a/modules/gfx/src/offscreen_buffer.hh b/modules/gfx/src/offscreen_buffer.hh
index c033d88169fe949febf3385df9fd4d5a6fdfa0d4..8270d1579eb16e146b6202277266ccd9a4be3a64 100644
--- a/modules/gfx/src/offscreen_buffer.hh
+++ b/modules/gfx/src/offscreen_buffer.hh
@@ -22,86 +22,54 @@
 /*
   Wraps GL offscreen rendering per platform
 
-  Authors: Ansgar Philippsen, Marco Biasini
+  boilerplate header, includes platform dependent stuff
 */
 
-#include <ost/gfx/gl_include.hh>
-
-#if defined(__linux__)
-#  include <GL/glx.h>
-#elif defined(__APPLE__)
-#  include <OpenGL/OpenGL.h>
-//#elif defined(_WIN32)
-//#  include <ost/gfx/GL/wglew.h>
-#endif
-
-#ifdef Complex
-#  undef Complex
-#endif
+#include <vector>
 
 namespace ost { namespace gfx {
 
-/// \brief offscreen management
-class OffscreenBuffer {
+class OffscreenBufferFormat
+{
 public:
-  
-  /// \brief singleton interface
-  static OffscreenBuffer& Instance();
+  OffscreenBufferFormat(): cbits(8),abits(8),dbits(12),accum(false),multisample(false),samples(0) {}
 
-  /// \brief activate offscreen context for rendering
-  bool Begin();
-  /// \brief switch back to normal rendering context
-  bool End();
-  /// \ brief resize offscreen rendering context
-  bool Resize(unsigned int width, unsigned int height);
+  unsigned int cbits,abits,dbits; // color, alpha, depth bits
+  bool accum;
+  bool multisample;
+  unsigned int samples;
+};
 
-  /// \brief returns true if offscreen rendering context is available
-  bool IsValid() const;
+}} // ns
 
-  /// \brief returns true between Begin/End bracket
-  bool IsActive() const;
+/* 
+   instead of creating an abstract base class and
+   making runtime polymorphic classes for each
+   platform, we do a bit more typing and copy
+   the minimal interface to each of the platform
+   specific OffscreenBuffer implementations
 
-private:
-  OffscreenBuffer(int width, int height, int r_bits, int b_bits, 
-                  int g_bits, int a_bits, int depth_bits);
+   OffscreenBuffer interface:
 
-  OffscreenBuffer(const OffscreenBuffer& b) {}
-  OffscreenBuffer& operator=(const OffscreenBuffer& b) {return *this;}
-  
-  int width_;
-  int height_;
-  bool valid_;
-  bool active_;
+   OffscreenBuffer(unsigned int width, unsigned int height, const OffscreenBufferFormat& f, bool shared=true);
+   bool Resize(unsigned int w, unsigned int h);
+   bool MakeActive();
+   bool IsActive();
+   bool IsValid();
+*/
 
 #if defined(__linux__)
-  Display*    dpy_;
-  GLXFBConfig* fbconfig_;
-  GLXPbuffer  pbuffer_;
-  GLXContext  context_;
-  GLXContext  old_context_;
-  GLXDrawable        old_dr1_;
-  GLXDrawable        old_dr2_;
-
+#include "impl/glx_offscreen_buffer.hh"
 #elif defined(__APPLE__)
-
-  CGLPBufferObj      pbuffer_;
-  CGLContextObj      context_;
-  CGLPixelFormatObj  pix_format_;
-  CGLContextObj      old_context_;
-
-#elif defined(_WIN32)
-/*  HPBUFFERARB        pbuffer_;
-  HGLRC              context_; //rendering context
-  HGLRC              old_context_;
-  
-  HDC                dev_context_;//device context
-  HDC                old_dev_context_;
-  */
+#include "impl/cgl_offscreen_buffer.hh"
+#elif defined(_MSC_VER)
+#include "impl/wgl_offscreen_buffer.hh"
+#else
+#error platform not found for offscreen rendering
 #endif
-
-  GLint       old_vp_[4];
-};
  
-}}
+#ifdef Complex
+#  undef Complex
+#endif
 
 #endif
diff --git a/modules/gfx/src/prim_list.cc b/modules/gfx/src/prim_list.cc
index 2302dc7fea417ff6c07748da0d0a5c1c0c11ed5e..e92c1477cddb57c477fbb7cbbaa05984fffe129d 100644
--- a/modules/gfx/src/prim_list.cc
+++ b/modules/gfx/src/prim_list.cc
@@ -23,6 +23,7 @@
 #include "scene.hh"
 
 #include "prim_list.hh"
+#include "povray.hh"
 
 namespace ost { namespace gfx {
 
@@ -31,7 +32,8 @@ PrimList::PrimList(const String& name):
   points_(),
   lines_(),
   radius_(0.5),
-  diameter_(0.5)
+  sphere_detail_(4),
+  arc_detail_(4)
 {}
 
 void PrimList::Clear()
@@ -39,6 +41,7 @@ void PrimList::Clear()
   points_.clear();
   lines_.clear();
   Scene::Instance().RequestRedraw();
+  this->FlagRebuild();
 }
 
 void PrimList::ProcessLimits(geom::Vec3& minc, geom::Vec3& maxc, 
@@ -95,8 +98,6 @@ void PrimList::CustomPreRenderGL(bool flag)
     } else {
       render_simple();
     }
-  } else {
-    RefreshVA(va_);
   }
 }
 
@@ -129,12 +130,25 @@ struct AALineEntryLess
 
 void PrimList::CustomRenderGL(RenderPass pass)
 {
-  if(pass!=STANDARD_RENDER_PASS) return;
-  va_.RenderGL();
+  if(pass==STANDARD_RENDER_PASS || pass==TRANSPARENT_RENDER_PASS) {
+    va_.RenderGL();
+  }
 }
 
 void PrimList::CustomRenderPov(PovState& pov)
 {
+  if(points_.empty() && lines_.empty()) return;
+  pov.write_merge_or_union(GetName());
+
+  for(PointEntryList::const_iterator it=points_.begin();it!=points_.end();++it) {
+    pov.write_sphere(it->pos,radius_,it->color,GetName());
+  }
+  for(LineEntryList::const_iterator it=lines_.begin();it!=lines_.end();++it) {
+    pov.write_sphere(it->pos1,radius_,it->color,GetName());
+    pov.write_sphere(it->pos2,radius_,it->color,GetName());
+    pov.write_cyl(it->pos1,it->pos2,radius_,it->color,GetName(),true);
+  }
+  pov.inc() << " }\n";
 }
 
 void PrimList::AddPoint(geom::Vec3& p, const Color& col)
@@ -153,14 +167,30 @@ void PrimList::AddLine(geom::Vec3& p1, geom::Vec3& p2, const Color& col)
 
 void PrimList::SetDiameter(float d)
 {
-  diameter_=d;
+  radius_=d*0.5;
   Scene::Instance().RequestRedraw();
+  FlagRebuild();
 }
 
 void PrimList::SetRadius(float r)
 {
   radius_=r;
   Scene::Instance().RequestRedraw();
+  FlagRebuild();
+}
+
+void PrimList::SetSphereDetail(unsigned int d)
+{
+  sphere_detail_=d;
+  Scene::Instance().RequestRedraw();
+  FlagRebuild();
+}
+
+void PrimList::SetArcDetail(unsigned int d)
+{
+  arc_detail_=d;
+  Scene::Instance().RequestRedraw();
+  FlagRebuild();
 }
 
 void PrimList::SetColor(const Color& c)
@@ -169,6 +199,7 @@ void PrimList::SetColor(const Color& c)
     it->color=c;
   }
   Scene::Instance().RequestRedraw();
+  FlagRebuild();
 }
 
 
@@ -210,11 +241,11 @@ void PrimList::render_custom()
   }
 
   for(LineEntryList::const_iterator it=lines_.begin();it!=lines_.end();++it) {
-    va_.AddSphere(SpherePrim(it->pos1, diameter_/2.0, it->color),
+    va_.AddSphere(SpherePrim(it->pos1, radius_, it->color),
                   GetSphereDetail());
-    va_.AddSphere(SpherePrim(it->pos2, diameter_/2.0, it->color),
+    va_.AddSphere(SpherePrim(it->pos2, radius_, it->color),
                   GetSphereDetail());
-    va_.AddCylinder(CylinderPrim(it->pos1,it->pos2,diameter_/2.0,it->color),
+    va_.AddCylinder(CylinderPrim(it->pos1,it->pos2,radius_,it->color),
                     GetArcDetail());
   }
 }
diff --git a/modules/gfx/src/prim_list.hh b/modules/gfx/src/prim_list.hh
index 1de40d7f9c862cc71fd995b7fd8d5c300c081304..b4aa65b98a3c601b913376b4c857c8d4aedda18d 100644
--- a/modules/gfx/src/prim_list.hh
+++ b/modules/gfx/src/prim_list.hh
@@ -74,6 +74,7 @@ class DLLEXPORT_OST_GFX PrimList: public GfxObj
                              const mol::Transform& tf) const;
   /// \brief get center      
   virtual geom::Vec3 GetCenter() const;
+
   virtual void CustomRenderPov(PovState& pov);
 
   virtual void CustomRenderGL(RenderPass pass);
@@ -98,6 +99,12 @@ class DLLEXPORT_OST_GFX PrimList: public GfxObj
   /// \brief set global prims color, overriding individual ones
   void SetColor(const Color& c);
 
+  void SetSphereDetail(unsigned int d);
+  unsigned int GetSphereDetail() const {return sphere_detail_;}
+
+  void SetArcDetail(unsigned int d);
+  unsigned int GetArcDetail() const {return arc_detail_;}
+
  protected:
   virtual void CustomPreRenderGL(bool flag);
 
@@ -106,6 +113,8 @@ class DLLEXPORT_OST_GFX PrimList: public GfxObj
   LineEntryList lines_;
   float radius_;
   float diameter_;
+  unsigned int sphere_detail_;
+  unsigned int arc_detail_;
   
   void render_simple();
   void render_custom();
diff --git a/modules/gfx/src/primitives.cc b/modules/gfx/src/primitives.cc
index 712a9077a58c97fb202179987982e49b572d100b..5c0d0650e3ee2785caa65e896276d2c300747308 100644
--- a/modules/gfx/src/primitives.cc
+++ b/modules/gfx/src/primitives.cc
@@ -30,8 +30,8 @@
 namespace ost { namespace gfx {
 
 Primitive::Primitive(const String& name):
-  GfxNode(name), fill_(true), line_(true), outline_color_(gfx::Color::WHITE), 
-  fill_color_(gfx::Color::LIGHT_GREY), line_width_(1.0)
+  GfxNode(name), fill_(true), line_(true), outline_color_(1.0,1.0,1.0), 
+  fill_color_(0.8,0.8,0.8), line_width_(1.0)
 {
   
 }
@@ -225,7 +225,7 @@ void Quad::RenderGL(RenderPass pass)
   if (!this->IsVisible()) {
     return;
   }
-  if (!(pass==OPAQUE_RENDER_PASS || pass==STANDARD_RENDER_PASS)) {
+  if (!(pass==DEPTH_RENDER_PASS || pass==STANDARD_RENDER_PASS)) {
     return;
   }
     glDisable(GL_LIGHTING);
diff --git a/modules/gfx/src/render_options/cartoon_render_options.cc b/modules/gfx/src/render_options/cartoon_render_options.cc
index da5d2e70376999782799e027b87586530b9016ed..e4ed3db3cdf17d241ac727c580852edb5c270341 100644
--- a/modules/gfx/src/render_options/cartoon_render_options.cc
+++ b/modules/gfx/src/render_options/cartoon_render_options.cc
@@ -1,3 +1,4 @@
+
 //------------------------------------------------------------------------------
 // This file is part of the OpenStructure project <www.openstructure.org>
 //
@@ -22,9 +23,7 @@
 
 #include "cartoon_render_options.hh"
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 CartoonRenderOptions::CartoonRenderOptions(bool force_tube):
   force_tube_(force_tube),
@@ -39,10 +38,13 @@ CartoonRenderOptions::CartoonRenderOptions(bool force_tube):
   helix_thickness_(0.2),
   helix_ecc_(0.3),
   helix_profile_(1),
+  helix_mode_(0),
   strand_width_(1.2),
   strand_thickness_(0.2),
   strand_ecc_(0.3),
-  strand_profile_(1)
+  strand_profile_(1),
+  strand_mode_(0),
+  color_blend_mode_(0)
 {}
 
 RenderMode::Type CartoonRenderOptions::GetRenderMode(){
@@ -66,12 +68,17 @@ void CartoonRenderOptions::ApplyRenderOptions(RenderOptionsPtr render_options){
   smooth_factor_=options->GetNormalSmoothFactor();
   tube_radius_=options->GetTubeRadius();
   tube_ratio_=options->GetTubeRatio();
+  tube_profile_=options->GetTubeProfileType();
   helix_width_=options->GetHelixWidth();
   helix_thickness_=options->GetHelixThickness();
   helix_ecc_=options->GetHelixEcc();
+  helix_profile_=options->GetHelixProfileType();
+  helix_mode_=options->GetHelixMode();
   strand_width_=options->GetStrandWidth();
   strand_thickness_=options->GetStrandThickness();
   strand_ecc_=options->GetStrandEcc();
+  strand_profile_=options->GetStrandProfileType();
+  strand_mode_=options->GetStrandMode();
   this->NotifyStateChange();
 }
 
@@ -196,6 +203,17 @@ void CartoonRenderOptions::SetHelixProfileType(unsigned int t)
   this->NotifyStateChange();
 }
 
+unsigned int CartoonRenderOptions::GetHelixMode() const
+{
+  return helix_mode_;
+}
+
+void CartoonRenderOptions::SetHelixMode(unsigned int m)
+{
+  helix_mode_=m;
+  this->NotifyStateChange();
+}
+
 void CartoonRenderOptions::SetStrandWidth(float strand_width){
   if(strand_width_ != strand_width){
     strand_width_= strand_width>0.0 ? strand_width : strand_width_;
@@ -240,6 +258,27 @@ void CartoonRenderOptions::SetStrandProfileType(unsigned int t)
   this->NotifyStateChange();
 }
 
+unsigned int CartoonRenderOptions::GetStrandMode() const
+{
+  return strand_mode_;
+}
+
+void CartoonRenderOptions::SetStrandMode(unsigned int m)
+{
+  strand_mode_=m;
+  this->NotifyStateChange();
+}
+
+void CartoonRenderOptions::SetColorBlendMode(unsigned int m)
+{
+  color_blend_mode_=m;
+  this->NotifyStateChange();
+}
+unsigned int CartoonRenderOptions::GetColorBlendMode() const
+{
+  return color_blend_mode_;
+}
+
 float CartoonRenderOptions::GetMaxRad() const{
   float max_rad=std::max(float(3.0),tube_radius_*tube_ratio_);
   max_rad=std::max(max_rad,tube_radius_);
@@ -250,8 +289,5 @@ float CartoonRenderOptions::GetMaxRad() const{
   return max_rad;
 }
 
-CartoonRenderOptions::~CartoonRenderOptions() {}
+}} // ns
 
-}
-
-}
diff --git a/modules/gfx/src/render_options/cartoon_render_options.hh b/modules/gfx/src/render_options/cartoon_render_options.hh
index 092fafe69f85cf55a6e6a29592288ac53b8e5566..8cb855567c1632c6d3caa517d00d531212c82e5f 100644
--- a/modules/gfx/src/render_options/cartoon_render_options.hh
+++ b/modules/gfx/src/render_options/cartoon_render_options.hh
@@ -27,60 +27,66 @@
 
 #include <ost/gfx/module_config.hh>
 
-#include <ost/gfx/render_options/render_options.hh>
+#include "render_options.hh"
 
 namespace ost { namespace gfx {
 
-class DLLEXPORT_OST_GFX CartoonRenderOptions: public ost::gfx::RenderOptions {
+class DLLEXPORT_OST_GFX CartoonRenderOptions: public RenderOptions {
 public:
   CartoonRenderOptions(bool force_tube=false);
 
+  // RenderOptions interface
   virtual RenderMode::Type GetRenderMode();
-
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual void SetSplineDetail(uint spline_detail);
-  virtual uint GetSplineDetail() const;
-
-  virtual void SetPolyMode(uint poly_mode);
-  virtual uint GetPolyMode() const;
-
-  virtual void SetArcDetail(uint arc_detail);
-  virtual uint GetArcDetail() const;
-
-  virtual void SetNormalSmoothFactor(float smooth_factor);
-  virtual float GetNormalSmoothFactor() const;
-
-  virtual void SetTubeRadius(float tube_radius);
-  virtual float GetTubeRadius() const;
-  virtual void SetTubeRatio(float tube_ratio);
-  virtual float GetTubeRatio() const;
-  virtual unsigned int GetTubeProfileType() const;
-  virtual void SetTubeProfileType(unsigned int);
-
-  virtual void SetHelixWidth(float helix_width);
-  virtual float GetHelixWidth() const;
-  virtual void SetHelixThickness(float helix_thickness);
-  virtual float GetHelixThickness() const;
-  virtual void SetHelixEcc(float helix_ecc);
-  virtual float GetHelixEcc() const;
-  virtual unsigned int GetHelixProfileType() const;
-  virtual void SetHelixProfileType(unsigned int);
-
-  virtual void SetStrandWidth(float strand_width);
-  virtual float GetStrandWidth() const;
-  virtual void SetStrandThickness(float strand_thickness);
-  virtual float GetStrandThickness() const;
-  virtual void SetStrandEcc(float strand_ecc);
-  virtual float GetStrandEcc() const;
-  virtual unsigned int GetStrandProfileType() const;
-  virtual void SetStrandProfileType(unsigned int);
+  // own interface
+  void SetSplineDetail(uint spline_detail);
+  uint GetSplineDetail() const;
+
+  void SetPolyMode(uint poly_mode);
+  uint GetPolyMode() const;
+
+  void SetArcDetail(uint arc_detail);
+  uint GetArcDetail() const;
+
+  void SetNormalSmoothFactor(float smooth_factor);
+  float GetNormalSmoothFactor() const;
+
+  void SetTubeRadius(float tube_radius);
+  float GetTubeRadius() const;
+  void SetTubeRatio(float tube_ratio);
+  float GetTubeRatio() const;
+  unsigned int GetTubeProfileType() const;
+  void SetTubeProfileType(unsigned int);
+
+  void SetHelixWidth(float helix_width);
+  float GetHelixWidth() const;
+  void SetHelixThickness(float helix_thickness);
+  float GetHelixThickness() const;
+  void SetHelixEcc(float helix_ecc);
+  float GetHelixEcc() const;
+  unsigned int GetHelixProfileType() const;
+  void SetHelixProfileType(unsigned int);
+  unsigned int GetHelixMode() const;
+  void SetHelixMode(unsigned int);
+
+  void SetStrandWidth(float strand_width);
+  float GetStrandWidth() const;
+  void SetStrandThickness(float strand_thickness);
+  float GetStrandThickness() const;
+  void SetStrandEcc(float strand_ecc);
+  float GetStrandEcc() const;
+  unsigned int GetStrandProfileType() const;
+  void SetStrandProfileType(unsigned int);
+  unsigned int GetStrandMode() const;
+  void SetStrandMode(unsigned int);
+
+  void SetColorBlendMode(unsigned int);
+  unsigned int GetColorBlendMode() const;
 
   float GetMaxRad() const;
 
-  virtual ~CartoonRenderOptions();
-
 private:
   bool force_tube_;
   uint spline_detail_;
@@ -96,10 +102,14 @@ private:
   float helix_thickness_;
   float helix_ecc_;
   unsigned int helix_profile_;
+  unsigned int helix_mode_;
   float strand_width_;
   float strand_thickness_;
   float strand_ecc_;
   unsigned int strand_profile_;
+  unsigned int strand_mode_;
+
+  unsigned int color_blend_mode_;
 };
 
 typedef boost::shared_ptr<CartoonRenderOptions> CartoonRenderOptionsPtr;
diff --git a/modules/gfx/src/render_options/cpk_render_options.cc b/modules/gfx/src/render_options/cpk_render_options.cc
index 611db0f48b7de674a82ceb956bec2589bbb23dd8..1413e582fc66cd73e86cffb3a1ef460a3a274152 100644
--- a/modules/gfx/src/render_options/cpk_render_options.cc
+++ b/modules/gfx/src/render_options/cpk_render_options.cc
@@ -22,9 +22,7 @@
 
 #include "cpk_render_options.hh"
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 CPKRenderOptions::CPKRenderOptions(): sphere_detail_(4) {
 #if OST_SHADER_SUPPORT_ENABLED
@@ -46,7 +44,7 @@ void CPKRenderOptions::ApplyRenderOptions(RenderOptionsPtr render_options){
   CPKRenderOptionsPtr options = boost::static_pointer_cast<CPKRenderOptions>(render_options);
 
   sphere_detail_=options->GetSphereDetail();
-  cpk_mode_=options->GetCPKMode();
+  cpk_mode_=options->GetSphereMode();
   this->NotifyStateChange();
 }
 
@@ -61,19 +59,15 @@ uint CPKRenderOptions::GetSphereDetail(){
   return sphere_detail_;
 }
 
-void CPKRenderOptions::SetCPKMode(uint mode){
+void CPKRenderOptions::SetSphereMode(uint mode){
   if(cpk_mode_!=mode) {
     cpk_mode_=mode;
     this->NotifyStateChange();
   }
 }
 
-uint CPKRenderOptions::GetCPKMode(){
+uint CPKRenderOptions::GetSphereMode(){
   return cpk_mode_;
 }
 
-CPKRenderOptions::~CPKRenderOptions() {}
-
-}
-
-}
+}} // ns
diff --git a/modules/gfx/src/render_options/cpk_render_options.hh b/modules/gfx/src/render_options/cpk_render_options.hh
index 079822fbdb2d5fd76872df6d6c34cf32c6ec0d4e..64da852289a8e3e36e5b3129172daed126dacbfd 100644
--- a/modules/gfx/src/render_options/cpk_render_options.hh
+++ b/modules/gfx/src/render_options/cpk_render_options.hh
@@ -27,7 +27,8 @@
 #include <ost/base.hh>
 
 #include <ost/gfx/module_config.hh>
-#include <ost/gfx/render_options/render_options.hh>
+
+#include "render_options.hh"
 
 namespace ost { namespace gfx {
 
@@ -35,23 +36,20 @@ class DLLEXPORT_OST_GFX CPKRenderOptions: public RenderOptions {
 public:
   CPKRenderOptions();
 
+  // RenderOptions interface
   virtual RenderMode::Type GetRenderMode();
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual void SetSphereDetail(uint detail);
-  virtual uint GetSphereDetail();
-
-  virtual void SetCPKMode(uint mode);
-  virtual uint GetCPKMode();
-
-
-  virtual ~CPKRenderOptions();
+  // own interface
+  void SetSphereDetail(uint detail);
+  uint GetSphereDetail();
+  void SetSphereMode(uint mode);
+  uint GetSphereMode();
 
 private:
   uint sphere_detail_;
   uint cpk_mode_;
-
 };
 
 typedef boost::shared_ptr<CPKRenderOptions> CPKRenderOptionsPtr;
diff --git a/modules/gfx/src/render_options/custom_render_options.cc b/modules/gfx/src/render_options/custom_render_options.cc
index eb4f62a43957d83045f1155939fb4e0758a2504c..bfce28e3f19a73f4ec6ff61882de8e4a8e123e54 100644
--- a/modules/gfx/src/render_options/custom_render_options.cc
+++ b/modules/gfx/src/render_options/custom_render_options.cc
@@ -22,9 +22,7 @@
 
 #include "custom_render_options.hh"
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 CustomRenderOptions::CustomRenderOptions(): 
   sphere_detail_(4),
@@ -99,8 +97,4 @@ float CustomRenderOptions::GetBondRad() const
   return bond_rad_;
 }
 
-CustomRenderOptions::~CustomRenderOptions() {}
-
-}
-
-}
+}} // ns
diff --git a/modules/gfx/src/render_options/custom_render_options.hh b/modules/gfx/src/render_options/custom_render_options.hh
index 03e9aa63577066e97e90dffdd443687010f495d2..35ef6d5209c3cc64b65578e668c593913bf97fbd 100644
--- a/modules/gfx/src/render_options/custom_render_options.hh
+++ b/modules/gfx/src/render_options/custom_render_options.hh
@@ -27,33 +27,30 @@
 #include <ost/base.hh>
 
 #include <ost/gfx/module_config.hh>
-#include <ost/gfx/render_options/render_options.hh>
+
+#include "render_options.hh"
 
 namespace ost {namespace gfx {
 
-class DLLEXPORT_OST_GFX CustomRenderOptions: public ost::gfx::RenderOptions {
+class DLLEXPORT_OST_GFX CustomRenderOptions: public RenderOptions {
 public:
   CustomRenderOptions();
 
+  // RenderOptions interface
   virtual RenderMode::Type GetRenderMode();
-
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual void SetSphereDetail(uint sphere_detail);
-  virtual uint GetSphereDetail();
-
-  virtual void SetArcDetail(uint arc_detail);
-  virtual uint GetArcDetail();
-
+  // own interface
+  void SetSphereDetail(uint sphere_detail);
+  uint GetSphereDetail();
+  void SetArcDetail(uint arc_detail);
+  uint GetArcDetail();
   void SetSphereRad(float r);
   float GetSphereRad() const;
-
   void SetBondRad(float r);
   float GetBondRad() const;
 
-  virtual ~CustomRenderOptions();
-
 private:
   uint sphere_detail_;
   uint arc_detail_;
diff --git a/modules/gfx/src/render_options/line_render_options.cc b/modules/gfx/src/render_options/line_render_options.cc
index 095d6dcaa996ad2e8c42be38868e2aedc9d562d4..5239243b9bd1edb6e3519bdc64e75e2489f0c7f5 100644
--- a/modules/gfx/src/render_options/line_render_options.cc
+++ b/modules/gfx/src/render_options/line_render_options.cc
@@ -22,9 +22,7 @@
 #include "line_render_options.hh"
 
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 LineRenderOptions::LineRenderOptions(): line_width_(2.0), aa_lines_(false){}
 
@@ -58,8 +56,4 @@ bool LineRenderOptions::GetAALines(){
   return aa_lines_;
 }
 
-LineRenderOptions::~LineRenderOptions() {}
-
-}
-
-}
+}} // ns
diff --git a/modules/gfx/src/render_options/line_render_options.hh b/modules/gfx/src/render_options/line_render_options.hh
index 886c1c34cab74f378133915db38cb365ad20c8dd..c96759596e976d4bc4e27141b143c6b63c169727 100644
--- a/modules/gfx/src/render_options/line_render_options.hh
+++ b/modules/gfx/src/render_options/line_render_options.hh
@@ -29,35 +29,30 @@
 
 #include "render_options.hh"
 
-namespace ost {
+namespace ost { namespace gfx {
 
-namespace gfx {
-
-class DLLEXPORT_OST_GFX LineRenderOptions: public ost::gfx::RenderOptions {
+class DLLEXPORT_OST_GFX LineRenderOptions: public RenderOptions {
 public:
   LineRenderOptions();
 
+  // partial RenderOptions interface
+  //virtual RenderMode::Type GetRenderMode()=0;
+  //virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options)=0;
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual void SetLineWidth(float line_width);
-  virtual float GetLineWidth();
-
-  virtual void SetAALines(bool aa_lines);
-  virtual bool GetAALines();
-
-
-  virtual ~LineRenderOptions();
+  void SetLineWidth(float line_width);
+  float GetLineWidth();
+  void SetAALines(bool aa_lines);
+  bool GetAALines();
 
 private:
   float line_width_;
   bool aa_lines_;
-
 };
 
 typedef boost::shared_ptr<LineRenderOptions> LineRenderOptionsPtr;
 
-}
+}} // ns
 
-}
+#endif
 
-#endif /* OST_GFX_SIMPLE_RENDER_OPTIONS_HH */
diff --git a/modules/gfx/src/render_options/line_trace_render_options.cc b/modules/gfx/src/render_options/line_trace_render_options.cc
index eb9fede1ba456f042e59059dff2038f56b50374e..afff2bf7965bd56dc904d0098ff14b9fbf3b0394 100644
--- a/modules/gfx/src/render_options/line_trace_render_options.cc
+++ b/modules/gfx/src/render_options/line_trace_render_options.cc
@@ -22,11 +22,10 @@
 
 #include "line_trace_render_options.hh"
 
-namespace ost {
+namespace ost { namespace gfx {
 
-namespace gfx {
-
-LineTraceRenderOptions::LineTraceRenderOptions(){}
+LineTraceRenderOptions::LineTraceRenderOptions()
+{}
 
 RenderMode::Type LineTraceRenderOptions::GetRenderMode(){
  return RenderMode::LINE_TRACE;
@@ -36,8 +35,4 @@ bool LineTraceRenderOptions::CanApplyRenderOptions(RenderOptionsPtr render_optio
   return render_options.get()->GetRenderMode()==RenderMode::LINE_TRACE;
 }
 
-LineTraceRenderOptions::~LineTraceRenderOptions() {}
-
-}
-
-}
+}} // ns
diff --git a/modules/gfx/src/render_options/line_trace_render_options.hh b/modules/gfx/src/render_options/line_trace_render_options.hh
index d7cce672cb26f52a1f77aa2b7fa55643b0c74699..114f4888bf12690e8301af6c3d34a6ba181920c1 100644
--- a/modules/gfx/src/render_options/line_trace_render_options.hh
+++ b/modules/gfx/src/render_options/line_trace_render_options.hh
@@ -26,20 +26,18 @@
 #include <boost/shared_ptr.hpp>
 
 #include <ost/gfx/module_config.hh>
-#include <ost/gfx/render_options/line_render_options.hh>
 
-namespace ost {
+#include "line_render_options.hh"
 
-namespace gfx {
+namespace ost { namespace gfx {
 
-class DLLEXPORT_OST_GFX LineTraceRenderOptions: public ost::gfx::LineRenderOptions {
+class DLLEXPORT_OST_GFX LineTraceRenderOptions: public LineRenderOptions {
 public:
   LineTraceRenderOptions();
 
+  // remaining RenderOptions interface not define in LineRenderOptions
   virtual RenderMode::Type GetRenderMode();
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
-
-  virtual ~LineTraceRenderOptions();
 };
 
 typedef boost::shared_ptr<LineTraceRenderOptions> LineTraceRenderOptionsPtr;
diff --git a/modules/gfx/src/render_options/render_options.cc b/modules/gfx/src/render_options/render_options.cc
index 5fd1f747b23c205f1db23ce5211e9d9f67f2d354..b7898657eedd80cd02ba7f1595289d276da53c21 100644
--- a/modules/gfx/src/render_options/render_options.cc
+++ b/modules/gfx/src/render_options/render_options.cc
@@ -60,5 +60,4 @@ void RenderOptions::NotifyStateChange()
   }
 }
 
-
-}}
+}} // ns
diff --git a/modules/gfx/src/render_options/render_options.hh b/modules/gfx/src/render_options/render_options.hh
index 234b35003d7eea355b85a2be922bdf6d1489d871..419528da9ec36e1b4a6f8006d92264503197aab7 100644
--- a/modules/gfx/src/render_options/render_options.hh
+++ b/modules/gfx/src/render_options/render_options.hh
@@ -40,15 +40,15 @@ typedef boost::shared_ptr<RenderOptions> RenderOptionsPtr;
 class DLLEXPORT_OST_GFX RenderOptions {
 public:
   RenderOptions();
+  virtual ~RenderOptions(){}
+
   virtual RenderMode::Type GetRenderMode()=0;
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options)=0;
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options)=0;
 
-  virtual bool AddObserver( EntityP entity);
-  virtual bool RemoveObserver( EntityP entity);
-  virtual void NotifyStateChange();
-
-  virtual ~RenderOptions(){}
+  bool AddObserver( EntityP entity);
+  bool RemoveObserver( EntityP entity);
+  void NotifyStateChange();
 
 private:
   typedef std::vector< EntityP > EntityPObservers;
diff --git a/modules/gfx/src/render_options/simple_render_options.cc b/modules/gfx/src/render_options/simple_render_options.cc
index e8dd554501efaf694b771e00134aa9523087b175..c15efb06d213a937ce33775630c94c7bb491f7ed 100644
--- a/modules/gfx/src/render_options/simple_render_options.cc
+++ b/modules/gfx/src/render_options/simple_render_options.cc
@@ -22,9 +22,7 @@
 
 #include "simple_render_options.hh"
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 SimpleRenderOptions::SimpleRenderOptions(): 
   blur_flag_(false), blur_factors_(1.0, 0.8),
@@ -40,8 +38,6 @@ bool SimpleRenderOptions::CanApplyRenderOptions(RenderOptionsPtr render_options)
   return render_options.get()->GetRenderMode()==RenderMode::SIMPLE;
 }
 
-SimpleRenderOptions::~SimpleRenderOptions() {}
-
 bool SimpleRenderOptions::GetBlurFlag() const
 {
   return blur_flag_;
@@ -86,6 +82,5 @@ void SimpleRenderOptions::SetBlurFactors(Real bf1, Real bf2)
   this->NotifyStateChange();
 }
 
-}
+}} // ns
 
-}
diff --git a/modules/gfx/src/render_options/simple_render_options.hh b/modules/gfx/src/render_options/simple_render_options.hh
index 68ba5fbbe6409f80ae78358e62d635891ad701dd..1eb284726826cceaf41a5e9fd90fbb3597a38fae 100644
--- a/modules/gfx/src/render_options/simple_render_options.hh
+++ b/modules/gfx/src/render_options/simple_render_options.hh
@@ -29,19 +29,17 @@
 
 #include "line_render_options.hh"
 
-namespace ost {
+namespace ost { namespace gfx {
 
-namespace gfx {
-
-class DLLEXPORT_OST_GFX SimpleRenderOptions: public ost::gfx::LineRenderOptions {
+class DLLEXPORT_OST_GFX SimpleRenderOptions: public LineRenderOptions {
 public:
   SimpleRenderOptions();
 
+  // remaining RenderOptions interface not define in LineRenderOptions
   virtual RenderMode::Type GetRenderMode();
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual ~SimpleRenderOptions();
-  
+  // own interface
   bool GetBlurFlag() const;
   bool GetBondOrderFlag() const;
   Real GetBondOrderDistance() const;
@@ -50,6 +48,7 @@ public:
   void SetBlurFactors(Real bf1, Real bf2);
   void SetBondOrderFlag(bool flag);
   void SetBondOrderDistance(Real bod);
+
 private:
   bool                     blur_flag_;
   std::pair<Real, Real>    blur_factors_;
diff --git a/modules/gfx/src/render_options/sline_render_options.cc b/modules/gfx/src/render_options/sline_render_options.cc
index 5bb1ce44713804180b8716401ac56c5549b27f5b..83fd53c1d5a20047c84f759296f662aa74085e6d 100644
--- a/modules/gfx/src/render_options/sline_render_options.cc
+++ b/modules/gfx/src/render_options/sline_render_options.cc
@@ -21,9 +21,7 @@
 */
 #include "sline_render_options.hh"
 
-namespace ost {
-
-namespace gfx {
+namespace ost { namespace gfx {
 
 SlineRenderOptions::SlineRenderOptions():
   spline_detail_(6)
@@ -55,8 +53,4 @@ uint SlineRenderOptions::GetSplineDetail(){
   return spline_detail_;
 }
 
-SlineRenderOptions::~SlineRenderOptions() {}
-
-}
-
-}
+}} // ns
diff --git a/modules/gfx/src/render_options/sline_render_options.hh b/modules/gfx/src/render_options/sline_render_options.hh
index 1285120e4838ec9a0b44eebec1c41918b9c914e8..386f7569aa967bd47164fe529fe8087a71655c15 100644
--- a/modules/gfx/src/render_options/sline_render_options.hh
+++ b/modules/gfx/src/render_options/sline_render_options.hh
@@ -26,28 +26,29 @@
 #include <boost/shared_ptr.hpp>
 
 #include <ost/gfx/module_config.hh>
-#include <ost/gfx/render_options/line_render_options.hh>
+
+#include "line_render_options.hh"
 
 namespace ost { namespace gfx {
 
-class DLLEXPORT_OST_GFX SlineRenderOptions: public ost::gfx::LineRenderOptions {
+class DLLEXPORT_OST_GFX SlineRenderOptions: public LineRenderOptions {
 public:
   SlineRenderOptions();
 
+  // RenderOptions interface
   virtual RenderMode::Type GetRenderMode();
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
-  virtual void SetSplineDetail(uint spline_detail);
-  virtual uint GetSplineDetail();
+  void SetSplineDetail(uint spline_detail);
+  uint GetSplineDetail();
 
-  virtual ~SlineRenderOptions();
 private:
   uint spline_detail_;
 };
 
 typedef boost::shared_ptr<SlineRenderOptions> SlineRenderOptionsPtr;
 
-}}
+}} // ns
 
-#endif /* OST_GFX_SIMPLE_RENDER_OPTIONS_HH */
+#endif
diff --git a/modules/gfx/src/render_options/trace_render_options.cc b/modules/gfx/src/render_options/trace_render_options.cc
index 337770895e15a7cd508a0fe3b0d44a3379e695d9..fb2afc3ccfb2e312d3dbbeac63367d76c0b28c49 100644
--- a/modules/gfx/src/render_options/trace_render_options.cc
+++ b/modules/gfx/src/render_options/trace_render_options.cc
@@ -29,7 +29,7 @@ TraceRenderOptions::TraceRenderOptions():
   arc_detail_(4),
   smooth_factor_(0.0),
   tube_radius_(0.4)
-{ }
+{}
 
 RenderMode::Type TraceRenderOptions::GetRenderMode()
 {
@@ -84,8 +84,4 @@ float TraceRenderOptions::GetTubeRadius() const{
   return tube_radius_;
 }
 
-TraceRenderOptions::~TraceRenderOptions() {}
-
-}
-
-}
+}}
diff --git a/modules/gfx/src/render_options/trace_render_options.hh b/modules/gfx/src/render_options/trace_render_options.hh
index c740ef7d921a29363ccf3413cd7292efa3b59fc5..e9943e4dd242f3e726d5ff4c763bbab8d0eccadd 100644
--- a/modules/gfx/src/render_options/trace_render_options.hh
+++ b/modules/gfx/src/render_options/trace_render_options.hh
@@ -27,31 +27,28 @@
 
 #include <ost/gfx/module_config.hh>
 
-#include <ost/gfx/render_options/render_options.hh>
+#include "render_options.hh"
 
 namespace ost { namespace gfx {
 
-class DLLEXPORT_OST_GFX TraceRenderOptions: public ost::gfx::RenderOptions {
+class DLLEXPORT_OST_GFX TraceRenderOptions: public RenderOptions {
 public:
   TraceRenderOptions();
 
+  // RenderOptions interface
   virtual RenderMode::Type GetRenderMode();
-
   virtual bool CanApplyRenderOptions(RenderOptionsPtr render_options);
   virtual void ApplyRenderOptions(RenderOptionsPtr render_options);
 
+  // own interface
   void SetArcDetail(uint arc_detail);
   uint GetArcDetail() const;
-
   void SetNormalSmoothFactor(float smooth_factor);
   float GetNormalSmoothFactor() const;
-
   void SetTubeRadius(float tube_radius);
   float GetTubeRadius() const;
   float GetMaxRad() const;
 
-  virtual ~TraceRenderOptions();
-
 private:
   uint spline_detail_;
   uint poly_mode_;
@@ -62,6 +59,6 @@ private:
 
 typedef boost::shared_ptr<TraceRenderOptions> TraceRenderOptionsPtr;
 
-}}
+}} // ns
 
-#endif /* OST_GFX_CARTOON_RENDER_OPTIONS_HH */
+#endif
diff --git a/modules/gfx/src/render_pass.hh b/modules/gfx/src/render_pass.hh
index 70173c6ca3c4ec2b4fbc2d82c0e139a582acf844..2105b9bb550ce939738b2652728efbe280cf6cd6 100644
--- a/modules/gfx/src/render_pass.hh
+++ b/modules/gfx/src/render_pass.hh
@@ -32,9 +32,14 @@ typedef enum {
   GLOW_RENDER_PASS,
   /// \brief renders objects with solid color as used for shadow map
   ///     generation
-  OPAQUE_RENDER_PASS
+  DEPTH_RENDER_PASS,
+  /// \ brief for transparent objects
+  /// the standard render pass is not supposed to render transparent
+  /// objects, as they should get drawn after the rest of the scene
+  TRANSPARENT_RENDER_PASS,
+  OVERLAY_RENDER_PASS
 } RenderPass;
  
 }}
 
-#endif
\ No newline at end of file
+#endif
diff --git a/modules/gfx/src/scene.cc b/modules/gfx/src/scene.cc
index 8f781aaf9efe43e9e6eec46da80c1efa47066d58..337077ee7a1248f9fb06633db808bb810879f6c6 100644
--- a/modules/gfx/src/scene.cc
+++ b/modules/gfx/src/scene.cc
@@ -42,7 +42,6 @@
 #include "gl_helper.hh"
 
 #include <ost/config.hh>
-#include "offscreen_buffer.hh"
 #include "scene.hh"
 #include "input.hh"
 #include "gfx_node.hh"
@@ -51,13 +50,13 @@
 #include "bitmap_io.hh"
 #include "entity.hh"
 #include "povray.hh"
+#include "offscreen_buffer.hh"
 
 #if OST_SHADER_SUPPORT_ENABLED
 # include "shader.hh"
+# include "impl/scene_fx.hh"
 #endif
 
-//#define DEBUG_SMAP
-
 using boost::bind;
 
 namespace ost {
@@ -95,10 +94,11 @@ Scene::Scene():
   root_node_(new GfxNode("Scene")),
   observers_(),
   transform_(),
+  gl_init_(false),
   fov_(30.0),
-  znear_(-200.0),zfar_(200.0),
-  fnear_(5.0), ffar_(0.0),
-  vp_width_(100),vp_height_(100),
+  znear_(1.0),zfar_(1000.0),
+  fnear_(0.0), ffar_(0.0),
+  vp_width_(1000),vp_height_(1000),
   scene_view_stack_(),
   aspect_ratio_(1.0),
   background_(Color(0.0,0.0,0.0,0.0)),
@@ -110,11 +110,13 @@ Scene::Scene():
   axis_flag_(false),
   fog_flag_(true),
   fog_color_(0.0,0.0,0.0,0.0),
-  shadow_flag_(false),
-  shadow_quality_(1),
-  texture_id_(),
   auto_autoslab_(true),
+  do_autoslab_(true),
+  do_autoslab_fast_(true),
   offscreen_flag_(false),
+  main_offscreen_buffer_(0),
+  old_vp_(),
+  def_shading_mode_("default"),
   selection_mode_(1),
   test_flag_(false),
   tmp_tex_(),
@@ -123,11 +125,14 @@ Scene::Scene():
   def_text_size_(32.0),
   blur_count_(0),
   blur_buffer_(),
-  stereo_(0),
+  stereo_mode_(0),
+  stereo_alg_(0),
   stereo_inverted_(false),
   stereo_eye_(0),
-  stereo_eye_dist_(150.0),
-  stereo_eye_offset_(10.0)
+  stereo_iod_(4.0),
+  stereo_distance_(0.0),
+  scene_left_tex_(),
+  scene_right_tex_()
 {
   transform_.SetTrans(Vec3(0,0,-100));
 }
@@ -143,6 +148,11 @@ void Scene::SetFog(bool f)
   RequestRedraw();
 }
 
+bool Scene::GetFog() const
+{
+  return fog_flag_;
+}
+
 void Scene::SetFogColor(const Color& c)
 {
   GLfloat fogc[]={c.Red(),c.Green(),c.Blue(),1.0};
@@ -151,21 +161,147 @@ void Scene::SetFogColor(const Color& c)
   RequestRedraw();
 }
 
+Color Scene::GetFogColor() const
+{
+  return fog_color_;
+}
+
 void Scene::SetShadow(bool f)
 {
-  shadow_flag_=f;
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().shadow_flag=f;
+  // the redraw routine will deal with the Shader
   RequestRedraw();
+#endif
 }
 
-bool Scene::GetShadow()
+bool Scene::GetShadow() const
 {
-  return shadow_flag_;
+#if OST_SHADER_SUPPORT_ENABLED
+  return impl::SceneFX::Instance().shadow_flag;
+#else
+  return false;
+#endif
 }
 
 void Scene::SetShadowQuality(int q)
 {
-  shadow_quality_=std::min(3,std::max(0,q));
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().shadow_quality=std::min(8,std::max(0,q));
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetShadowWeight(float w)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().shadow_weight=w;
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetDepthDarkening(bool f)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().depth_dark_flag=f;
+  // the redraw routine will deal with the Shader
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetDepthDarkeningWeight(float f)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().depth_dark_factor=f;
+  // the redraw routine will deal with the Shader
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetAmbientOcclusion(bool f)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().amb_occl_flag=f;
+  // the redraw routine will deal with the Shader
+  RequestRedraw();
+#endif
+} 
+
+bool Scene::GetAmbientOcclusion() const
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  return impl::SceneFX::Instance().amb_occl_flag;
+#else
+  return false;
+#endif
+} 
+
+void Scene::SetAmbientOcclusionWeight(float f)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().amb_occl_factor=f;
+  // the redraw routine will deal with the Shader
   RequestRedraw();
+#endif
+}
+
+void Scene::SetAmbientOcclusionMode(uint m)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().amb_occl_mode=m;
+  // the redraw routine will deal with the Shader
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetAmbientOcclusionQuality(uint m)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().amb_occl_quality=m;
+  // the redraw routine will deal with the Shader
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetShadingMode(const std::string& smode)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  // this here is required - in case SetShadingMode is called
+  // before GL is initialized (e.g. during batch mode rendering)
+  def_shading_mode_=smode;
+  if(smode=="fallback") {
+    Shader::Instance().Activate("");
+  } else if(smode=="basic") {
+    Shader::Instance().Activate("basic");
+  } else if(smode=="hf") {
+    Shader::Instance().Activate("hemilight");
+  } else if(smode=="toon1") {
+    Shader::Instance().Activate("toon1");
+  } else if(smode=="toon2") {
+    Shader::Instance().Activate("toon2");
+  } else if(smode=="test_tex") {
+    Shader::Instance().Activate("test_tex");
+  } else {
+    Shader::Instance().Activate("fraglight");
+  }
+  RequestRedraw();
+#endif
+}
+
+void Scene::SetBeacon(int wx, int wy)
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().use_beacon=true;
+  impl::SceneFX::Instance().beacon.wx=static_cast<float>(wx);
+  impl::SceneFX::Instance().beacon.wy=static_cast<float>(wy);
+#endif  
+}
+
+void Scene::SetBeaconOff()
+{
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().use_beacon=false;
+#endif  
 }
 
 namespace {
@@ -179,13 +315,18 @@ void set_light_dir(Vec3 ld)
 
 }
 
-void Scene::InitGL()
+void Scene::InitGL(bool full)
 {
-  LOG_DEBUG("scene: initializing GL state");
+  LOG_VERBOSE("Scene: initializing GL state");
+
+  if(full) {
+    LOG_INFO(glGetString(GL_RENDERER) << ", openGL version " << glGetString(GL_VERSION)); 
 
 #if OST_SHADER_SUPPORT_ENABLED
-  Shader::Instance().PreGLInit();
+    LOG_DEBUG("Scene: shader pre-gl");
+    Shader::Instance().PreGLInit();
 #endif
+  }
 
   // TODO: add more lights
   glLightfv(GL_LIGHT0, GL_AMBIENT, light_amb_);
@@ -212,11 +353,14 @@ void Scene::InitGL()
 
   // background
   SetBackground(background_);
+
   // polygon orientation setting
   glFrontFace(GL_CCW);
+
   // blending
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   glEnable(GL_BLEND);  
+
   // depth effect thru fog
   GLfloat fogc[]={fog_color_.Red(),fog_color_.Green(),fog_color_.Blue(),1.0};
   glFogfv(GL_FOG_COLOR,fogc);
@@ -233,10 +377,32 @@ void Scene::InitGL()
   // smooth shading across polygon faces
   glShadeModel(GL_SMOOTH);
 
+#if OST_SHADER_SUPPORT_ENABLED & defined(OST_GL_VERSION_2_0)
+  GLint mbufs=0,msamples=0;
+
+  if(OST_GL_VERSION_2_0) {
+    glGetIntegerv(GL_SAMPLE_BUFFERS, &mbufs);
+    glGetIntegerv(GL_SAMPLES, &msamples);
+  }
+
+  if(mbufs>0 && msamples>0) {
+    LOG_INFO("Scene: enabling multisampling with: " << msamples << " samples");
+    glDisable(GL_LINE_SMOOTH);
+    glDisable(GL_POINT_SMOOTH);
+    glDisable(GL_POLYGON_SMOOTH);
+    glEnable(GL_MULTISAMPLE);
+  } else {
+    glEnable(GL_LINE_SMOOTH);
+    glDisable(GL_POINT_SMOOTH);
+    glDisable(GL_POLYGON_SMOOTH);
+  }
+#else
   // line and point anti-aliasing
   glEnable(GL_LINE_SMOOTH);
   glDisable(GL_POINT_SMOOTH);
   glDisable(GL_POLYGON_SMOOTH);
+#endif
+
   // rendering hints
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
   glHint(GL_FOG_HINT, GL_NICEST);
@@ -247,20 +413,54 @@ void Scene::InitGL()
   glDisable(GL_NORMALIZE);
   // double-buffer rendering requires this
   // glDrawBuffer(GL_BACK);
-  // initialize shaders
+
 #if OST_SHADER_SUPPORT_ENABLED
-  Shader::Instance().Setup();
-  Shader::Instance().Activate("fraglight");
+  if(full) {
+    LOG_DEBUG("Scene: shader setup");
+    Shader::Instance().Setup();
+    SetShadingMode(def_shading_mode_);
+    LOG_DEBUG("Scene: scenefx setup");
+    impl::SceneFX::Instance().Setup();
+  }
+#endif
 
-  glGenTextures(1,&texture_id_);
+  if(full) {
+    prep_glyphs();
+  }
+
+  if(full) {
+    glGenTextures(1,&scene_left_tex_);
+    glGenTextures(1,&scene_right_tex_);
+  }
+
+  glEnable(GL_TEXTURE_2D);
+#if OST_SHADER_SUPPORT_ENABLED
+  if(OST_GL_VERSION_2_0) {
+    glActiveTexture(GL_TEXTURE0);
+  }
 #endif
 
-  prep_glyphs();
+  glBindTexture(GL_TEXTURE_2D, scene_left_tex_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  glBindTexture(GL_TEXTURE_2D, scene_right_tex_);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+  glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
+
+  LOG_DEBUG("Scene: gl init done");
+  gl_init_=true;
 }
 
 void Scene::RequestRedraw()
 {
-  if (win_) {
+  if (win_ && !offscreen_flag_) {
     win_->DoRefresh();
   }
 }
@@ -278,6 +478,11 @@ void Scene::SetBackground(const Color& c)
   RequestRedraw();
 }
 
+Color Scene::GetBackground() const
+{
+  return background_;
+}
+
 Viewport Scene::GetViewport() const
 {
   Viewport vp;
@@ -292,6 +497,9 @@ void Scene::SetViewport(int w, int h)
   vp_height_=h;
   aspect_ratio_=static_cast<float>(w)/static_cast<float>(h);
   ResetProjection();
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().Resize(w,h);
+#endif
 }
 
 void Scene::Resize(int w, int h)
@@ -306,6 +514,7 @@ void Scene::SetCenter(const Vec3& cen)
   float delta_z = tcen[2]-transform_.GetTrans()[2];
 
   transform_.SetCenter(cen);
+  transform_.SetTrans(Vec3(0,0,transform_.GetTrans()[2]));
   SetNearFar(znear_+delta_z,zfar_+delta_z);
   RequestRedraw();  
 }
@@ -426,49 +635,30 @@ void draw_lightdir(const Vec3& ldir, const mol::Transform& tf)
 
 void Scene::RenderGL()
 {
-  if(auto_autoslab_) Autoslab(false, false);
+  if(auto_autoslab_ || do_autoslab_) {
+    do_autoslab();
+    do_autoslab_=false;
+  }
 
-  #if OST_SHADER_SUPPORT_ENABLED
-    if(shadow_flag_) {
-      prep_shadow_map();
-  #if DEBUG_SMAP
-      return;
-  #endif
-    }
-  #endif
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   prep_blur();
 
-  glMatrixMode(GL_MODELVIEW);
-  glLoadIdentity();
-
-  set_light_dir(light_dir_);
-
-  glMultMatrix(transform_.GetTransposedMatrix().Data());
-
-  if(stereo_==2 || stereo_==3) {
-    render_interlaced_stereo();
-  } else if (stereo_==1) {
-    this->render_quad_buffered_stereo();
+  if(stereo_mode_==1 || stereo_mode_==2) {
+    render_stereo();
   } else {
-    this->render_scene_with_glow();
-  }
-  #if OST_SHADER_SUPPORT_ENABLED
-  if(shadow_flag_) {
-    glDisable(GL_TEXTURE_2D);
+    render_scene();
   }
-  #endif
+  check_gl_error();
 }
 
 void Scene::Register(GLWinBase* win)
 {
-  LOG_DEBUG("scene: registered win @" << win);
+  LOG_DEBUG("Scene: registered win @" << win);
   win_=win;
 }
 
 void Scene::Unregister(GLWinBase* win)
 {
-  LOG_DEBUG("scene: unregistered win @" << win);
+  LOG_DEBUG("Scene: unregistered win @" << win);
   win_=0;
 }
 
@@ -501,6 +691,37 @@ namespace {
     GfxObjP node;
   };
 
+#if 0
+  struct RegexFindObj: public GfxNodeVisitor {
+    RegexFindObj(const String& rs): reg(), valid(false), node() {
+      try {
+        reg = boost::regex(rs);
+        valid = true;
+      } catch (boost::regex_error& e) {
+        LOG_ERROR("invalid regex");
+      }
+    }
+
+    virtual bool VisitNode(GfxNode* n, const Stack& st) {
+      return true;
+    }
+
+    virtual void VisitObject(GfxObj* o, const Stack& st) {
+      if(boost::regex_match(o->GetName(),reg)) {
+        GfxNodeP nn = o->shared_from_this();
+        GfxObjP oo = dyn_cast<GfxObj>(nn);
+        if(oo) {
+          olist.push_back(oo);
+        }
+      }
+    }
+
+    boost::regex reg;
+    bool valid;
+    std::vector<GfxObjP> olist;
+  };
+#endif
+
   struct FindNode2: public GfxNodeVisitor {
     FindNode2(GfxNodeP n): node(n), found(false) {}
     virtual bool VisitNode(GfxNode* n, const Stack& st) {
@@ -535,26 +756,31 @@ size_t Scene::GetNodeCount() const
 void Scene::Add(const GfxNodeP& n, bool redraw)
 {
   if(!n) return;
+  // even though IsNameAvailable() is called in GfxNode::Add, check here 
+  // as well to produce error message specific to adding a node to the scene.
   if(!this->IsNameAvailable(n->GetName())){
     throw Error("Scene already has a node with name '"+n->GetName()+"'");
   }
 
-  LOG_DEBUG("scene: graphical object added @" << n.get());
+  LOG_DEBUG("Scene: graphical object added @" << n.get() << std::endl);
+
+  if(root_node_->GetChildCount()==0) {
+    GfxObjP go = boost::dynamic_pointer_cast<GfxObj>(n);
+    if(go) {
+      SetCenter(go->GetCenter());
+    }
+    do_autoslab_=true;
+  }
+
   root_node_->Add(n);
   if (redraw) {
     this->RequestRedraw();
   }
 }
 
-bool Scene::IsNameAvailable(String name)
+bool Scene::IsNameAvailable(const String& name) const
 {
-  FindNode fn(name);
-  Apply(fn);
-  if(fn.node) {
-    LOG_INFO(name << " already exists as a scene node");
-    return false;
-  }
-  return true;
+  return root_node_->IsNameAvailable(name);
 }
 
 void Scene::NodeAdded(const GfxNodeP& node)
@@ -599,7 +825,6 @@ void Scene::Remove(const GfxNodeP& go)
   if(!go) return;
   root_node_->Remove(go);
   this->NotifyObservers(bind(&SceneObserver::NodeRemoved, _1,go));
-  this->RequestRedraw();
 }
 
 void Scene::RemoveAll()
@@ -616,7 +841,6 @@ void Scene::Remove(const String& name)
     root_node_->Remove(name);
     if(GfxObjP go = dyn_cast<GfxObj>(fn.node)) {
       this->NotifyObservers(bind(&SceneObserver::NodeRemoved, _1,go));
-      this->RequestRedraw();
     }
   }
 }
@@ -641,12 +865,12 @@ GfxObjP Scene::operator[](const String& name)
   FindNode fn(name);
   Apply(fn);
   if(!fn.node) {
-    LOG_ERROR("error: " << name << " not found");
+    LOG_ERROR("Scene: error: " << name << " not found");
     return GfxObjP();
   }
   GfxObjP nrvo = dyn_cast<GfxObj>(fn.node);
   if(!nrvo) {
-    LOG_ERROR("error: " << name << " points to invalid entry");
+    LOG_ERROR("Scene: error: " << name << " points to invalid entry");
   }
   return nrvo;
 }
@@ -692,7 +916,6 @@ void Scene::Apply(GfxNodeVisitor& v) const
 
 void Scene::OnInput(const InputEvent& e)
 {
-  float sf=1.0;
   if(e.GetCommand()==INPUT_COMMAND_AUTOSLAB) {
     Autoslab();
   } else if(e.GetCommand()==INPUT_COMMAND_TOGGLE_FOG) {
@@ -728,7 +951,8 @@ void Scene::OnInput(const InputEvent& e)
       transform_.ApplyYAxisTranslation(e.GetDelta()*fxy[1]);
     }
   } else if(e.GetCommand()==INPUT_COMMAND_TRANSZ) {
-    float delta=e.GetDelta()*sf;
+    float currz=transform_.GetTrans()[2];
+    float delta=currz*pow(1.01f,-e.GetDelta())-currz;
     transform_.ApplyZAxisTranslation(delta);
     SetNearFar(znear_-delta,zfar_-delta);
   } else if(e.GetCommand()==INPUT_COMMAND_SLABN) {
@@ -764,7 +988,7 @@ void Scene::Pick(int mx, int my, int mask)
   Vec3 v1=UnProject(Vec3(mx,my,0.0));
   Vec3 v2=UnProject(Vec3(mx,my,1.0));
 
-  LOG_DEBUG("Scene pick: " << v1 << " " << v2 << " " << mask);
+  LOG_DEBUG("Scene: pick: " << v1 << " " << v2 << " " << mask);
 
   Scene::Instance().StatusMessage("");
 
@@ -1058,33 +1282,62 @@ void Scene::SetFogOffsets(float no, float fo)
   RequestRedraw();
 }
 
-void Scene::Stereo(unsigned int m)
+void Scene::SetStereoMode(unsigned int m)
 {
   if(m==1) {
-    stereo_=m;
-    if(win_) win_->SetStereo(true);
-  } else if(m==2 || m==3) {
-    stereo_=m;
-    if(win_) win_->SetStereo(false);
+    if(win_ && win_->HasStereo()) {
+      stereo_mode_=1;
+    } else {
+      LOG_INFO("Scene: No visual present for quad-buffered stereo");
+      stereo_mode_=0;
+    }
+  } else if(m==2) {
+    stereo_mode_=2;
   } else {
-    stereo_=0;
-    if(win_) win_->SetStereo(false);
+    stereo_mode_=0;
   }
   RequestRedraw();
 }
 
-void Scene::SetStereoInverted(bool f)
+void Scene::SetStereoFlip(bool f)
 {
   stereo_inverted_=f;
+  RequestRedraw();
 }
 
-void Scene::SetStereoEye(unsigned int m)
+void Scene::SetStereoView(int m)
 {
-  stereo_eye_= (m>2) ? 0: m;
+  stereo_eye_= m;
   ResetProjection();
   RequestRedraw();
 }
 
+void Scene::SetStereoIOD(Real d)
+{
+  stereo_iod_=d;
+  if(stereo_mode_>0) {
+    RequestRedraw();
+  }
+}
+
+void Scene::SetStereoDistance(Real d)
+{
+  stereo_distance_=d;
+  if(stereo_mode_>0) {
+    RequestRedraw();
+  }
+}
+
+void Scene::SetStereoAlg(unsigned int a)
+{
+  stereo_alg_=a;
+  if(stereo_alg_>1) {
+    stereo_alg_=0;
+  }
+  if(stereo_mode_>0) {
+    RequestRedraw();
+  }
+}
 
 void Scene::SetLightDir(const Vec3& dir)
 {
@@ -1134,107 +1387,139 @@ uint Scene::GetSelectionMode() const
   return selection_mode_;
 }
 
-namespace {
-
-struct OffscreenSwitcher
+bool Scene::StartOffscreenMode(unsigned int width, unsigned int height)
 {
-  OffscreenSwitcher()
-  {
-    LOG_TRACE("offscreen begin");
-    OffscreenBuffer::Instance().Begin();
+  LOG_DEBUG("Scene: starting offscreen rendering mode " << width << "x" << height);
+  if(main_offscreen_buffer_) return false;
+  main_offscreen_buffer_ = new OffscreenBuffer(width,height,OffscreenBufferFormat(),true);
+
+  if(!main_offscreen_buffer_->IsValid()) {
+    LOG_ERROR("Scene: error during offscreen buffer creation");
+    delete main_offscreen_buffer_;   
+    main_offscreen_buffer_=0;
+    return false;
   }
+  old_vp_[0]=vp_width_;
+  old_vp_[1]=vp_height_;
+  main_offscreen_buffer_->MakeActive();
+  offscreen_flag_=true;
+  root_node_->ContextSwitch();
 
-  ~OffscreenSwitcher()
-  {
-    LOG_TRACE("offscreen end");
-    OffscreenBuffer::Instance().End();
+#if OST_SHADER_SUPPORT_ENABLED
+  String shader_name = Shader::Instance().GetCurrentName();
+#endif
+
+  LOG_DEBUG("Scene: initializing GL");
+  if(gl_init_) {
+    this->InitGL(false);
+  } else {
+    this->InitGL(true);
   }
-};
+  LOG_DEBUG("Scene: setting viewport");
+  Resize(width,height);
+  LOG_DEBUG("Scene: updating fog settings");
+  update_fog();
+  glDrawBuffer(GL_FRONT);
+#if OST_SHADER_SUPPORT_ENABLED
+  LOG_DEBUG("Scene: activating shader");
+  Shader::Instance().Activate(shader_name);
+#endif
+  return true;
+}
 
-} // anon ns
+void Scene::StopOffscreenMode()
+{
+  if(main_offscreen_buffer_) {
+    if (win_) {
+      win_->MakeActive();
+    }
+    delete main_offscreen_buffer_;
+    main_offscreen_buffer_=0;
+    Scene::Instance().SetViewport(old_vp_[0],old_vp_[1]);
+    offscreen_flag_=false;
+    root_node_->ContextSwitch();
+    glDrawBuffer(GL_BACK);
+    update_fog();
+  }
+}
 
 void Scene::Export(const String& fname, unsigned int width,
                    unsigned int height, bool transparent)
 {
   int d_index=fname.rfind('.');
   if (d_index==-1) {
-    LOG_ERROR("no file extension specified");
+    LOG_ERROR("Scene: no file extension specified");
     return;
   }
   String ext = fname.substr(d_index);
   if(!(ext==".png")) {
-    LOG_ERROR("unknown file format (" << ext << ")");
+    LOG_ERROR("Scene: unknown file format (" << ext << ")");
     return;
   }
 
-  offscreen_flag_=true;
-  LOG_TRACE("offscreen resize");
-  OffscreenBuffer::Instance().Resize(width, height);
-  try {
-    // ensures that context is switched back when this goes out of scope
-    OffscreenSwitcher offscreen_switch;
+  bool of_flag = (main_offscreen_buffer_==0);
 
-#if OST_SHADER_SUPPORT_ENABLED
-    String shader_name = Shader::Instance().GetCurrentName();
-#endif
-    LOG_TRACE("initializing GL");
-    this->InitGL();
-    LOG_TRACE("setting viewport");
-    SetViewport(width,height);
-    LOG_TRACE("reseting projection");
-    ResetProjection();
-    LOG_TRACE("updating fog settings");
-    update_fog();
-    glDrawBuffer(GL_FRONT);
-    //this->flag_all_dirty();
-#if OST_SHADER_SUPPORT_ENABLED
-    LOG_TRACE("activating shader");
-    Shader::Instance().Activate(shader_name);
-#endif
-    LOG_TRACE("doing rendering");
-    this->RenderGL();
-    // make sure drawing operations are finished
-    glFinish();
-    boost::shared_array<uchar> img_data(new uchar[width*height*4]);
-
-    LOG_TRACE("setting background transparency");
-    if (transparent) {
-      glPixelTransferf(GL_ALPHA_BIAS, 0.0);
-    } else {
-      // shift alpha channel by one to make sure pixels are read out as opaque
-      glPixelTransferf(GL_ALPHA_BIAS, 1.0);
+  // only switch if offscreen mode is not active
+  if(of_flag) {
+    if(!StartOffscreenMode(width,height)) {
+      return;
     }
+  }
+  LOG_DEBUG("Scene: rendering into offscreen buffer");
+  this->RenderGL();
+  // make sure drawing operations are finished
+  glFlush();
+  glFinish();
 
-    LOG_TRACE("reading framebuffer pixels");
-    glReadBuffer(GL_FRONT);
-    glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,img_data.get());
-
-    LOG_DEBUG("calling bitmap export");
-    BitmapExport(fname,ext,width,height,img_data.get());
-  } catch (...) {
-    // noop
-  } // offscreen_switch goes out of scope
-  offscreen_flag_=false;
-  glDrawBuffer(GL_BACK);
-  LOG_TRACE("updating fog");
-  update_fog();
+  boost::shared_array<uchar> img_data(new uchar[width*height*4]);
+      
+  LOG_DEBUG("Scene: setting background transparency");
+  if (transparent) {
+    glPixelTransferf(GL_ALPHA_BIAS, 0.0);
+  } else {
+    // shift alpha channel by one to make sure pixels are read out as opaque
+    glPixelTransferf(GL_ALPHA_BIAS, 1.0);
+  }
+  
+  LOG_DEBUG("Scene: reading framebuffer pixels");
+  glReadBuffer(GL_FRONT);
+  glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,img_data.get());
+  glReadBuffer(GL_BACK);
+
+  LOG_DEBUG("Scene: calling bitmap export");
+  BitmapExport(fname,ext,width,height,img_data.get());
+
+  // only switch back if it was not on to begin with
+  if(of_flag) {
+    StopOffscreenMode();
+  }
 }
 
 void Scene::Export(const String& fname, bool transparent)
 {
+  if(!win_ && !main_offscreen_buffer_) {
+    LOG_ERROR("Scene: Export without dimensions either requires an interactive session \nor an active offscreen mode (scene.StartOffscreenMode(W,H))");
+    return;
+  }
   int d_index=fname.rfind('.');
   if (d_index==-1) {
-    LOG_ERROR("no file extension specified");
+    LOG_ERROR("Scene: no file extension specified");
     return;
   }
   String ext = fname.substr(d_index);
   if(ext!=".png") {
-    LOG_ERROR("unknown file format (" << ext << ")");
+    LOG_ERROR("Scene: unknown file format (" << ext << ")");
     return;
   }
   GLint vp[4];
   glGetIntegerv(GL_VIEWPORT,vp);
 
+  if(main_offscreen_buffer_) {
+    this->RenderGL();
+    glFlush();
+    glFinish();
+  }
+
   if (transparent) {
     glPixelTransferf(GL_ALPHA_BIAS, 0.0);
   } else {
@@ -1269,7 +1554,7 @@ void Scene::ExportPov(const std::string& fname, const std::string& wdir)
 
 void Scene::ResetProjection()
 {
-  LOG_TRACE("scene: projection matrix " << fov_ << " " << znear_ << " " << zfar_);
+  LOG_TRACE("Scene: projection matrix " << fov_ << " " << znear_ << " " << zfar_);
   stereo_projection(stereo_eye_);
 }
 
@@ -1312,37 +1597,10 @@ public:
 
 } // anon ns
 
-void Scene::Autoslab(bool fast, bool update)
+void Scene::Autoslab(bool fast, bool)
 {
-  if(fast) {
-    geom::AlignedCuboid bb =this->GetBoundingBox(transform_);
-    // necessary code duplication due to awkward slab limit impl
-    znear_=-(bb.GetMax()[2]-1.0);
-    zfar_=-(bb.GetMin()[2]+1.0);
-    set_near(-(bb.GetMax()[2]-1.0));
-    set_far(-(bb.GetMin()[2]+1.0));
-    ResetProjection();
-  } else {
-    LimCalc limcalc;
-    limcalc.transform=transform_;
-    limcalc.minc = Vec3(std::numeric_limits<float>::max(),
-                              std::numeric_limits<float>::max(),
-                              std::numeric_limits<float>::max());
-    limcalc.maxc = Vec3(-std::numeric_limits<float>::max(),
-                              -std::numeric_limits<float>::max(),
-                              -std::numeric_limits<float>::max());
-    this->Apply(limcalc);
-    float mynear=std::max(float(0.0), std::min(float(-limcalc.minc[2]),float(-limcalc.maxc[2])))-float(2.0);
-    float myfar=std::max(float(-limcalc.minc[2]),float(-limcalc.maxc[2]))+float(2.0);
-    znear_=mynear;
-    zfar_=myfar;
-    set_near(znear_);
-    set_far(zfar_);
-    ResetProjection();
-  }
-  if (update) {
-    this->RequestRedraw();
-  }
+  do_autoslab_=true;
+  do_autoslab_fast_=fast;
 }
 
 void Scene::AutoslabMax()
@@ -1394,146 +1652,6 @@ void Scene::update_fog()
   glFogf(GL_FOG_END,zfar_+ffar_);
 }
 
-void Scene::prep_shadow_map()
-{
-#if OST_SHADER_SUPPORT_ENABLED
-  GLint smap_size=256 << shadow_quality_;
-
-  // modelview transform for the lightsource pov
-  mol::Transform ltrans(transform_);
-  ltrans.SetRot(light_rot_*transform_.GetRot());
-
-  // calculate encompassing box for ortho projection
-  geom::AlignedCuboid bb=this->GetBoundingBox(ltrans);
-  const Vec3& tmin=bb.GetMin();
-  const Vec3& tmax=bb.GetMax();
-
-  // render pass 1 - without shadows
-
-  // turn shadowing off for subsequent rendering
-  glUniform1i(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),
-              "shadow_flag"),0);
-  // save overall gl settings
-  glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT);
-  // maximize rendering for depth-only information
-#ifndef DEBUG_SMAP
-  glDisable(GL_LIGHTING);
-  glDisable(GL_FOG);
-  glDisable(GL_COLOR_MATERIAL);
-  glDisable(GL_NORMALIZE);
-  glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
-#endif
-
-  // render scene with only depth components
-  glViewport(0,0,smap_size,smap_size);
-  glClear(GL_DEPTH_BUFFER_BIT);
-
-  glMatrixMode(GL_PROJECTION);
-  glPushMatrix();
-  glLoadIdentity();
-  glOrtho(tmin[0],tmax[0],tmin[1],tmax[1],-tmax[2],-tmin[2]);
-  //glFrustum(tmin[0],tmax[0],tmin[1],tmax[1],-tmax[2],-tmin[2]);
-  float glpmat[16];
-  glGetv(GL_PROJECTION_MATRIX, glpmat);
-  Mat4 pmat(Transpose(Mat4(glpmat)));
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
-  glMultMatrix(ltrans.GetTransposedMatrix().Data());
-
-  // only render non-transparent objects for the shadow map
-  root_node_->RenderGL(OPAQUE_RENDER_PASS);
-
-  // now get the shadow map
-  glActiveTexture(GL_TEXTURE0);
-  glBindTexture(GL_TEXTURE_2D, texture_id_);
-
-  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
-                   0,0, smap_size,smap_size, 0);
-
-  ////////////////
-  // all of the following texture and shader params need to be moved
-  // to a one-time initialization place
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-  //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-  //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-
-  GLuint cpr=Shader::Instance().GetCurrentProgram();
-
-  // assign tex unit 0 to shadow map
-  glUniform1i(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"shadow_map"),0);
-  //int depth_bits;
-  //glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
-  //float depth_bias = 1.0/static_cast<float>(1<<depth_bits);
-  glUniform1f(glGetUniformLocation(cpr,"depth_bias"),0.008);
-
-  glUniform1f(glGetUniformLocation(cpr,"epsilon"),0.002);
-
-  glUniform1f(glGetUniformLocation(cpr,"shadow_multiplier"),0.4);
-
-  //
-  //////////////////
-
-  // restore settings
-  glPopMatrix();
-  glMatrixMode(GL_PROJECTION);
-  glPopMatrix();
-  glMatrixMode(GL_MODELVIEW);
-
-  glPopAttrib();
-  glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
-
-  glEnable(GL_TEXTURE_2D);
-
-  // and turn shadowing on for subsequent rendering
-  glUniform1i(glGetUniformLocation(cpr,"shadow_flag"),1);
-
-#ifndef DEBUG_SMAP
-  // set up appropriate texture matrix
-  Mat4 bias(0.5,0.0,0.0,0.5,
-                  0.0,0.5,0.0,0.5,
-                  0.0,0.0,0.5,0.5,
-                  0.0,0.0,0.0,1.0);
-
-  Mat4 texm = bias*pmat*ltrans.GetMatrix();
-
-  glMatrixMode(GL_TEXTURE);
-  // make explicit object instead of temporary to avoid potential crash with Data()
-  Mat4 ttmp=Transpose(texm);
-  glLoadMatrix(ttmp.Data());
-  glMatrixMode(GL_MODELVIEW);
-#else
-  // this debug code draws the depth map across the screen
-  Shader::Instance().Activate("");
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  glDisable(GL_CULL_FACE);
-  glDisable(GL_LIGHTING);
-  glDisable(GL_FOG);
-  glEnable(GL_TEXTURE_2D);
-  glMatrixMode(GL_PROJECTION);
-  glLoadIdentity();
-  glOrtho(-1,11,-1,11,-1,1);
-  glMatrixMode(GL_MODELVIEW);
-  glLoadIdentity();
-  glColor3f(1.0,1.0,1.0);
-  glBegin(GL_QUADS);
-  glTexCoord2f(0.0,0.0);
-  glVertex2f(0.0,0.0);
-  glTexCoord2f(0.0,1.0);
-  glVertex2f(0.0,10.0);
-  glTexCoord2f(1.0,1.0);
-  glVertex2f(10.0,10.0);
-  glTexCoord2f(1.0,0.0);
-  glVertex2f(10.0,0.0);
-  glEnd();
-  Shader::Instance().Activate("basic_shadow");
-#endif
-#endif
-}
 
 namespace {
 class DirtyAll: public GfxNodeVisitor
@@ -1560,11 +1678,6 @@ bool Scene::InOffscreenMode() const
   return offscreen_flag_;
 }
 
-void Scene::SetOffscreenMode()
-{
-  OffscreenBuffer::Instance().Begin();
-}
-
 float Scene::ElapsedTime() const
 {
 #ifndef _MSC_VER
@@ -1587,14 +1700,6 @@ void Scene::SetTestMode(bool f)
   }
 }
 
-// temporary interface
-void Scene::ActivateShader(const String& name)
-{
-#if OST_SHADER_SUPPORT_ENABLED
-  Shader::Instance().Activate(name);
-#endif
-}
-
 void Scene::prep_glyphs()
 {
   glGenTextures(1,&glyph_tex_id_);
@@ -1604,7 +1709,7 @@ void Scene::prep_glyphs()
   Bitmap bm = BitmapImport(tex_file.string(),".png");
   if(!bm.data) return;
 
-  LOG_DEBUG("importing glyph tex with id " << glyph_tex_id_);
+  LOG_DEBUG("Scene: importing glyph tex with id " << glyph_tex_id_);
   glBindTexture(GL_TEXTURE_2D, glyph_tex_id_);
   glPixelStorei(GL_UNPACK_ALIGNMENT,1);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
@@ -1618,7 +1723,7 @@ void Scene::prep_glyphs()
   } else if(bm.channels==4) {
     glTexImage2D(GL_TEXTURE_2D,0,GL_INTENSITY,bm.width,bm.height,0,GL_RGBA,GL_UNSIGNED_BYTE,bm.data.get());
   } else {
-    LOG_ERROR("unsupported glyph texture channel count of " << bm.channels);
+    LOG_ERROR("Scene: unsupported glyph texture channel count of " << bm.channels);
     return;
   }
   float ir = 1.0/8.0;
@@ -1632,8 +1737,7 @@ void Scene::prep_glyphs()
   }
   for(int cc=128;cc<256;++cc) glyph_map_[cc]=Vec2(0.0,0.0);
 
-  LOG_VERBOSE("done loading glyphs");
-
+  LOG_DEBUG("Scene: done loading glyphs");
 }
 
 void Scene::prep_blur()
@@ -1643,13 +1747,36 @@ void Scene::prep_blur()
   glFlush();
 }
 
-void Scene::render_scene_with_glow()
+void Scene::render_scene()
 {
-  glDepthFunc(GL_LEQUAL);    
-  glDepthMask(1);
-  glEnable(GL_DEPTH_TEST);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+
+  glMultMatrix(transform_.GetTransposedMatrix().Data());
+
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().Preprocess();
+#endif
+
   root_node_->RenderGL(STANDARD_RENDER_PASS);
-  glPushAttrib(GL_ENABLE_BIT);
+  glEnable(GL_BLEND);
+  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+  root_node_->RenderGL(TRANSPARENT_RENDER_PASS);
+  glDisable(GL_BLEND);
+  root_node_->RenderGL(OVERLAY_RENDER_PASS);
+
+#if OST_SHADER_SUPPORT_ENABLED
+  impl::SceneFX::Instance().Postprocess();
+#endif
+
+  render_glow();
+}
+
+void Scene::render_glow()
+{
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
   glEnable(GL_COLOR_MATERIAL);
   glShadeModel(GL_FLAT);
   glDisable(GL_FOG);
@@ -1672,38 +1799,92 @@ void Scene::render_scene_with_glow()
 #endif  
 }
 
-void Scene::stereo_projection(unsigned int view)
+void Scene::stereo_projection(int view)
 {
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
-  
-  float zn=std::max(float(1.0),znear_);
-  float zf=std::max(float(1.1),zfar_);
 
-  gluPerspective(fov_,aspect_ratio_,zn,zf);
+  Real zn=std::max<Real>(1.0,znear_);
+  Real zf=std::max<Real>(1.2,zfar_);
+  Real top = zn * std::tan(fov_*M_PI/360.0);
+  Real bot = -top;
+  Real left = -top*aspect_ratio_;
+  Real right = -left;
+
+  if(view!=0) {
+    
+    Real ff=(view<0 ? -1.0 : 1.0);
+    Real iod=std::max<Real>(0.1,stereo_iod_);
+
+    if(stereo_alg_==1) {
+      // Toe-in method, easy but wrong
+      glFrustum(left,right,bot,top,zn,zf);
+      Real dist = -transform_.GetTrans()[2]+stereo_distance_;
+      glTranslated(0.0,0.0,-dist);
+      glRotated(180.0/M_PI*atan(0.1*ff/iod),0.0,1.0,0.0);
+      glTranslated(0.0,0.0,dist);
+    } else {
+      // correct off-axis frustims
+
+      Real fo=-transform_.GetTrans()[2]+stereo_distance_;
+
+      // correction of near clipping plane to avoid extreme drifting
+      // of left and right view
+      if(iod*zn/fo<2.0) {
+        zn=2.0*fo/iod;
+        zf=std::max(zn+Real(0.2),zf);
+      }
+    
+      Real sd = -ff*0.5*iod*zn/fo;
+      left+=sd;
+      right+=sd;
+
+      glFrustum(left,right,bot,top,zn,zf);
+      glTranslated(-ff*iod*0.5,0.0,0.0);
+    }
 
-  if(view>0) {
-    float iod = (view==1) ? -stereo_eye_dist_ : stereo_eye_dist_;
-    //float fr=(-stereo_eye_offset_-zn)/(zf-zn);
-    float angle=180.0f/M_PI*std::atan(stereo_eye_offset_/(2.0*iod));
-    glTranslated(0.0,0.0,transform_.GetTrans()[2]);
-    glRotated(-angle,0.0,1.0,0.0);
-    glTranslated(0.0,0.0,-transform_.GetTrans()[2]);
+  } else { // view==0
+    // standard viewing frustum
+    glFrustum(left,right,bot,top,zn,zf);
   }
 }
 
-void Scene::render_interlaced_stereo()
+void Scene::render_stereo()
 {
-  // set up stencil buffer
-  glPushAttrib(GL_STENCIL_BUFFER_BIT| GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT);
-  glMatrixMode(GL_PROJECTION);
-  glPushMatrix();
-  glLoadIdentity();
-  glOrtho(0,vp_width_,0,vp_height_,-1,1);
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
-  glDrawBuffer(GL_NONE);
+  int old_stereo_eye=stereo_eye_;
+  stereo_eye_=-1;
+  stereo_projection(-1);
+  render_scene();
+
+  glEnable(GL_TEXTURE_2D);
+#if OST_SHADER_SUPPORT_ENABLED
+  if(OST_GL_VERSION_2_0) {
+    glActiveTexture(GL_TEXTURE0);
+  }
+#endif
+  glBindTexture(GL_TEXTURE_2D, scene_left_tex_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, vp_width_, vp_height_, 0);
+
+  stereo_eye_=1;
+  stereo_projection(1);
+  render_scene();
+  glEnable(GL_TEXTURE_2D);
+#if OST_SHADER_SUPPORT_ENABLED
+  if(OST_GL_VERSION_2_0) {
+    glActiveTexture(GL_TEXTURE0);
+  }
+#endif
+  glBindTexture(GL_TEXTURE_2D, scene_right_tex_);
+  glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, vp_width_, vp_height_, 0);
+  stereo_eye_=old_stereo_eye;
+  stereo_projection(0);
+
+#if OST_SHADER_SUPPORT_ENABLED
+  Shader::Instance().PushProgram();
+  Shader::Instance().Activate("");
+#endif
+
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_LIGHTING);
   glDisable(GL_COLOR_MATERIAL);
@@ -1712,63 +1893,121 @@ void Scene::render_interlaced_stereo()
   glDisable(GL_BLEND);
   glDisable(GL_LINE_SMOOTH);
   glDisable(GL_POINT_SMOOTH);
-  glLineWidth(1.0);
-  glEnable(GL_STENCIL_TEST);
-  glStencilMask(0x1);
-  glClearStencil(0x0);
-  glClear(GL_STENCIL_BUFFER_BIT);
-  glStencilFunc(GL_ALWAYS,0x1,0x1);
-  glStencilOp(GL_REPLACE,GL_REPLACE,GL_REPLACE);
-  glBegin(GL_LINES);
-  glColor3f(1.0,1.0,1.0);
-  for(unsigned int i=0;i<vp_height_;i+=2) {
-    glVertex2i(0,i);
-    glVertex2i(vp_width_-1,i);
-  } 
-  glEnd();
-  glPopMatrix();
+#if defined(OST_GL_VERSION_2_0)
+  glDisable(GL_MULTISAMPLE);
+#endif
   glMatrixMode(GL_PROJECTION);
-  glPopMatrix();
+  glPushMatrix();
+  glLoadIdentity();
+  glOrtho(0,vp_width_,0,vp_height_,-1,1);
   glMatrixMode(GL_MODELVIEW);
-  glPopAttrib();
+  glPushMatrix();
+  glLoadIdentity();
 
-  glEnable(GL_STENCIL_TEST);
-  glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
+  if(stereo_mode_==2) {
+    // draw interlace lines in stencil buffer
+    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+    glLineWidth(1.0);
+    glEnable(GL_STENCIL_TEST);
+    glStencilMask(0x1);
+    glClearStencil(0x0);
+    glClear(GL_STENCIL_BUFFER_BIT);
+    glStencilFunc(GL_ALWAYS,0x1,0x1);
+    glStencilOp(GL_REPLACE,GL_REPLACE,GL_REPLACE);
+    glBegin(GL_LINES);
+    glColor3f(1.0,1.0,1.0);
+    for(unsigned int i=0;i<vp_height_;i+=2) {
+      glVertex2i(0,i);
+      glVertex2i(vp_width_-1,i);
+    } 
+    glEnd();
+    
+    glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
+  }
 
-  glStencilFunc(GL_EQUAL,0x1,0x1);
-  stereo_projection(stereo_==2 ? 1 : 2);
-  root_node_->RenderGL(STANDARD_RENDER_PASS);
-  root_node_->RenderGL(GLOW_RENDER_PASS);
+  // right eye
+  if(stereo_mode_==1) {
+    glDrawBuffer(GL_BACK_RIGHT);
+    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  } else if(stereo_mode_==2) {
+    glStencilFunc(GL_EQUAL,0x0,0x1);
+  }
+#if OST_SHADER_SUPPORT_ENABLED
+  if(OST_GL_VERSION_2_0) {
+    glActiveTexture(GL_TEXTURE0);
+  }
+#endif
+  glBindTexture(GL_TEXTURE_2D, stereo_inverted_ ? scene_left_tex_ : scene_right_tex_);
+  // draw
+  glColor3f(1.0,0.0,1.0);
+  glBegin(GL_QUADS);
+  glTexCoord2f(0.0,0.0); glVertex2i(0,0);
+  glTexCoord2f(0.0,1.0); glVertex2i(0,vp_height_);
+  glTexCoord2f(1.0,1.0); glVertex2i(vp_width_,vp_height_);
+  glTexCoord2f(1.0,0.0); glVertex2i(vp_width_,0);
+  glEnd();
 
-  glStencilFunc(GL_EQUAL,0x0,0x1);
-  stereo_projection(stereo_==2 ? 2 : 1);
-  root_node_->RenderGL(STANDARD_RENDER_PASS);
-  root_node_->RenderGL(GLOW_RENDER_PASS);
-  glDisable(GL_STENCIL_TEST);
+  // left eye
+  if(stereo_mode_==1) {
+    glDrawBuffer(GL_BACK_LEFT);
+    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  } else if(stereo_mode_==2) {
+    glStencilFunc(GL_EQUAL,0x1,0x1);
+  }
+#if OST_SHADER_SUPPORT_ENABLED
+  if(OST_GL_VERSION_2_0) {
+    glActiveTexture(GL_TEXTURE0);
+  }
+#endif
+  glBindTexture(GL_TEXTURE_2D, stereo_inverted_ ? scene_right_tex_ : scene_left_tex_);
+  // draw
+  glColor3f(1.0,0.0,1.0);
+  glBegin(GL_QUADS);
+  glTexCoord2f(0.0,0.0); glVertex2i(0,0);
+  glTexCoord2f(0.0,1.0); glVertex2i(0,vp_height_);
+  glTexCoord2f(1.0,1.0); glVertex2i(vp_width_,vp_height_);
+  glTexCoord2f(1.0,0.0); glVertex2i(vp_width_,0);
+  glEnd();
+  
+  // restore settings
+  glMatrixMode(GL_PROJECTION);
+  glPopMatrix();
+  glMatrixMode(GL_MODELVIEW);
+  glPopMatrix();
   glPopAttrib();
+#if OST_SHADER_SUPPORT_ENABLED
+  Shader::Instance().PopProgram();
+#endif
 }
 
-void Scene::render_quad_buffered_stereo()
+void Scene::do_autoslab()
 {
-  glDrawBuffer(GL_BACK);
-  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
-  glDrawBuffer(GL_BACK_LEFT);
-  glClear(GL_DEPTH_BUFFER_BIT);
-  if (stereo_inverted_) {
-    stereo_projection(stereo_==1 ? 2 : 1);
-  } else {
-    stereo_projection(stereo_==1 ? 1 : 2);
-  }
-  this->render_scene_with_glow();
-  glDrawBuffer(GL_BACK_RIGHT);
-  glClear(GL_DEPTH_BUFFER_BIT);
-  if (stereo_inverted_) {
-    stereo_projection(stereo_==1 ? 1 : 2);
+  if(do_autoslab_fast_) {
+    geom::AlignedCuboid bb =this->GetBoundingBox(transform_);
+    // necessary code duplication due to awkward slab limit impl
+    znear_=-(bb.GetMax()[2]-1.0);
+    zfar_=-(bb.GetMin()[2]+1.0);
+    set_near(-(bb.GetMax()[2]-1.0));
+    set_far(-(bb.GetMin()[2]+1.0));
+    ResetProjection();
   } else {
-    stereo_projection(stereo_==1 ? 2 : 1);
+    LimCalc limcalc;
+    limcalc.transform=transform_;
+    limcalc.minc = Vec3(std::numeric_limits<float>::max(),
+                              std::numeric_limits<float>::max(),
+                              std::numeric_limits<float>::max());
+    limcalc.maxc = Vec3(-std::numeric_limits<float>::max(),
+                              -std::numeric_limits<float>::max(),
+                              -std::numeric_limits<float>::max());
+    this->Apply(limcalc);
+    float mynear=std::max(float(0.0), std::min(float(-limcalc.minc[2]),float(-limcalc.maxc[2])))-float(2.0);
+    float myfar=std::max(float(-limcalc.minc[2]),float(-limcalc.maxc[2]))+float(2.0);
+    znear_=mynear;
+    zfar_=myfar;
+    set_near(znear_);
+    set_far(zfar_);
+    ResetProjection();
   }
-  this->render_scene_with_glow();
-  glDrawBuffer(GL_BACK);
 }
 
 }} // ns
diff --git a/modules/gfx/src/scene.hh b/modules/gfx/src/scene.hh
index 87a6760551520bbcd017f6a82db785043ab154e0..34e2e033aeb50b462cca4d7087787d5b416e9b87 100644
--- a/modules/gfx/src/scene.hh
+++ b/modules/gfx/src/scene.hh
@@ -32,6 +32,7 @@
 #include <ost/gfx/module_config.hh>
 #include <ost/mol/transform.hh>
 
+#include "gl_include.hh"
 #include "color.hh"
 #include "gfx_object_fw.hh"
 #include "gfx_node_fw.hh"
@@ -40,22 +41,24 @@
 #include "glwin_base.hh"
 #include "scene_observer.hh"
 #include "gfx_prim.hh"
-#include "gl_include.hh"
 #include "povray_fw.hh"
 
 namespace ost { namespace gfx {
 
 class InputEvent;
+class OffscreenBuffer;
 
 typedef std::vector<SceneObserver*>  SceneObserverList;
 
 struct Viewport {
-  int bottom;
-  int left;
+  int x;
+  int y;
   int width;
   int height;
 };
 
+namespace impl {class SceneFX;}
+
 /// \brief main class for organization and root for the graphical display
 /// 
 /// The scene manages graphical objects for rendering. Typical graphical objects 
@@ -73,6 +76,7 @@ struct Viewport {
 /// disabling the AutoAutoslab(). The near and far clipping plane can then be 
 /// adjusted manually.
 class DLLEXPORT_OST_GFX Scene {
+  friend class impl::SceneFX;
  private:
    
   // TODO: this struct may be the seed for a proper
@@ -92,18 +96,39 @@ class DLLEXPORT_OST_GFX Scene {
   /// \brief turn fog on or off
   void SetFog(bool f);
 
+  /// \brief check fog status
+  bool GetFog() const;
+
   /// \brief set the fog color
   void SetFogColor(const Color& c);
 
-  /// \brief turn shadow on and off
+  /// \brief get the fog color
+  Color GetFogColor() const;
+
+  /// \brief turn shadow mapping on and off
   void SetShadow(bool f);
 
-  /// \brief returns true if shadow is on
-  bool GetShadow();
+  /// \brief get shadow mapping status
+  bool GetShadow() const;
 
   /// \brief shadow quality from 0 (low) to 3 (high), default=1
   void SetShadowQuality(int q);
+
+  void SetShadowWeight(float w);
+
+  void SetDepthDarkening(bool f);
+  void SetDepthDarkeningWeight(float f);
+
+  void SetAmbientOcclusion(bool f);
+  bool GetAmbientOcclusion() const;
+  void SetAmbientOcclusionWeight(float f);
+  void SetAmbientOcclusionMode(uint m);
+  void SetAmbientOcclusionQuality(uint q);
   
+  /// \brief select shading mode
+  /// one of fallback, basic, default, hf, toon1, toon2
+  void SetShadingMode(const std::string& smode);
+
   /// \name clipping planes
   //@{
   /// \brief get near clipping plane
@@ -143,30 +168,54 @@ class DLLEXPORT_OST_GFX Scene {
   void SetFogOffsets(float no, float fo);
   
   /// \brief adjust near and far clipping plane to fit visible objects
+  // TODO: use mode aka fast, precise, max
   void Autoslab(bool fast=false, bool redraw=true);
-  // \brief adjust clipping planes to fix maximal extent of all objects
-  //        even under rotation
+
+  /// \brief adjust clipping planes to fix maximal extent of all objects
+  ///        even under rotation
+  // TODO: merge with Autoslab
   void AutoslabMax();
 
   /// \brief turn on automatic auto-slabbing (using the fast bounding box alg)
+  // TODO: more sophisticated mode, aka fast, precise, max
   void AutoAutoslab(bool f);
   //@}
   
-  /// \brief switch stereo mode
-  /*
-    0=off
-    1=quad-buffered
-    2=interlaced variant #1
-    3=interlaced variant #2
-  */
-  void Stereo(unsigned int);
-
-  /// \brief invert stereo eyes for stereo mode=0
-  void SetStereoInverted(bool f);
+  /// \brief get current state of automatic auto-slabbing
+  bool GetAutoAutoslab() const { return auto_autoslab_; }
 
-  /// \brief eye mode, 0=center, 1=left, 2=right
-  void SetStereoEye(unsigned int);
+  /// \brief set stereo mode
+  /// one of 0 (off), 1 (quad-buffered) 2 (interlaced (for special monitors))
+  void SetStereoMode(unsigned int mode);
+  int GetStereoMode() const {return stereo_mode_;}
 
+  /// \brief invert stereo eyes for stereo mode=0
+  void SetStereoFlip(bool f);
+  /// \brief return invert flag for stereo
+  bool GetStereoFlip() const {return stereo_inverted_;}
+  
+  /// \brief stereo view mode
+  /// one of 0 (center), -1 (left), 1 (right)
+  void SetStereoView(int);
+  /// \brief return current stereo view mode
+  int GetStereoView() const {return stereo_eye_;}
+
+  /// \brief set stereo eye distance
+  void SetStereoIOD(Real);
+  /// \brief return current stereo eye distance
+  Real GetStereoIOD() const {return stereo_iod_;}
+
+  /// \brief set stereo distance offset from COR
+  void SetStereoDistance(Real);
+  /// \brief return current stereo distance offset from COR
+  Real GetStereoDistance() const {return stereo_distance_;}
+  
+  /// \brief set stereo algorithm
+  /// one of 0 or 1
+  void SetStereoAlg(unsigned int);
+  /// \brief return current stereo algorithm
+  unsigned int GetStereoAlg() const {return stereo_alg_;}
+  
   /// \brief set main light direction
   void SetLightDir(const geom::Vec3& dir);
   /// \brief set ambient, diffuse and specular light color
@@ -184,20 +233,22 @@ class DLLEXPORT_OST_GFX Scene {
   /// \name Export
   //@}
   /// \brief export scene into a bitmap, rendering into offscreen of given size
+  /// if a main offscreen buffer is active (\sa StartOffscreenMode), then the
+  /// dimensions here are ignored
   void Export(const String& fname, unsigned int w,
               unsigned int h, bool transparent=true);
 
   /// \brief export snapshot of current scene
   void Export(const String& fname, bool transparent=true);
 
-  /// \brief export scene into povray files names fname.pov and fname.inc
+  /// \brief export scene into povray files named fname.pov and fname.inc
   void ExportPov(const std::string& fname, const std::string& wdir=".");
   //@}
   /// \brief entry point for gui events (internal use)
   void OnInput(const InputEvent& e);
   
   /// \brief initialize OpenGL after context has been setup (internal use)
-  void InitGL();
+  void InitGL(bool full=true);
 
   /// \brief handle new viewport size (internal use)
   void Resize(int w, int h);
@@ -225,6 +276,9 @@ class DLLEXPORT_OST_GFX Scene {
   /// \brief set background color
   void SetBackground(const Color& c);
 
+  /// \brief get background color
+  Color GetBackground() const;
+
   /// \brief center rotation on the given point
   void SetCenter(const geom::Vec3& cen);
   
@@ -318,24 +372,41 @@ class DLLEXPORT_OST_GFX Scene {
   
   bool InOffscreenMode() const;
 
-  /// \brief internal use
-  static void SetOffscreenMode();
-
   /// \brief switch into test mode (internal use)
   void SetTestMode(bool t);
 
   float ElapsedTime() const;
 
   Viewport GetViewport() const;
-  
-  // temporary interface
-  void ActivateShader(const String& name);
 
+  /*!
+    This method has two different tasks. 
+
+    During interactive rendering, it facilitates export 
+    into an offscreen buffer with Scene::Export(file,width,height)
+    by avoiding repeated initializations of the GL state, e.g.
+    during animation rendering.
+
+    During batch mode, this is the only way to get meaningful
+    functionality with the gfx module
+
+    returns true upon success and false upon failure
+  */
+  bool StartOffscreenMode(unsigned int w, unsigned int h);
+  /// \brief stops offline rendering in interactive mode
+  void StopOffscreenMode();
+  
   void SetBlur(uint n);
   void BlurSnapshot();
 
   void RenderText(const TextPrim& t);
 
+  geom::Vec3 GetLightDir() const {return light_dir_;}
+  geom::Mat3 GetLightRot() const {return light_rot_;}
+
+  void SetBeacon(int wx, int wy);
+  void SetBeaconOff();
+
 protected:
   friend class GfxObj; 
   friend class GfxNode;
@@ -366,6 +437,8 @@ private:
 
   mol::Transform transform_; // overall modelview transformation
 
+  bool gl_init_;
+
   float fov_; // field of view
   float znear_,zfar_; // near and far clipping plane
   float fnear_,ffar_; // fog near and far offsets
@@ -387,12 +460,13 @@ private:
   bool axis_flag_;
   bool fog_flag_;
   Color fog_color_;
-  bool shadow_flag_;
-  int shadow_quality_;
-  GLuint texture_id_;
   bool auto_autoslab_;
+  bool do_autoslab_,do_autoslab_fast_;
 
-  bool offscreen_flag_;
+  bool offscreen_flag_; // a simple indicator whether in offscreen mode or not
+  OffscreenBuffer* main_offscreen_buffer_; // not null if a main offscreen buffer is present
+  uint old_vp_[2]; // used by the offline rendering code
+  std::string def_shading_mode_;
 
   uint selection_mode_;
 
@@ -405,24 +479,30 @@ private:
 
   uint blur_count_;
   std::vector<boost::shared_array<unsigned char> > blur_buffer_;
-  GLuint  glow_tex_;
-  unsigned int stereo_;
+
+  unsigned int stereo_mode_;
+  unsigned int stereo_alg_;
   bool stereo_inverted_;
   unsigned int stereo_eye_;
-  float stereo_eye_dist_,stereo_eye_offset_;
+  Real stereo_iod_,stereo_distance_;
+  unsigned int scene_left_tex_;
+  unsigned int scene_right_tex_;
 
   void set_near(float n);
   void set_far(float f);
   void update_fog();
-  void prep_shadow_map();
   void flag_all_dirty();
   void prep_glyphs();
   void prep_blur();
-  void stereo_projection(unsigned int view);
-  void render_interlaced_stereo();
-  void render_quad_buffered_stereo();
-  void render_scene_with_glow();
-  bool IsNameAvailable(String name);
+  void stereo_projection(int view);
+  void render_scene();
+  void render_glow();
+  void render_stereo();
+
+  void do_autoslab();
+
+  bool IsNameAvailable(const String& name) const;
+
 };
 
 }} // ns
diff --git a/modules/gfx/src/shader.cc b/modules/gfx/src/shader.cc
index b791be9a13940086730cd74266dc7723a787d727..0a14cf59bc35417e0c5d218289e4c1cd3f6a9574 100644
--- a/modules/gfx/src/shader.cc
+++ b/modules/gfx/src/shader.cc
@@ -49,7 +49,11 @@ Shader::Shader():
   current_name_(""),
   shader_code_map_(),
   shader_program_map_()
-{}
+{
+  if(!OST_GL_VERSION_2_0) {
+    LOG_VERBOSE("OpenGL version smaller 2.0, deactivating shader functionality");
+  }
+}
 
 
 void Shader::PreGLInit() 
@@ -63,9 +67,8 @@ void Shader::PreGLInit()
 #endif
 }
 
-namespace {
-
-bool compile_shader(String shader_name, String shader_code, GLenum shader_type, GLuint& shader_id)
+bool Shader::Compile(std::string shader_name, std::string shader_code, 
+                     GLenum shader_type, GLuint& shader_id)
 {
   shader_id = glCreateShader(shader_type);
   const char* tmp_ptr[] = {0};
@@ -88,7 +91,7 @@ bool compile_shader(String shader_name, String shader_code, GLenum shader_type,
   return true;
 }
 
-bool link_shader(const std::vector<GLuint>& code_list, String pr_name, GLuint& shader_pr)
+bool Shader::Link(const std::vector<GLuint>& code_list, std::string pr_name, GLuint& shader_pr)
 {
   shader_pr = glCreateProgram();
   for(std::vector<GLuint>::const_iterator it=code_list.begin();it!=code_list.end();++it) {
@@ -116,10 +119,36 @@ bool link_shader(const std::vector<GLuint>& code_list, String pr_name, GLuint& s
   return true;
 }
 
+bool Shader::Add(const std::string& name, const std::string& vs_code, const std::string& fs_code)
+{
+  GLuint vs_id=0;
+  if(!Shader::Compile(name,vs_code,GL_VERTEX_SHADER,vs_id)) {
+    return false;
+  }
+  
+  GLuint fs_id=0;
+  if(!Shader::Compile(name,fs_code,GL_FRAGMENT_SHADER,fs_id)) {
+    return false;
+  }
+  
+  std::vector<GLuint> shader_program_list;
+  GLuint id;
+
+  shader_program_list.push_back(vs_id);
+  shader_program_list.push_back(fs_id);
+  if(!Shader::Link(shader_program_list,"hatch",id)) {
+    return false;
+  }
+
+  shader_program_map_[name]=id;
+  return true;
 }
 
+
 void Shader::Setup() 
 {
+  if(!OST_GL_VERSION_2_0) return;
+
   String ost_root = GetSharedDataPath();
   bf::path ost_root_dir(ost_root);
   bf::path shader_dir(ost_root_dir / "shader");
@@ -129,16 +158,12 @@ void Shader::Setup()
     GLenum type;
   } shader_list[] = {
     //////////////////////////////////////////////////////////////////
-    // this is the master list of all shader code in lib/ost/shader
-
-    {"basic_lf_vs.glsl", GL_VERTEX_SHADER},
-    {"basic_lf_fs.glsl", GL_FRAGMENT_SHADER},
-    {"fraglight_lf_vs.glsl", GL_VERTEX_SHADER},
-    {"fraglight_lf_fs.glsl", GL_FRAGMENT_SHADER},
-    {"basic_lfs_vs.glsl", GL_VERTEX_SHADER},
-    {"basic_lfs_fs.glsl", GL_FRAGMENT_SHADER},
-    {"fraglight_lfs_vs.glsl", GL_VERTEX_SHADER},
-    {"fraglight_lfs_fs.glsl", GL_FRAGMENT_SHADER},
+    // this is the master list of all shader code in shader/
+
+    {"basic_vs.glsl", GL_VERTEX_SHADER},
+    {"basic_fs.glsl", GL_FRAGMENT_SHADER},
+    {"fraglight_vs.glsl", GL_VERTEX_SHADER},
+    {"fraglight_fs.glsl", GL_FRAGMENT_SHADER},
     {"basic_hf_vs.glsl", GL_VERTEX_SHADER},
     {"selfx_vs.glsl", GL_VERTEX_SHADER},
     {"selfx_fs.glsl", GL_FRAGMENT_SHADER},
@@ -151,7 +176,17 @@ void Shader::Setup()
     {"iso_fs.glsl", GL_FRAGMENT_SHADER},
     {"fast_sphere_vs.glsl", GL_VERTEX_SHADER},
     {"fast_sphere_fs.glsl", GL_FRAGMENT_SHADER},
-    {"outline_vs.glsl", GL_VERTEX_SHADER}
+    {"outline_vs.glsl", GL_VERTEX_SHADER},
+    {"dumpnorm_vs.glsl", GL_VERTEX_SHADER},
+    {"dumpnorm_fs.glsl", GL_FRAGMENT_SHADER},
+    {"quadpp_vs.glsl", GL_VERTEX_SHADER},
+    {"convolute1_fs.glsl", GL_FRAGMENT_SHADER},
+    {"amboccl_fs.glsl", GL_FRAGMENT_SHADER},
+    {"scenefx_vs.glsl", GL_VERTEX_SHADER},
+    {"scenefx_fs.glsl", GL_FRAGMENT_SHADER},
+    {"beacon_fs.glsl", GL_FRAGMENT_SHADER},
+    {"screenblur4_fs.glsl", GL_FRAGMENT_SHADER},
+    {"test_tex_fs.glsl", GL_FRAGMENT_SHADER}
     //////////////////////////////////////////////////////////////////
   };
 
@@ -174,7 +209,7 @@ void Shader::Setup()
     }
 
     GLuint shader_id;
-    if(compile_shader(shader_name,shader_code,shader_list[i].type,shader_id)) {
+    if(Shader::Compile(shader_name,shader_code,shader_list[i].type,shader_id)) {
       shader_code_map_[shader_name]=shader_id;
     } else {
       shader_code_map_[shader_name]=0;
@@ -184,94 +219,131 @@ void Shader::Setup()
   std::vector<GLuint> shader_program_list;
   GLuint shader_program_id;
   // basic shader
-  shader_program_list.push_back(shader_code_map_["basic_lf_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["basic_lf_fs.glsl"]);
-  if(link_shader(shader_program_list,"basic",shader_program_id)) {
+  shader_program_list.push_back(shader_code_map_["basic_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["basic_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"basic",shader_program_id)) {
     shader_program_map_["basic"]=shader_program_id;
   }
   // fraglight shader
   shader_program_list.clear();
-  shader_program_list.push_back(shader_code_map_["fraglight_lf_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["fraglight_lf_fs.glsl"]);
-  if(link_shader(shader_program_list,"fraglight",shader_program_id)) {
+  shader_program_list.push_back(shader_code_map_["fraglight_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["fraglight_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"fraglight",shader_program_id)) {
     shader_program_map_["fraglight"]=shader_program_id;
   }
-  // basic shadow map shader
-  shader_program_list.clear();
-  shader_program_list.push_back(shader_code_map_["basic_lfs_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["basic_lfs_fs.glsl"]);
-  if(link_shader(shader_program_list,"basic_shadow",shader_program_id)) {
-    shader_program_map_["basic_shadow"]=shader_program_id;
-  }
-  // fraglight shader with shadow map
-  shader_program_list.clear();
-  shader_program_list.push_back(shader_code_map_["fraglight_lfs_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["fraglight_lfs_fs.glsl"]);
-  if(link_shader(shader_program_list,"fraglight_shadow",shader_program_id)) {
-    shader_program_map_["fraglight_shadow"]=shader_program_id;
-  }
   // basic hemisphere lighting shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["basic_hf_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["basic_lf_fs.glsl"]);
-  if(link_shader(shader_program_list,"hemilight",shader_program_id)) {
+  shader_program_list.push_back(shader_code_map_["basic_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"hemilight",shader_program_id)) {
     shader_program_map_["hemilight"]=shader_program_id;
   }
   // selfx shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["selfx_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["selfx_fs.glsl"]);
-  if(link_shader(shader_program_list,"selfx",shader_program_id)) {
+  if(Shader::Link(shader_program_list,"selfx",shader_program_id)) {
     shader_program_map_["selfx"]=shader_program_id;
   }
   // toon shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["toon_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["toon_fs.glsl"]);
-  if(link_shader(shader_program_list,"toon",shader_program_id)) {
-    shader_program_map_["toon"]=shader_program_id;
+  if(Shader::Link(shader_program_list,"toon1",shader_program_id)) {
+    shader_program_map_["toon1"]=shader_program_id;
   }
   // toon2 shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["toon_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["toon2_fs.glsl"]);
-  if(link_shader(shader_program_list,"toon2",shader_program_id)) {
+  if(Shader::Link(shader_program_list,"toon2",shader_program_id)) {
     shader_program_map_["toon2"]=shader_program_id;
   }
   // line shader
   shader_program_list.clear();
-  shader_program_list.push_back(shader_code_map_["basic_lf_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["basic_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["aaline_fs.glsl"]);
-  if(link_shader(shader_program_list,"aaline",shader_program_id)) {
+  if(Shader::Link(shader_program_list,"aaline",shader_program_id)) {
     shader_program_map_["aaline"]=shader_program_id;
   }
   // iso shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["iso_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["iso_fs.glsl"]);
-  if(link_shader(shader_program_list,"iso",shader_program_id)) {
+  if(Shader::Link(shader_program_list,"iso",shader_program_id)) {
     shader_program_map_["iso"]=shader_program_id;
   }
   // fast sphere shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["fast_sphere_vs.glsl"]);
   shader_program_list.push_back(shader_code_map_["fast_sphere_fs.glsl"]);
-  if(link_shader(shader_program_list,"fast_sphere",shader_program_id)) {
+  if(Shader::Link(shader_program_list,"fast_sphere",shader_program_id)) {
     shader_program_map_["fast_sphere"]=shader_program_id;
   }
-  // basic shader
+  // outline shader
   shader_program_list.clear();
   shader_program_list.push_back(shader_code_map_["outline_vs.glsl"]);
-  shader_program_list.push_back(shader_code_map_["basic_lf_fs.glsl"]);
-  if(link_shader(shader_program_list,"outline",shader_program_id)) {
+  shader_program_list.push_back(shader_code_map_["basic_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"outline",shader_program_id)) {
     shader_program_map_["outline"]=shader_program_id;
   }
+  // dumpnorm shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["dumpnorm_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["dumpnorm_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"dumpnorm",shader_program_id)) {
+    shader_program_map_["dumpnorm"]=shader_program_id;
+  }
+  // convolute1 shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["quadpp_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["convolute1_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"convolute1",shader_program_id)) {
+    shader_program_map_["convolute1"]=shader_program_id;
+  }
+  // amboccl shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["quadpp_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["amboccl_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"amboccl",shader_program_id)) {
+    shader_program_map_["amboccl"]=shader_program_id;
+  }
+  // beacon shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["scenefx_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["beacon_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"beacon",shader_program_id)) {
+    shader_program_map_["beacon"]=shader_program_id;
+  }
+  // scenefx shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["scenefx_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["scenefx_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"scenefx",shader_program_id)) {
+    shader_program_map_["scenefx"]=shader_program_id;
+  }
+  // screen blur shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["quadpp_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["screenblur4_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"screenblur4",shader_program_id)) {
+    shader_program_map_["screenblur4"]=shader_program_id;
+  }
+  // test tex shader
+  shader_program_list.clear();
+  shader_program_list.push_back(shader_code_map_["fraglight_vs.glsl"]);
+  shader_program_list.push_back(shader_code_map_["test_tex_fs.glsl"]);
+  if(Shader::Link(shader_program_list,"test_tex",shader_program_id)) {
+    shader_program_map_["test_tex"]=shader_program_id;
+  }
 
   valid_=true;
 }
 
 void Shader::Activate(const String& name)
 {
+  if(!OST_GL_VERSION_2_0) return;
+
   if(!name.empty()) {
     std::map<String, GLuint>::iterator it = shader_program_map_.find(name);
     if(it!=shader_program_map_.end()) {
@@ -280,14 +352,6 @@ void Shader::Activate(const String& name)
       current_program_=it->second;
       current_name_=name;
 
-      if(name=="basic_shadow" || name=="fraglight_shadow") {
-    	if(!Scene::Instance().GetShadow())
-          Scene::Instance().SetShadow(true);
-      } else {
-      	if(Scene::Instance().GetShadow())
-          Scene::Instance().SetShadow(false);
-      }
-
       UpdateState();
       return;
 
@@ -314,6 +378,7 @@ String Shader::GetCurrentName() const
 
 bool Shader::IsValid() const
 {
+  if(!OST_GL_VERSION_2_0) return false;
   return valid_;
 }
 
@@ -324,11 +389,13 @@ bool Shader::IsActive() const
 
 void Shader::PushProgram()
 {
+  if(!OST_GL_VERSION_2_0) return;
   program_stack_.push(current_name_);
 }
 
 void Shader::PopProgram()
 {
+  if(!OST_GL_VERSION_2_0) return;
   if(!program_stack_.empty()) {
     current_name_ = program_stack_.top();
     program_stack_.pop();
@@ -338,8 +405,9 @@ void Shader::PopProgram()
 
 void Shader::UpdateState()
 {
+  if(!OST_GL_VERSION_2_0) return;
   if(current_program_!=0) {
-    // update current lighting and fog settings, valid for all shaders
+    // update all settings
     GLint result;
     glGetIntegerv(GL_LIGHTING,&result);
     LOG_TRACE("setting lighting flag to " << result);
@@ -352,6 +420,7 @@ void Shader::UpdateState()
     LOG_TRACE("setting fog flag to " << result);
     glUniform1i(glGetUniformLocation(current_program_,"fog_flag"),result);
     glDisable(GL_COLOR_MATERIAL);
+
   } else {
     glEnable(GL_COLOR_MATERIAL);
   }
diff --git a/modules/gfx/src/shader.hh b/modules/gfx/src/shader.hh
index 054fdc37e1e98c19f27a6d29a17f20085547b895..ecd457beb878979d75573182a9b328b8e07d5123 100644
--- a/modules/gfx/src/shader.hh
+++ b/modules/gfx/src/shader.hh
@@ -28,8 +28,10 @@
 #include <string>
 #include <map>
 #include <stack>
+#include <vector>
+
 #include <ost/gfx/module_config.hh>
-#include "gl_include.hh"
+#include "glext_include.hh"
 
 namespace ost { namespace gfx {
 
@@ -38,6 +40,13 @@ public:
   // singleton implementation
   static Shader& Instance();
 
+  static bool Compile(std::string shader_name, std::string shader_code,
+                      GLenum shader_type, GLuint& shader_id);
+
+  static bool Link(const std::vector<GLuint>& code_list, std::string pr_name, GLuint& shader_pr);
+
+  bool Add(const std::string& name, const std::string& vs_code, const std::string& fs_code);
+
   void PreGLInit();
   void Setup();
   void Activate(const String& name);
@@ -52,7 +61,6 @@ public:
   void PopProgram();
 
   void UpdateState();
-  
 private:
   Shader();
 
diff --git a/modules/gfx/src/shader/amboccl_fs.glsl b/modules/gfx/src/shader/amboccl_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..2d7819565c59158fc80272ce19bc059e7dfaeb9f
--- /dev/null
+++ b/modules/gfx/src/shader/amboccl_fs.glsl
@@ -0,0 +1,76 @@
+uniform sampler2D depth_map;
+uniform sampler2D norm_map;
+uniform sampler1D kernel;
+uniform float step;
+uniform vec2 i_vp;
+uniform vec4 abcd;
+uniform int mode;
+
+// gl_TexCoord[0] comes from quadpp_vs, i.e. from post processing
+
+vec3 unproject(in vec3 rpos)
+{ 
+  vec4 coord = gl_TextureMatrix[0]*vec4(rpos.xy*2.0-1.0,rpos.z*2.0-1.0,1.0);
+  return coord.xyz/coord.w;
+}
+
+float ao(in vec2 tab, in float depth_p, in vec3 norm_p, in vec3 t_pos_p)
+{
+  vec2 rpos = gl_TexCoord[0].xy+tab.xy*i_vp;
+  float depth_q = texture2D(depth_map,rpos).r;
+  if(mode==0) {
+    if(depth_q>=depth_p) {
+      return 0.0;
+    } else {
+      return 1.0;
+    }
+  } 
+
+  vec3 t_pos_q = unproject(vec3(rpos.xy,depth_q));
+  vec3 diff=t_pos_q-t_pos_p;
+  float nd = dot(normalize(norm_p),normalize(diff));
+
+  if(mode==1) {
+    return 1.6*max(0.0,nd);
+  }
+
+  if(mode==2) {
+    float fac=1.0+dot(diff,diff)/100.0;
+    return 1.6*max(0.0,nd)/fac;
+  }
+
+  if(mode==3) {
+    // radius of imposter at distance depth_q to cover a single pixel
+    vec4 tmpv=gl_TextureMatrix[0]*vec4(-1.0,0.0,depth_q,1.0);
+    float tmpd=tmpv.x/tmpv.w;
+    tmpv=gl_TextureMatrix[0]*vec4(1.0,0.0,depth_q,1.0);
+    // 10.0 is a fudge factor
+    float rad=10.0*i_vp[0]*abs(tmpv.x/tmpv.w-tmpd);
+    float s = 6.283*(1.0-sqrt(1.0-min(1.0,rad*rad/dot(diff,diff))));
+    return s*max(0.0,nd);
+  }
+
+  return 0.0;
+}
+
+void main()
+{
+  float depth_p = texture2D(depth_map,gl_TexCoord[0].xy).r;
+  if(depth_p>=1.0) {
+    gl_FragColor = vec4(0,0,0,1);
+    return;
+  }
+  vec3 norm_p = (texture2D(norm_map,gl_TexCoord[0].xy).xyz-0.5)*2.0;
+  vec3 t_pos_p = unproject(vec3(gl_TexCoord[0].xy,depth_p));
+
+  float i;
+  float sum=0.0;
+  for(i=0.0;i<1.0;i+=step) {
+    vec2 nn=texture1D(kernel,i).xy*40.0-20.0;
+    sum+=ao(nn,depth_p,norm_p,t_pos_p);
+  }
+  sum*=step;
+
+  gl_FragColor.rgb=vec3(sum,sum,sum);
+  gl_FragColor.a=1.0;
+}
diff --git a/modules/gfx/src/shader/basic_fs.glsl b/modules/gfx/src/shader/basic_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..9856cd3a47445b3ea94d57e9e00ea34c90ec2474
--- /dev/null
+++ b/modules/gfx/src/shader/basic_fs.glsl
@@ -0,0 +1,9 @@
+uniform bool fog_flag;
+
+void main()
+{
+  float fog = fog_flag ? clamp((gl_Fog.end-gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0) : 1.0;
+  gl_FragColor.rgb = mix(gl_Fog.color.rgb, gl_Color.rgb, fog);
+  gl_FragColor.a = gl_Color.a;
+}
+
diff --git a/modules/gfx/src/shader/basic_hf_vs.glsl b/modules/gfx/src/shader/basic_hf_vs.glsl
index 4dbe147a6a9a9261d34038de21107c36efbf8f58..80324bf1d7a4764f719de0bff3f9dc5775b3f6e1 100644
--- a/modules/gfx/src/shader/basic_hf_vs.glsl
+++ b/modules/gfx/src/shader/basic_hf_vs.glsl
@@ -17,7 +17,10 @@ void main()
   // hemisphere lighting contribution
   vec3 ec_pos = vec3(gl_ModelViewMatrix* gl_Vertex);
   if(lighting_flag) {
-    vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
+    vec3 normal = vec3(0,0,1);
+    if(dot(gl_Normal,gl_Normal)>0.001) {
+      normal = normalize(gl_NormalMatrix * gl_Normal);
+    }
     vec3 l_dir  = normalize(gl_LightSource[0].position.xyz); // assume directional vector
     float a  = 0.5+0.5*dot(normal,l_dir);
     gl_FrontColor.rgb = mix(ground_color, sky_color, a).rgb;
diff --git a/modules/gfx/src/shader/basic_lfs_fs.glsl b/modules/gfx/src/shader/basic_lfs_fs.glsl
deleted file mode 100644
index 66d8b04415336972b8553a7146601e67516e6dea..0000000000000000000000000000000000000000
--- a/modules/gfx/src/shader/basic_lfs_fs.glsl
+++ /dev/null
@@ -1,33 +0,0 @@
-uniform sampler2D shadow_map;
-uniform bool shadow_flag;
-uniform float depth_bias;
-uniform float epsilon;
-uniform float shadow_multiplier;
-uniform bool fog_flag;
-
-float CalcShadowFactor(in vec4 coord, in vec2 o)
-{
-  // get original depth value of line projected towards light
-  float d = texture2D(shadow_map, coord.xy+o*epsilon).x+depth_bias;
-  return d<=coord.z ? shadow_multiplier : 1.0;
-}
-
-void main()
-{
-  float fog = fog_flag ? clamp((gl_Fog.end-gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0) : 1.0;
-  if(shadow_flag) {
-    vec4 coord=gl_TexCoord[1]/gl_TexCoord[1].w;
-    float sum = 0.0;
-    sum += 0.18*CalcShadowFactor(coord, vec2(-0.7, -0.7));
-    sum += 0.18*CalcShadowFactor(coord, vec2(0.7, -0.7));
-    sum += 0.18*CalcShadowFactor(coord, vec2(0.7, 0.7));
-    sum += 0.18*CalcShadowFactor(coord, vec2(-0.7, 0.7));
-    sum += 0.28*CalcShadowFactor(coord, vec2(0, 0));
-
-    gl_FragColor = vec4(sum*mix(gl_Fog.color.rgb, gl_Color.rgb, fog),gl_Color.a);
-  } else {
-    gl_FragColor.rgb = mix(gl_Fog.color.rgb, gl_Color.rgb, fog);
-    gl_FragColor.a = gl_Color.a;
-  }
-}
-
diff --git a/modules/gfx/src/shader/basic_lfs_vs.glsl b/modules/gfx/src/shader/basic_vs.glsl
similarity index 95%
rename from modules/gfx/src/shader/basic_lfs_vs.glsl
rename to modules/gfx/src/shader/basic_vs.glsl
index 9f43289f6ab97923b819fa89c5fe71d6a6f5f43e..7c1a080f15600d8cc1626d3b38307e9bc61a7969 100644
--- a/modules/gfx/src/shader/basic_lfs_vs.glsl
+++ b/modules/gfx/src/shader/basic_vs.glsl
@@ -56,6 +56,7 @@ void main()
   vec4 ec_Pos = gl_ModelViewMatrix* gl_Vertex;
 
   vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
+  gl_TexCoord[2].stp = normal;
   
   if(lighting_flag) {
     CalcFrontAndBackColor(normal);
@@ -66,8 +67,5 @@ void main()
 
   // for some reason, the fog and z coordinate are sign toggled...
   gl_FogFragCoord = -ec_Pos.z;
-
-  // shadow map projection coords
-  gl_TexCoord[1] = gl_TextureMatrix[0] * gl_Vertex;
 }
 
diff --git a/modules/gfx/src/shader/beacon_fs.glsl b/modules/gfx/src/shader/beacon_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..aa910131fe554bd79338bdf54c4f2e01130501e8
--- /dev/null
+++ b/modules/gfx/src/shader/beacon_fs.glsl
@@ -0,0 +1,25 @@
+uniform vec3 pos;
+uniform vec3 dir;
+uniform float len;
+uniform float rad;
+uniform sampler2D depth_map;
+
+// gl_TexCoord[0] comes from scenefx_vs, i.e. from post processing
+
+void main()
+{
+  float depth = texture2D(depth_map,gl_TexCoord[0].xy).r;
+  if(depth>=1.0) {
+    discard;
+  }
+  vec4 pcoord = vec4(gl_TexCoord[0].xy*2.0-1.0,depth*2.0-1.0,1.0);
+  vec4 coord = gl_TextureMatrix[1]*pcoord;
+  coord/=coord.w;
+
+  float d = length(cross(dir,coord.xyz-pos))/len;
+  if(d>rad) {
+    discard;
+  }
+  gl_FragColor.rgb=vec3(0,1.0,0);
+  gl_FragColor.a=min(0.9,mix(3.0,0.0,d/rad));
+}
diff --git a/modules/gfx/src/shader/convolute1_fs.glsl b/modules/gfx/src/shader/convolute1_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..41d89053d6ad2bc973fc5c0724d5e81109d503c2
--- /dev/null
+++ b/modules/gfx/src/shader/convolute1_fs.glsl
@@ -0,0 +1,27 @@
+uniform sampler2D data;
+uniform sampler1D kernel;
+uniform float step;
+uniform vec2 i_vp;
+
+// gl_TexCoord[0] comes from quadpp_vs, i.e. from post processing
+
+void main()
+{
+  float i;
+  float sum=0.0;
+  float sum2=0.0;
+  for (i=0.0;i<1.0;i=i+step) {
+    vec3 kvalue = texture1D(kernel,i).xyz;
+    kvalue.xy=(kvalue.xy-0.5)*10.0*i_vp;
+    sum+=kvalue.z*texture2D(data,gl_TexCoord[0].xy+kvalue.xy).r;
+    sum2+=kvalue.z;
+  }
+  sum=sum/sum2;
+  float delta=5.0*(sum-texture2D(data,gl_TexCoord[0].xy).r);
+  if(delta<0.0) {
+    gl_FragColor.rgb=vec3(1.0+delta,1.0+delta,1.0+delta);
+  } else {
+    gl_FragColor.rgb=vec3(1.0,1.0,1.0);
+  }
+  gl_FragColor.a=1.0;
+}
diff --git a/modules/gfx/src/shader/dumpnorm_fs.glsl b/modules/gfx/src/shader/dumpnorm_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..09bee99284fd774c4d5a010f10b31c603d104aa9
--- /dev/null
+++ b/modules/gfx/src/shader/dumpnorm_fs.glsl
@@ -0,0 +1,5 @@
+void main()
+{
+  gl_FragColor.rgb=normalize(gl_TexCoord[0]).stp*0.5+0.5;
+}
+
diff --git a/modules/gfx/src/shader/dumpnorm_vs.glsl b/modules/gfx/src/shader/dumpnorm_vs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..f4cc4a1b43079dbd4ce92c5e101db7cec3d56d47
--- /dev/null
+++ b/modules/gfx/src/shader/dumpnorm_vs.glsl
@@ -0,0 +1,10 @@
+void main()
+{
+  gl_Position = ftransform();
+  vec3 normal = vec3(0,0,1);
+  if(dot(gl_Normal,gl_Normal)>0.001) {
+    normal = gl_NormalMatrix * gl_Normal;
+  }
+  gl_TexCoord[0].stp=normal;
+}
+
diff --git a/modules/gfx/src/shader/fast_sphere_fs.glsl b/modules/gfx/src/shader/fast_sphere_fs.glsl
index f6c47e9befe29c9e0590bd0c95cdd544da405d84..8832b5e28f850064d68a1082b050ed4ccb88ac04 100644
--- a/modules/gfx/src/shader/fast_sphere_fs.glsl
+++ b/modules/gfx/src/shader/fast_sphere_fs.glsl
@@ -1,6 +1,10 @@
 uniform bool lighting_flag;
 uniform bool two_sided_flag;
 uniform bool fog_flag;
+uniform bool write_normals;
+
+// gl_TexCoord[0] is from gl_MultiTexCoord0, which in turn
+// is custom crafted in the fast sphere prep routine
 
 // copy from basic_fl_vs !
 bool DirectionalLight(in vec3 normal,
@@ -32,6 +36,13 @@ void main()
   float z1 = gl_TexCoord[0].z*zz;
   float z2 = gl_TexCoord[0].w*zz;
 
+  gl_FragDepth = gl_FragCoord.z+z2;
+
+  if(write_normals) {
+    gl_FragColor.rgb=normal*0.5+0.5;
+    return;
+  }
+
   vec4 amb = vec4(0.0);
   vec4 diff = vec4(0.0);
   vec4 spec = vec4(0.0);
@@ -50,5 +61,4 @@ void main()
   gl_FragColor.rgb = color.rgb;
   gl_FragColor.a = 1.0;
 
-  gl_FragDepth = gl_FragCoord.z+z2;
 }
diff --git a/modules/gfx/src/shader/fraglight_lf_fs.glsl b/modules/gfx/src/shader/fraglight_fs.glsl
similarity index 50%
rename from modules/gfx/src/shader/fraglight_lf_fs.glsl
rename to modules/gfx/src/shader/fraglight_fs.glsl
index 7ffec79b80c30e5f4daf458f3cf63bc510d6fc16..76ff5dfaff9dbef8def110bee406ae67407fedac 100644
--- a/modules/gfx/src/shader/fraglight_lf_fs.glsl
+++ b/modules/gfx/src/shader/fraglight_fs.glsl
@@ -1,19 +1,23 @@
 uniform bool lighting_flag;
 uniform bool two_sided_flag;
 uniform bool fog_flag;
-uniform bool occlusion_flag;
-varying vec4 ambient_color;
+uniform sampler2D depth_map;
+uniform int depth_mode;
+uniform bool tex_flag;
+uniform sampler2D tex_map;
 
 // copy from basic_fl_vs !
 bool DirectionalLight(in vec3 normal,
                       in float shin,
                       inout vec4 ambient,
                       inout vec4 diffuse,
-                      inout vec4 specular)
+                      inout vec4 specular,
+		      inout bool lflag)
 {
   float n_vp = max(0.0, dot(normal, normalize(gl_LightSource[0].position.xyz)));
 
   float pf = 0.0;
+  lflag = n_vp>0.0;
   if(n_vp>0.0 && shin>0.0) {
     float n_hv = max(0.0, dot(normal, normalize(gl_LightSource[0].halfVector.xyz)));
     pf=pow(n_hv, shin);
@@ -28,49 +32,41 @@ bool DirectionalLight(in vec3 normal,
 
 void main()
 {
+  bool lflag=false;
+
+  vec4 color = gl_Color;
+
+  if(tex_flag) {
+    color.rgb = texture2D(tex_map,gl_TexCoord[0].st).rgb;
+  }
+
   if(lighting_flag) {
-    vec3 normal = normalize(gl_TexCoord[0].stp);
+    vec3 normal = normalize(gl_TexCoord[2].stp);
 
     vec4 amb = vec4(0.0);
     vec4 diff = vec4(0.0);
     vec4 spec = vec4(0.0);
-    vec4 color = vec4(0.0);
 
-    /* 
-      For ambient occlusion, this blends the local ambient color together with
-      the fragment color at intensity given my the ambient material settings;
-      ambient_color defaults to gl_Color, so for non ambient-occluded scenes,
-      this is a noop
-    */
-    vec4 diff_color = gl_Color;
-    if(occlusion_flag) {
-      diff_color.rgb = mix(gl_Color.rgb,ambient_color.rgb,gl_FrontMaterial.ambient.rgb);
-    }
-
-    if(DirectionalLight(normal, gl_FrontMaterial.shininess, amb, diff, spec)) {
+    if(DirectionalLight(normal, gl_FrontMaterial.shininess, amb, diff, spec, lflag)) {
 
       color  = gl_FrontLightModelProduct.sceneColor  +
-               (amb  * gl_FrontMaterial.diffuse * diff_color * ambient_color.a) +
-               (diff * gl_FrontMaterial.diffuse * diff_color) +
+               (amb  * gl_FrontMaterial.ambient * color) +
+               (diff * gl_FrontMaterial.diffuse * color) +
                (spec * gl_FrontMaterial.specular);
     } else {
-      DirectionalLight(-normal, gl_BackMaterial.shininess, amb, diff, spec);
+      bool dummy;
+      DirectionalLight(-normal, gl_BackMaterial.shininess, amb, diff, spec, dummy);
 
       color = gl_BackLightModelProduct.sceneColor  +
-              (amb  * gl_BackMaterial.ambient * diff_color * ambient_color.a) +
-              (diff * gl_BackMaterial.diffuse * diff_color) +
+              (amb  * gl_BackMaterial.ambient * color) +
+              (diff * gl_BackMaterial.diffuse * color) +
               (spec * gl_BackMaterial.specular);
     }
-    
-    gl_FragColor = color;
-
-  } else {
-    gl_FragColor = gl_Color;
   }
 
-  if(fog_flag) {
-    float fog = clamp((gl_Fog.end-gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0);
-    gl_FragColor.rgb = mix(gl_Fog.color.rgb, gl_FragColor.rgb, fog);
-  }
+  gl_FragColor = color;
+
+  float fog = fog_flag ? clamp((gl_Fog.end-gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0) : 1.0;
+  gl_FragColor.rgb = mix(gl_Fog.color.rgb, gl_FragColor.rgb, fog);
   gl_FragColor.a = gl_Color.a;
 }
diff --git a/modules/gfx/src/shader/fraglight_lf_vs.glsl b/modules/gfx/src/shader/fraglight_lf_vs.glsl
deleted file mode 100644
index 011fb782053ecc1f5a65a11658c6099304e8ad9e..0000000000000000000000000000000000000000
--- a/modules/gfx/src/shader/fraglight_lf_vs.glsl
+++ /dev/null
@@ -1,27 +0,0 @@
-uniform bool occlusion_flag;
-varying vec4 ambient_color;
-
-void main()
-{
-  // transformed position
-  gl_Position = ftransform();
-
-  vec4 ec_Pos = gl_ModelViewMatrix* gl_Vertex;
-  // for some reason, the fog and z coordinate are sign toggled...
-  gl_FogFragCoord = -ec_Pos.z;
-
-  vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
-  // since a directional light is used, the position is not needed
-  gl_TexCoord[0].stp=normal;
-
-  if(occlusion_flag) {
-    // ambient occlusion and color terms
-    ambient_color = gl_MultiTexCoord0;
-  } else {
-    ambient_color = gl_Color;
-    ambient_color.a = 1.0;
-  }
-  gl_FrontColor=gl_Color;
-  gl_BackColor=gl_Color;
-}
-
diff --git a/modules/gfx/src/shader/fraglight_lfs_fs.glsl b/modules/gfx/src/shader/fraglight_lfs_fs.glsl
deleted file mode 100644
index d6a9580e70c5d735d1be8913be053ab56d19b8c5..0000000000000000000000000000000000000000
--- a/modules/gfx/src/shader/fraglight_lfs_fs.glsl
+++ /dev/null
@@ -1,98 +0,0 @@
-uniform sampler2D shadow_map;
-uniform bool shadow_flag;
-uniform float depth_bias;
-uniform float epsilon;
-uniform float shadow_multiplier;
-uniform bool lighting_flag;
-uniform bool two_sided_flag;
-uniform bool fog_flag;
-
-// copy from basic_lfs_fs !
-float CalcShadowFactor(in vec4 coord, in vec2 o)
-{
-  // get original depth value of line projected towards light
-  float d = texture2D(shadow_map, coord.xy+o*epsilon).x+depth_bias;
-  return d<=coord.z ? shadow_multiplier : 1.0;
-}
-
-// modified copy from basic_fl_vs !
-bool DirectionalLight(in vec3 normal,
-                      in float shin,
-                      inout vec4 ambient,
-                      inout vec4 diffuse,
-                      inout vec4 specular,
-                      inout bool lflag)
-{
-  float n_vp = max(0.0, dot(normal, normalize(gl_LightSource[0].position.xyz)));
-
-  lflag = n_vp>0.0;
-  if(n_vp==0.0 && two_sided_flag) return false;
-
-  float pf = 0.0;
-  if(n_vp>0.0 && shin>0.0) {
-    float n_hv = max(0.0, dot(normal, normalize(gl_LightSource[0].halfVector.xyz)));
-    pf=pow(n_hv, shin);
-  }
-
-  ambient  += gl_LightSource[0].ambient;
-  diffuse  += gl_LightSource[0].diffuse * n_vp;
-  specular += gl_LightSource[0].specular * pf;
-
-  return true;
-}
-
-void main()
-{
-  bool lflag=false;
-
-  if(lighting_flag) {
-    vec3 normal = normalize(gl_TexCoord[0].stp);
-
-    vec4 amb = vec4(0.0);
-    vec4 diff = vec4(0.0);
-    vec4 spec = vec4(0.0);
-    vec4 color = vec4(0.0);
-    
-    if(DirectionalLight(normal, gl_FrontMaterial.shininess, amb, diff, spec,lflag)) {
-   
-        color  = gl_FrontLightModelProduct.sceneColor  +
-                 (amb  * gl_FrontMaterial.ambient * gl_Color) +
-                 (diff * gl_FrontMaterial.diffuse * gl_Color) +
-                 (spec * gl_FrontMaterial.specular);
-    } else {
-      bool dummy;
-      DirectionalLight(-normal, gl_BackMaterial.shininess, amb, diff, spec, dummy);
-
-      color = gl_BackLightModelProduct.sceneColor  +
-              (amb  * gl_BackMaterial.ambient * gl_Color) +
-              (diff * gl_BackMaterial.diffuse * gl_Color) +
-              (spec * gl_BackMaterial.specular);
-
-    }
-    
-    gl_FragColor = color;
-
-  } else {
-    gl_FragColor = gl_Color;
-  }
-
-  float fog = fog_flag ? clamp((gl_Fog.end-gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0) : 1.0;
-  if(shadow_flag) {
-    vec4 coord = gl_TexCoord[1]/gl_TexCoord[1].w;
-    float sum = 0.0;
-    if(lflag) {
-      sum += 0.18*CalcShadowFactor(coord, vec2(-0.7, -0.7));
-      sum += 0.18*CalcShadowFactor(coord, vec2(0.7, -0.7));
-      sum += 0.18*CalcShadowFactor(coord, vec2(0.7, 0.7));
-      sum += 0.18*CalcShadowFactor(coord, vec2(-0.7, 0.7));
-      sum += 0.28*CalcShadowFactor(coord, vec2(0, 0));
-    } else {
-      sum = shadow_multiplier;
-    }
-
-    gl_FragColor = vec4(sum*mix(gl_Fog.color.rgb, gl_FragColor.rgb, fog),gl_FragColor.a);
-  } else {
-    gl_FragColor.rgb = mix(gl_Fog.color.rgb, gl_FragColor.rgb, fog);
-    gl_FragColor.a = gl_Color.a;
-  }
-}
diff --git a/modules/gfx/src/shader/fraglight_lfs_vs.glsl b/modules/gfx/src/shader/fraglight_vs.glsl
similarity index 66%
rename from modules/gfx/src/shader/fraglight_lfs_vs.glsl
rename to modules/gfx/src/shader/fraglight_vs.glsl
index 7052797e33abc2ce78b547e54a762d52bd0d9aa4..279016e1443fe061d0636f897d5d8b07829e5a9a 100644
--- a/modules/gfx/src/shader/fraglight_lfs_vs.glsl
+++ b/modules/gfx/src/shader/fraglight_vs.glsl
@@ -7,13 +7,14 @@ void main()
   // for some reason, the fog and z coordinate are sign toggled...
   gl_FogFragCoord = -ec_Pos.z;
 
-  vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
   // since a directional light is used, the position is not needed
-  gl_TexCoord[0].stp=normal;
+  // and only the normal is passed on
+  gl_TexCoord[2].stp=normalize(gl_NormalMatrix * gl_Normal);
 
-  // shadow map projection coords
-  gl_TexCoord[1] = gl_TextureMatrix[0] * gl_Vertex;
+  // default tex coord
+  gl_TexCoord[0] = gl_MultiTexCoord0;
 
   gl_FrontColor=gl_Color;
   gl_BackColor=gl_Color;
 }
+
diff --git a/modules/gfx/src/shader/quadpp_vs.glsl b/modules/gfx/src/shader/quadpp_vs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..043c65d69b2d1a4f96d705cc84d12ba9b847d592
--- /dev/null
+++ b/modules/gfx/src/shader/quadpp_vs.glsl
@@ -0,0 +1,6 @@
+void main()
+{    
+  gl_Position = ftransform();
+  gl_TexCoord[0] = gl_MultiTexCoord0;
+}
+
diff --git a/modules/gfx/src/shader/scenefx_fs.glsl b/modules/gfx/src/shader/scenefx_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..cb5c2313c77dced05f81fdd4854704ebbb4b9a6c
--- /dev/null
+++ b/modules/gfx/src/shader/scenefx_fs.glsl
@@ -0,0 +1,60 @@
+uniform sampler2D scene_map;
+uniform sampler2D depth_map;
+uniform vec2 i_vp;
+uniform bool shadow_flag;
+uniform sampler2D shadow_map;
+uniform float shadow_weight;
+uniform float shadow_depth_bias;
+uniform float shadow_epsilon;
+uniform float shadow_multiplier;
+uniform bool occl_flag;
+uniform sampler2D occl_map;
+uniform float occl_mult;
+uniform bool dark_flag;
+uniform sampler2D dark_map;
+uniform float dark_mult;
+
+// gl_TexCoord[0] comes from scenefx_vs, i.e. from post processing
+
+float CalcShadowFactor(in vec4 coord, in vec2 o)
+{
+  // get original depth value of line projected towards light
+  float d = texture2D(shadow_map, coord.xy+o*shadow_epsilon).x+shadow_depth_bias;
+  return d<=coord.z ? shadow_multiplier : 1.0;
+}
+
+void main()
+{
+  float depth = texture2D(depth_map,gl_TexCoord[0].xy).r;
+  if(depth>=1.0) {
+    discard;
+  }
+  vec4 scene_color=texture2D(scene_map,gl_TexCoord[0].xy);
+  gl_FragColor.a = scene_color.a;
+
+  float shadow_factor=1.0;
+  if(shadow_flag) {
+    vec4 pcoord = vec4(gl_TexCoord[0].xy*2.0-1.0,depth*2.0-1.0,1.0);
+    vec4 coord = gl_TextureMatrix[2]*pcoord;
+    coord/=coord.w;
+    shadow_factor = 0.0;
+    shadow_factor += 0.18*CalcShadowFactor(coord, vec2(-0.7, -0.7));
+    shadow_factor += 0.18*CalcShadowFactor(coord, vec2(0.7, -0.7));
+    shadow_factor += 0.18*CalcShadowFactor(coord, vec2(0.7, 0.7));
+    shadow_factor += 0.18*CalcShadowFactor(coord, vec2(-0.7, 0.7));
+    shadow_factor += 0.28*CalcShadowFactor(coord, vec2(0, 0));
+    shadow_factor = mix(1.0, shadow_factor, shadow_weight);
+  }
+
+  float occl_factor=1.0;
+  if(occl_flag) {
+    occl_factor=max(0.0,1.0-occl_mult*texture2D(occl_map,gl_TexCoord[0].xy).r);
+  }
+
+  float dark_factor=1.0;
+  if(dark_flag) {
+    dark_factor=max(0.0,1.0-dark_mult*(1.0-texture2D(dark_map,gl_TexCoord[0].xy).r));
+  }
+    
+  gl_FragColor.rgb = shadow_factor*occl_factor*dark_factor*scene_color.rgb;
+}
diff --git a/modules/gfx/src/shader/scenefx_vs.glsl b/modules/gfx/src/shader/scenefx_vs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..043c65d69b2d1a4f96d705cc84d12ba9b847d592
--- /dev/null
+++ b/modules/gfx/src/shader/scenefx_vs.glsl
@@ -0,0 +1,6 @@
+void main()
+{    
+  gl_Position = ftransform();
+  gl_TexCoord[0] = gl_MultiTexCoord0;
+}
+
diff --git a/modules/gfx/src/shader/screenblur4_fs.glsl b/modules/gfx/src/shader/screenblur4_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..9bf2df9e28f57c54a0c49d9e8e48396f38aaad16
--- /dev/null
+++ b/modules/gfx/src/shader/screenblur4_fs.glsl
@@ -0,0 +1,33 @@
+uniform sampler2D scene_map;
+uniform sampler2D depth_map;
+uniform vec2 i_vp;
+uniform float depth_cutoff;
+
+void main()
+{
+  // reference depth
+  float depth = texture2D(depth_map,gl_TexCoord[0].xy).r;
+
+  vec4 scene_color=vec4(0.0,0.0,0.0,0.0);
+
+  int count=0;
+  for(float x=-1.5;x<1.51;x+=1.0) {
+    for(float y=-1.5;y<1.51;y+=1.0) {
+      vec2 p = gl_TexCoord[0].xy+vec2(x*i_vp[0],y*i_vp[1]);
+      float dd = abs(depth-texture2D(depth_map,p).r);
+      if(dd<depth_cutoff) {
+        ++count;
+        scene_color+=texture2D(scene_map,p);
+      }
+    }
+  }
+
+  if (count==0) {
+    scene_color=texture2D(scene_map,gl_TexCoord[0].xy);
+  } else {
+    scene_color/=float(count);
+  }
+
+  gl_FragColor=scene_color;
+
+}
\ No newline at end of file
diff --git a/modules/gfx/src/shader/test_tex_fs.glsl b/modules/gfx/src/shader/test_tex_fs.glsl
new file mode 100644
index 0000000000000000000000000000000000000000..bfa84270d2ebd3a5ca9b35740c01a8fce32c7ea5
--- /dev/null
+++ b/modules/gfx/src/shader/test_tex_fs.glsl
@@ -0,0 +1,6 @@
+void main()
+{
+  gl_FragColor.rg=fract(gl_TexCoord[0].st);
+  gl_FragColor.b=1.0;
+  gl_FragColor.a=1.0;
+}
diff --git a/modules/gfx/src/shader/toon2_fs.glsl b/modules/gfx/src/shader/toon2_fs.glsl
index 7d5dc45f0bc0bfbef1bf0bb99cb790db315ab1ab..ae12978378d24389a124313e3c6b70120ea81061 100644
--- a/modules/gfx/src/shader/toon2_fs.glsl
+++ b/modules/gfx/src/shader/toon2_fs.glsl
@@ -33,7 +33,7 @@ void main()
   vec4 diff = vec4(0.0);
   vec4 spec = vec4(0.0);
   vec4 color = vec4(0.0);
-  vec3 normal = normalize(gl_TexCoord[0].stp);
+  vec3 normal = normalize(gl_TexCoord[2].stp);
 
   DirectionalLight(normal, gl_FrontMaterial.shininess, amb, diff, spec);
 
diff --git a/modules/gfx/src/shader/toon_fs.glsl b/modules/gfx/src/shader/toon_fs.glsl
index 06c17f7870e26275efc7e342beea90419bc3334e..4298ec02a44ff781e8dd87604a0d993403676d4e 100644
--- a/modules/gfx/src/shader/toon_fs.glsl
+++ b/modules/gfx/src/shader/toon_fs.glsl
@@ -25,7 +25,7 @@ void main()
   vec4 amb = vec4(0.0);
   vec4 diff = vec4(0.0);
   vec4 color = vec4(0.0);
-  vec3 normal = normalize(gl_TexCoord[0].stp);
+  vec3 normal = normalize(gl_TexCoord[2].stp);
 
   DirectionalLight(normal, amb, diff);
 
diff --git a/modules/gfx/src/shader/toon_vs.glsl b/modules/gfx/src/shader/toon_vs.glsl
index 1913f445eaf04f43bdce4d9e9dea6a4021777e8c..c4624ebd72fa4899fd56e4acac138d6dcc70c2bc 100644
--- a/modules/gfx/src/shader/toon_vs.glsl
+++ b/modules/gfx/src/shader/toon_vs.glsl
@@ -7,9 +7,12 @@ void main()
   // for some reason, the fog and z coordinate are sign toggled...
   gl_FogFragCoord = -ec_Pos.z;
 
-  vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
+  vec3 normal = vec3(0,0,1);
+  if(dot(gl_Normal,gl_Normal)>0.001) {
+    normal = normalize(gl_NormalMatrix * gl_Normal);
+  }
   // since a directional light is used, the position is not needed
-  gl_TexCoord[0].stp=normal;
+  gl_TexCoord[2].stp=normal;
 
   gl_FrontColor=gl_Color;
   gl_BackColor=gl_Color;
diff --git a/modules/gfx/src/surface.cc b/modules/gfx/src/surface.cc
index 00ee954a959809f860c2f17cb70bc705df6dc6b8..1f4b79161532e331dda66b5cc5ddb1d48b93593c 100644
--- a/modules/gfx/src/surface.cc
+++ b/modules/gfx/src/surface.cc
@@ -23,7 +23,6 @@
 #include <map>
 #include <limits>
 
-#include <ost/mol/atom_prop.hh>
 #include <ost/mol/mol.hh>
 #include <ost/mol/entity_property_mapper.hh>
 #include "surface.hh"
@@ -43,14 +42,18 @@ Surface::Surface(const String& name, const mol::SurfaceHandle& sh):
   recalc_bb_(true)
 {
   // TODO replace with def mat for this gfx obj type
-  SetMat(0.0,1.0,0.2,48.0);
+  SetMatAmb(Color(0,0,0));
+  SetMatDiff(Color(1,1,1));
+  SetMatSpec(Color(0.2,0.2,0.2));
+  SetMatShin(48);
   Rebuild();
 }
 
 void Surface::CustomRenderGL(RenderPass pass)
 {
-  if(pass>0) return;
-  va_.RenderGL();
+  if(pass==STANDARD_RENDER_PASS) {
+    va_.RenderGL();
+  }
 }
 
 void Surface::CustomRenderPov(PovState& pov)
@@ -164,10 +167,11 @@ geom::AlignedCuboid Surface::GetBoundingBox() const
 
 void Surface::CustomPreRenderGL(bool flag)
 {
+  va_.FlagRefresh();
   if(flag) {
     //Rebuild();
   } else {
-    RefreshVA(va_);
+    //RefreshVA(va_);
   }
 }
 
@@ -244,28 +248,30 @@ void Surface::ColorBy(const String& prop,
 
 void Surface::Apply(const gfx::UniformColorOp& op, bool store){
   if(store){
-	UniformColorOp* op_ptr = new UniformColorOp(op);
+    UniformColorOp* op_ptr = new UniformColorOp(op);
     this->AppendColorOp(op_ptr);
   }
   mol::Query q(op.GetSelection());
   gfx::Color col = op.GetColor();
   if(op.GetSelection()=="") {
-	for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-	  va_.SetColor(it->second,col);
-	}
+    for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
+      va_.SetColor(it->second,col);
+    }
   } else {
-	for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-	  mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
-	  if(ah.IsValid()) {
-		if(q.IsAtomSelected(ah)) {
-		  va_.SetColor(it->second,col);
-		}
-	  }
-	}
+    for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
+      mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
+      if(ah.IsValid()) {
+        if(q.IsAtomSelected(ah)) {
+          va_.SetColor(it->second,col);
+        }
+      }
+    }
   }
   FlagRefresh();
 }
-void Surface::Apply(const gfx::BasicGradientColorOp& op, bool store){
+
+void Surface::Apply(const gfx::BasicGradientColorOp& op, bool store)
+{
   if(store){
     BasicGradientColorOp* op_ptr = new BasicGradientColorOp(op);
     this->AppendColorOp(op_ptr);
@@ -279,23 +285,24 @@ void Surface::Apply(const gfx::BasicGradientColorOp& op, bool store){
   mol::EntityPropertyMapper epm(prop, level);
   std::vector<std::pair<VertexID,float> > v2v;
   for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-	mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
-	if(ah.IsValid()) {
-	  float v = epm.Get(ah);
-	  v2v.push_back(std::make_pair(it->second,v));
-	  minv=std::min(minv,v);
-	  maxv=std::max(maxv,v);
-	}
+    mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
+    if(ah.IsValid()) {
+      float v = epm.Get(ah);
+      v2v.push_back(std::make_pair(it->second,v));
+      minv=std::min(minv,v);
+      maxv=std::max(maxv,v);
+    }
   }
-
+  
   // reuse values for speed optimization
   for(std::vector<std::pair<VertexID,float> >::const_iterator it=v2v.begin();it!=v2v.end();++it) {
-	va_.SetColor(it->first,gradient.GetColorAt(normalize(it->second,minv,maxv)));
+    va_.SetColor(it->first,gradient.GetColorAt(normalize(it->second,minv,maxv)));
   }
   FlagRefresh();
 }
 
-void Surface::Apply(const gfx::GradientLevelColorOp& op, bool store){
+void Surface::Apply(const gfx::GradientLevelColorOp& op, bool store)
+{
   if(store){
     GradientLevelColorOp* op_ptr = new GradientLevelColorOp(op);
     this->AppendColorOp(op_ptr);
@@ -309,16 +316,16 @@ void Surface::Apply(const gfx::GradientLevelColorOp& op, bool store){
   // for the attached atoms
   mol::EntityPropertyMapper epm(prop, level);
   for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-	mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
-	if(ah.IsValid()) {
-	  va_.SetColor(it->second,gradient.GetColorAt(normalize(epm.Get(ah, minv),
-	                                              minv,maxv)));
-	}
+    mol::AtomHandle ah = sh_.GetVertex(it->first).atom;
+    if(ah.IsValid()) {
+      va_.SetColor(it->second,gradient.GetColorAt(normalize(epm.Get(ah,minv),minv,maxv)));
+    }
   }
   FlagRefresh();
 }
 
-void Surface::Apply(const gfx::EntityViewColorOp& op, bool store){
+void Surface::Apply(const gfx::EntityViewColorOp& op, bool store)
+{
   if(store){
     EntityViewColorOp* op_ptr = new EntityViewColorOp(op);
     this->AppendColorOp(op_ptr);
@@ -329,14 +336,15 @@ void Surface::Apply(const gfx::EntityViewColorOp& op, bool store){
   float minv = op.GetMinV();
   float maxv = op.GetMaxV();
   for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-  va_.SetColor(it->second,impl::MappedProperty(ev,prop,g,minv,maxv,
-                                               sh_.GetVertex(it->first).position));
+    va_.SetColor(it->second,impl::MappedProperty(ev,prop,g,minv,maxv,
+                                                 sh_.GetVertex(it->first).position));
   }
   FlagRefresh();
 }
-
+  
 #if OST_IMG_ENABLED
-void Surface::Apply(const gfx::MapHandleColorOp& op, bool store){
+void Surface::Apply(const gfx::MapHandleColorOp& op, bool store)
+{
   if(store){
     MapHandleColorOp* op_ptr = new MapHandleColorOp(op);
     this->AppendColorOp(op_ptr);
@@ -347,17 +355,19 @@ void Surface::Apply(const gfx::MapHandleColorOp& op, bool store){
   float minv = op.GetMinV();
   float maxv = op.GetMaxV();
   for(VMap::const_iterator it=vmap_.begin();it!=vmap_.end();++it) {
-	va_.SetColor(it->second,impl::MappedProperty(mh,prop,g,minv,maxv,sh_.GetVertex(it->first).position));
+    va_.SetColor(it->second,impl::MappedProperty(mh,prop,g,minv,maxv,sh_.GetVertex(it->first).position));
   }
   FlagRefresh();
 }
 #endif //OST_IMG_ENABLED
 
-void Surface::CleanColorOps(){
+void Surface::CleanColorOps()
+{
   GfxObj::CleanColorOps();
 }
 
-void Surface::ReapplyColorOps(){
+void Surface::ReapplyColorOps()
+{
   GfxObj::ReapplyColorOps();
 }
 
diff --git a/modules/gfx/src/texture.cc b/modules/gfx/src/texture.cc
new file mode 100644
index 0000000000000000000000000000000000000000..56ea7555360c05de3d4b2d0e36c5c446275f62b4
--- /dev/null
+++ b/modules/gfx/src/texture.cc
@@ -0,0 +1,41 @@
+#include "texture.hh"
+
+namespace ost { namespace gfx {
+
+  Texture::Texture(const Bitmap& bm):
+    w_(bm.width), h_(bm.height),
+    d_()
+  {
+    if(!bm.data) return;
+    d_=boost::shared_array<Color>(new Color[w_*h_]);
+    static float f=1.0/255.0;
+    for(GLint v=0;v<h_;++v) {
+      for(GLint u=0;u<w_;++u) {
+        int p=v*w_+u;
+        Color& c = d_[p];
+        if(bm.channels==1) {
+          c[0]=f*static_cast<float>(bm.data[p]);
+          c[1]=c[0];
+          c[2]=c[0];
+          c[3]=1.0;
+        } else if(bm.channels==2) {
+          c[0]=f*static_cast<float>(bm.data[p*2+0]);
+          c[1]=c[0];
+          c[2]=c[0];
+          c[3]=f*static_cast<float>(bm.data[p*2+1]);
+        } else if(bm.channels==3) {
+          c[0]=f*static_cast<float>(bm.data[p*3+0]);
+          c[1]=f*static_cast<float>(bm.data[p*3+1]);
+          c[2]=f*static_cast<float>(bm.data[p*3+2]);
+          c[3]=1.0;
+        } else if(bm.channels==4) {
+          c[0]=f*static_cast<float>(bm.data[p*4+0]);
+          c[1]=f*static_cast<float>(bm.data[p*4+1]);
+          c[2]=f*static_cast<float>(bm.data[p*4+2]);
+          c[2]=f*static_cast<float>(bm.data[p*4+3]);
+        }
+      }
+    }
+  }
+
+}}
diff --git a/modules/gfx/src/impl/calc_ambient.hh b/modules/gfx/src/texture.hh
similarity index 57%
rename from modules/gfx/src/impl/calc_ambient.hh
rename to modules/gfx/src/texture.hh
index 6064f84c9aabf4344734254461e91a2b67683788..471bdfd7175c307770da9340ec9ca5c5dedf1062 100644
--- a/modules/gfx/src/impl/calc_ambient.hh
+++ b/modules/gfx/src/texture.hh
@@ -16,20 +16,59 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
-#ifndef OST_CALC_AMBIENT_HH
-#define OST_CALC_AMBIENT_HH
+#ifndef OST_GFX_TEXTURE_HH
+#define OST_GFX_TEXTURE_HH
 
 /*
-  calculate ambient contributions per VA entry
+  texture
 
   Author: Ansgar Philippsen
 */
 
+#include <boost/shared_array.hpp>
+
+#include "module_config.hh"
+#include "glext_include.hh"
+#include "color.hh"
+#include "bitmap_io.hh"
+
 namespace ost { namespace gfx {
 
-    class IndexedVertexArray;
-    void CalcAmbientTerms(IndexedVertexArray& va);
-      
+class Texture
+{
+public:
+  Texture():
+    w_(0),
+    h_(0),
+    d_()
+  {}
+
+  Texture(GLint w, GLint h):
+    w_(w),
+    h_(h),
+    d_(new Color[w*h])
+  {}
+
+  Texture(const Bitmap& b);
+
+  bool IsValid() const {return d_;}
+
+  Color& operator()(uint u, uint v) {return d_[v*w_+u];}
+  const Color& operator()(uint u, uint v) const {return d_[v*w_+u];}
+
+  float* data() {return d_[0];}
+  
+  GLint width() const {return w_;}
+  GLint height() const {return h_;}
+  GLint format() const {return GL_RGBA;}
+  GLint type() const {return GL_FLOAT;}
+  GLint border() const {return 0;}
+
+private:
+  GLint w_,h_;
+  boost::shared_array<Color> d_;
+};
+
 }} // ns
 
 #endif
diff --git a/modules/gfx/src/vertex_array.cc b/modules/gfx/src/vertex_array.cc
index 484d153a7f4fb112ef2225f5a092b15ec7cda740..da22a32727df37eb87cd2311263efdf486f504ca 100644
--- a/modules/gfx/src/vertex_array.cc
+++ b/modules/gfx/src/vertex_array.cc
@@ -31,8 +31,6 @@
 #include "vertex_array_helper.hh"
 #include "povray.hh"
 
-#include "impl/calc_ambient.hh"
-
 #if OST_SHADER_SUPPORT_ENABLED
 #include "shader.hh"
 #endif
@@ -64,20 +62,23 @@ IndexedVertexArray::Entry::Entry()
   v[0]=0.0; v[1]=0.0; v[2]=0.0;
   n[0]=0.0; n[1]=0.0; n[2]=1.0;
   c[0]=0.0; c[1]=0.0; c[2]=0.0; c[3]=0.0;
+  t[0]=0.0; t[1]=0.0;
 }
 
-IndexedVertexArray::Entry::Entry(const Vec3& vv, const Vec3& nn, const Color& cc)
+  IndexedVertexArray::Entry::Entry(const Vec3& vv, const Vec3& nn, const Color& cc, const geom::Vec2& tt)
 {
   v[0]=vv[0]; v[1]=vv[1]; v[2]=vv[2];
   n[0]=nn[0]; n[1]=nn[1]; n[2]=nn[2];
   c[0]=cc[0]; c[1]=cc[1]; c[2]=cc[2]; c[3]=cc[3];
+  t[0]=tt[0]; t[1]=tt[1];
 }
 
 
 IndexedVertexArray::IndexedVertexArray()
 {
   initialized_=false;
-  Clear(); // replaces ctor initialization list
+  Reset(); // replaces ctor initialization list
+  glGenTextures(1,&tex_id_);
 }
 
 IndexedVertexArray::~IndexedVertexArray()
@@ -87,24 +88,27 @@ IndexedVertexArray::~IndexedVertexArray()
 IndexedVertexArray::IndexedVertexArray(const IndexedVertexArray& va)
 {
   copy(va);
+  glGenTextures(1,&tex_id_);
 }
 
 IndexedVertexArray& IndexedVertexArray::operator=(const IndexedVertexArray& va)
 {
   copy(va);
+  // keep already allocated tex id
   return *this;
 }
 
 unsigned int IndexedVertexArray::GetFormat()
 {
   // hardcoded for now, may be refactored and moved into an impl
-  return GL_C4F_N3F_V3F;
+  return GL_T2F_C4F_N3F_V3F;
 }
 
 
 void IndexedVertexArray::Cleanup() 
 {
   if(initialized_) {
+    glDeleteTextures(1,&tex_id_);
     glDeleteLists(outline_mat_dlist_,1);
 #if OST_SHADER_SUPPORT_ENABLED
     glDeleteBuffers(7,buffer_id_);
@@ -139,11 +143,11 @@ void IndexedVertexArray::SetOutlineExpandColor(const Color& c) {outline_exp_colo
 
 VertexID IndexedVertexArray::Add(const Vec3& vert, 
                                  const Vec3& norm,
-                                 const Color& col) 
+                                 const Color& col,
+                                 const Vec2& texc) 
 {
   dirty_=true;
-  ambient_dirty_=true;
-  entry_list_.push_back(Entry(vert,norm,col));
+  entry_list_.push_back(Entry(vert,norm,col,texc));
   return entry_list_.size()-1;
 }
 
@@ -163,7 +167,6 @@ LineID IndexedVertexArray::AddLine(VertexID id0, VertexID id1)
 {
   assert(id0<entry_list_.size() && id1<entry_list_.size());
   dirty_=true;
-  ambient_dirty_=true;
   line_index_list_.push_back(id0);
   line_index_list_.push_back(id1);
   return line_index_list_.size()-2;
@@ -173,7 +176,6 @@ TriID IndexedVertexArray::AddTri(VertexID id0, VertexID id1, VertexID id2)
 {
   assert(id0<entry_list_.size() && id1<entry_list_.size() && id2<entry_list_.size());
   dirty_=true;
-  ambient_dirty_=true;
   tri_index_list_.push_back(id0);
   tri_index_list_.push_back(id1);
   tri_index_list_.push_back(id2);
@@ -203,7 +205,6 @@ QuadID IndexedVertexArray::AddQuad(VertexID id0, VertexID id1, VertexID id2, Ver
 {
   assert(id0<entry_list_.size() && id1<entry_list_.size() && id2<entry_list_.size() && id3<entry_list_.size());
   dirty_=true;
-  ambient_dirty_=true;
   quad_index_list_.push_back(id0);
   quad_index_list_.push_back(id1);
   quad_index_list_.push_back(id2);
@@ -214,7 +215,6 @@ QuadID IndexedVertexArray::AddQuad(VertexID id0, VertexID id1, VertexID id2, Ver
 void IndexedVertexArray::AddSphere(const SpherePrim& prim, unsigned int detail) 
 {
   dirty_=true;
-  ambient_dirty_=true;
 
   unsigned int level= std::min(VA_SPHERE_MAX_DETAIL,detail);
 
@@ -235,7 +235,6 @@ void IndexedVertexArray::AddSphere(const SpherePrim& prim, unsigned int detail)
 void IndexedVertexArray::AddIcoSphere(const SpherePrim& prim, unsigned int detail) 
 {
   dirty_=true;
-  ambient_dirty_=true;
   
   unsigned int level= std::min(VA_ICO_SPHERE_MAX_DETAIL,detail);
   
@@ -249,43 +248,63 @@ void IndexedVertexArray::AddIcoSphere(const SpherePrim& prim, unsigned int detai
   }
 }
 
-void IndexedVertexArray::AddCylinder(const CylinderPrim& prim, unsigned int detail)
+void IndexedVertexArray::AddCylinder(const CylinderPrim& prim, unsigned int detail,bool cap)
 {
   dirty_=true;
-  ambient_dirty_=true;
   
   unsigned int level = std::min(VA_CYL_MAX_DETAIL,detail);
   
   const std::vector<Vec3>& vlist = detail::GetPrebuildCyl(level);
   
   Vec3 off(0.0,0.0,prim.length);
+
+  Vec3 cn0 = cap ? prim.rotmat* geom::Vec3(0.0,0.0,-1.0) : Vec3();
+  Vec3 cn1 = -cn0;
+  VertexID cid0 = cap ? Add(prim.start, cn0 , prim.color1) : 0;
+  VertexID cid7 = cap ? Add(prim.rotmat * off + prim.start, cn1, prim.color2) : 0;
   
   // prepare first vertices to add
   std::vector<Vec3>::const_iterator it=vlist.begin();
   Vec3 v0 = (*it);
   Vec3 n0 = prim.rotmat * v0; 
   v0*=prim.radius;
-  VertexID id1 = Add(prim.rotmat * v0 + prim.start, n0, prim.color);
-  VertexID id2 = Add(prim.rotmat * (v0+off) + prim.start, n0, prim.color);
+  VertexID id1 = Add(prim.rotmat * v0 + prim.start, n0, prim.color1);
+  VertexID id2 = Add(prim.rotmat * (v0+off) + prim.start, n0, prim.color2);
+  VertexID cid1 = cap ? Add(prim.rotmat * v0 + prim.start, cn0, prim.color1) : 0;
+  VertexID cid2 = cap ? Add(prim.rotmat * (v0+off) + prim.start, cn1, prim.color2) : 0;
   
   // now for the loop around the circle
   VertexID id3=id1;
   VertexID id4=id2;
+  VertexID cid3=cid1;
+  VertexID cid4=cid2;
   ++it;
   for(;it!=vlist.end();++it) {
     v0 = (*it);
     n0 = prim.rotmat * v0; 
     v0 *= prim.radius;
-    VertexID id5 = Add(prim.rotmat * v0 + prim.start, n0, prim.color);
-    VertexID id6 = Add(prim.rotmat * (v0+off) + prim.start, n0, prim.color);
+    VertexID id5 = Add(prim.rotmat * v0 + prim.start, n0, prim.color1);
+    VertexID id6 = Add(prim.rotmat * (v0+off) + prim.start, n0, prim.color2);
     AddTri(id3,id5,id4);
     AddTri(id5,id6,id4);
+    if(cap) {
+      VertexID cid5 = Add(prim.rotmat * v0 + prim.start, cn0, prim.color1);
+      VertexID cid6 = Add(prim.rotmat * (v0+off) + prim.start, cn1, prim.color2);
+      AddTri(cid0,cid5,cid3);
+      AddTri(cid7,cid4,cid6);
+      cid3=cid5;
+      cid4=cid6;
+    }
     id3=id5;
     id4=id6;
   }
   // and finally close the circle
   AddTri(id3,id1,id4);
   AddTri(id1,id2,id4);
+  if(cap) {
+    AddTri(cid0,cid1,cid3);
+    AddTri(cid7,cid4,cid2);
+  }
 }
 
 Vec3 IndexedVertexArray::GetVert(VertexID id) const
@@ -340,6 +359,33 @@ void IndexedVertexArray::SetColor(VertexID id, const Color& c)
   entry_list_[id].c[3]=c[3];
 }
 
+Vec2 IndexedVertexArray::GetTexCoord(VertexID id) const
+{
+  Vec2 nrvo;
+  if(id>=entry_list_.size()) return nrvo;
+  nrvo = Vec2(entry_list_[id].t);
+  return nrvo;
+} 
+
+void IndexedVertexArray::SetTexCoord(VertexID id, const Vec2& t) 
+{
+  if(id>=entry_list_.size()) return;
+  entry_list_[id].t[0]=t[0];
+  entry_list_[id].t[1]=t[1];
+}
+
+void IndexedVertexArray::SetOpacity(float o)
+{
+  o=std::max(0.0f,std::min(1.0f,o));
+  // this should really just set a value in the shader... 
+  // but we need to support the fixed function pipeline as well
+  for(EntryList::iterator it=entry_list_.begin();it!=entry_list_.end();++it) {
+    it->c[3]=o;
+  }
+  opacity_=o;
+  FlagRefresh();
+}
+
 void IndexedVertexArray::RenderGL() 
 {
   static bool use_buff=false;
@@ -347,7 +393,9 @@ void IndexedVertexArray::RenderGL()
   if(!initialized_) {
     LOG_DEBUG("initializing vertex array lists");
 #if OST_SHADER_SUPPORT_ENABLED
-    glGenBuffers(7,buffer_id_);
+    if(!Scene::Instance().InOffscreenMode()) {
+      glGenBuffers(7,buffer_id_);
+    }
 #endif
     outline_mat_dlist_=glGenLists(1);
     initialized_=true;
@@ -356,11 +404,6 @@ void IndexedVertexArray::RenderGL()
   if(dirty_) {
     dirty_=false;
 #if OST_SHADER_SUPPORT_ENABLED
-    if(ambient_dirty_ && use_ambient_) {
-      LOG_DEBUG("re-calculating ambient occlusion terms");
-      recalc_ambient_occlusion();
-      ambient_dirty_=false;
-    }
 
     LOG_DEBUG("checking buffer object availability");
     if(mode_&0x2 && aalines_flag_) {
@@ -369,6 +412,7 @@ void IndexedVertexArray::RenderGL()
       use_buff=prep_buff();
     }
     if(!use_buff) {
+      LOG_TRACE("buffer not available");
       glBindBuffer(GL_ARRAY_BUFFER,0);
       glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
     } else {
@@ -377,9 +421,8 @@ void IndexedVertexArray::RenderGL()
 #endif
   }
   
-  glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT | GL_COLOR_BUFFER_BIT | GL_LIGHTING_BIT);
+  glPushAttrib(GL_ALL_ATTRIB_BITS);
   glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);
-  glPushMatrix();
 
   if(outline_mode_>0) {
     LOG_TRACE("outline rendering");
@@ -394,7 +437,7 @@ void IndexedVertexArray::RenderGL()
     glCullFace(GL_FRONT);
     glEnable(GL_CULL_FACE);
     glShadeModel(GL_FLAT);
-    if(outline_mode_==1) {
+    if(outline_mode_==2) {
       glCallList(outline_mat_dlist_);
       glEnable(GL_POLYGON_OFFSET_LINE);
       glEnable(GL_POLYGON_OFFSET_POINT);
@@ -404,7 +447,7 @@ void IndexedVertexArray::RenderGL()
       glEnable(GL_LINE_SMOOTH);
       glDisable(GL_POINT_SMOOTH); // kills selfx fragment shader if enabled
       glDisable(GL_POLYGON_SMOOTH);
-    } else if(outline_mode_==2) {
+    } else if(outline_mode_==1) {
       glCallList(outline_mat_dlist_);
       glEnable(GL_POLYGON_OFFSET_LINE);
       glPolygonOffset(10.0,1.0);
@@ -417,7 +460,12 @@ void IndexedVertexArray::RenderGL()
       glDisable(GL_POLYGON_OFFSET_LINE);
       glDisable(GL_POLYGON_OFFSET_POINT);
       glDisable(GL_LINE_SMOOTH);
-      glDisable(GL_BLEND);
+      if(opacity_<1.0) {
+        glEnable(GL_BLEND);
+        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+      } else {
+        glDisable(GL_BLEND);
+      }
     }
   } else {
     // not in outline mode
@@ -431,21 +479,16 @@ void IndexedVertexArray::RenderGL()
     } else {
       glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
     }
-    if(color_mat_) {
-      glEnable(GL_COLOR_MATERIAL); 
-    } else {
-      glDisable(GL_COLOR_MATERIAL);
-    }
     if(cull_face_) {
       glEnable(GL_CULL_FACE);
     } else { 
       glDisable(GL_CULL_FACE); 
     }
-#if OST_SHADER_SUPPORT_ENABLED
-    if(use_ambient_ && !ambient_data_.empty()) {
-      glUniform1i(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"occlusion_flag"),1);
-    }
-#endif
+  }
+  if(color_mat_) {
+    glEnable(GL_COLOR_MATERIAL); 
+  } else {
+    glDisable(GL_COLOR_MATERIAL);
   }
   
   if(mode_&0x1) {
@@ -479,7 +522,7 @@ void IndexedVertexArray::RenderGL()
       glUniform1f(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"scalef"),outline_exp_factor_);
       glUniform4f(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"color"),
                   outline_exp_color_[0],outline_exp_color_[1],
-                  outline_exp_color_[2],outline_exp_color_[3]);
+                  outline_exp_color_[2],opacity_);
       glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
       draw_ltq(use_buff);
 
@@ -511,12 +554,6 @@ void IndexedVertexArray::RenderGL()
     }
   }
 
-#if OST_SHADER_SUPPORT_ENABLED
-  if(use_ambient_) {
-    glUniform1i(glGetUniformLocation(Shader::Instance().GetCurrentProgram(),"occlusion_flag"),0);
-  }
-#endif
-
   if(draw_normals_) {
     //glColor3f(1,0,0);
     glBegin(GL_LINES);
@@ -531,7 +568,6 @@ void IndexedVertexArray::RenderGL()
     glEnd();
   }
 
-  glPopMatrix();
   glPopClientAttrib();
   glPopAttrib();
 }
@@ -539,13 +575,16 @@ void IndexedVertexArray::RenderGL()
 namespace {
   unsigned int col_to_index(float* c)
   {
-    return static_cast<unsigned int>(c[0]*7.0)*64+static_cast<unsigned int>(c[1]*7.0)*8+static_cast<unsigned int>(c[2]*7.0);
+    // don't look too closely - I am lacking sufficient caffeine to do this more elegantly
+    int ret= std::max(0,std::min<int>(511,static_cast<int>(round(c[0]*7.0f))*64+static_cast<int>(round(c[1]*7.0f))*8+static_cast<unsigned int>(round(c[2]*7.0f))));
+    return static_cast<unsigned int>(ret);
   }
 }
 
 void IndexedVertexArray::RenderPov(PovState& pov, const std::string& name)
 {
   if(entry_list_.empty()) return;
+
   pov.inc() << "mesh2 {\n";
 
   pov.inc() << " vertex_vectors { " << entry_list_.size() << ",\n";
@@ -607,15 +646,19 @@ void IndexedVertexArray::RenderPov(PovState& pov, const std::string& name)
   pov.inc() << "}\n";
 }
 
-void IndexedVertexArray::Clear() 
+void IndexedVertexArray::Clear()
 {
   dirty_=true;
-  ambient_dirty_=true;
   entry_list_.clear();
   quad_index_list_.clear();
   tri_index_list_.clear();
   line_index_list_.clear();
   ntentry_list_.clear();
+} 
+
+void IndexedVertexArray::Reset() 
+{
+  Clear();
   mode_=0x4;
   poly_mode_=2;
   lighting_=true;
@@ -626,6 +669,7 @@ void IndexedVertexArray::Clear()
   aalines_flag_=false;
   point_size_=2.0;
   line_halo_=0.0;
+  opacity_=1.0;
   outline_mode_=0;
   outline_width_=4.0;
   outline_mat_=Material(0.3,1.0,0.0,0.0,0.0);
@@ -633,8 +677,7 @@ void IndexedVertexArray::Clear()
   outline_exp_factor_=0.1;
   outline_exp_color_=Color(0,0,0);
   draw_normals_=false;
-  use_ambient_=false;
-  ambient_data_.clear();
+  use_tex_=true;
 }
 
 void IndexedVertexArray::FlagRefresh()
@@ -907,36 +950,6 @@ void IndexedVertexArray::SmoothVertices(float smoothf)
   }
 }
 
-void IndexedVertexArray::UseAmbient(bool f)
-{
-  if(use_ambient_==f) return;
-  use_ambient_=f;
-  FlagRefresh();
-}
-
-Color IndexedVertexArray::GetAmbientColor(VertexID id) const
-{
-  Color nrvo;
-  if(id*4>=ambient_data_.size()) return nrvo;
-  unsigned int offset=id*4;
-  nrvo = Color(ambient_data_[offset+0],
-               ambient_data_[offset+1],
-               ambient_data_[offset+2],
-               ambient_data_[offset+3]);
-  return nrvo;
-} 
-
-void IndexedVertexArray::SetAmbientColor(VertexID id, const Color& c) 
-{
-  if(id*4>=ambient_data_.size()) return;
-  unsigned int offset=id*4;
-  ambient_data_[offset+0]=c[0];
-  ambient_data_[offset+1]=c[1];
-  ambient_data_[offset+2]=c[2];
-  ambient_data_[offset+3]=c[3];
-}
-
-
 namespace {
 
 uint npatch_tab_id(uint u, uint v, uint N)
@@ -954,7 +967,7 @@ void IndexedVertexArray::NPatch()
   IndexList tri_index_list;
   IndexList line_index_list;
 
-  entry_list.push_back(Entry(Vec3(),Vec3(),Color(1,0,0)));
+  entry_list.push_back(Entry(Vec3(),Vec3(),Color(1,0,0),Vec2()));
 
   for(uint c=0;c<tri_index_list_.size();) {
     VertexID id0 = tri_index_list_[c++];
@@ -992,7 +1005,8 @@ void IndexedVertexArray::NPatch()
           3.0*(u*u*v*p210+u*u*w*p201+u*v*v*p120+v*v*w*p021+v*w*w*p012+u*w*w*p102)+
           6.0*u*v*w*p111;
         Vec3 n = Normalize(u*u*n200+v*v*n020+w*w*n002+u*v*n110+u*w*n101+v*w*n011);
-        entry_list.push_back(Entry(p,n,Color()));
+        // TODO: patch texture coord as well
+        entry_list.push_back(Entry(p,n,Color(),Vec2()));
         tab[npatch_tab_id(uc,vc,N)] = entry_list.size()-1;
       }
     }
@@ -1042,7 +1056,6 @@ void IndexedVertexArray::copy(const IndexedVertexArray& va)
   line_index_list_=va.line_index_list_;
   ntentry_list_=va.ntentry_list_;
   dirty_=true;
-  ambient_dirty_=va.ambient_dirty_;
   mode_=va.mode_;
   poly_mode_=va.poly_mode_;
   lighting_=va.lighting_;
@@ -1060,12 +1073,12 @@ void IndexedVertexArray::copy(const IndexedVertexArray& va)
   outline_exp_factor_=va.outline_exp_factor_;
   outline_exp_color_=va.outline_exp_color_;
   draw_normals_=va.draw_normals_;
-  use_ambient_=va.use_ambient_;
-  ambient_data_=va.ambient_data_;
+  use_tex_=va.use_tex_;
 }
   
 bool IndexedVertexArray::prep_buff()
 {
+  if(Scene::Instance().InOffscreenMode()) return false;
 #if OST_SHADER_SUPPORT_ENABLED
   glEnableClientState(GL_VERTEX_ARRAY);
   glEnableClientState(GL_NORMAL_ARRAY);
@@ -1130,24 +1143,6 @@ bool IndexedVertexArray::prep_buff()
     VERTEX_ARRAY_CHECK_GL_ERROR("set qindex buf");
   }
 
-  if(use_ambient_) {
-    if(ambient_data_.empty()) {
-      LOG_VERBOSE("ambient data empty");
-      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-    } else {
-      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-      glBindBuffer(GL_ARRAY_BUFFER, buffer_id_[VA_AMBIENT_BUFFER]);
-      VERTEX_ARRAY_CHECK_GL_ERROR("bind ambient buf");
-      glBufferData(GL_ARRAY_BUFFER,
-                   sizeof(float) * ambient_data_.size(),
-                   &ambient_data_[0],
-                   GL_STATIC_DRAW);
-      VERTEX_ARRAY_CHECK_GL_ERROR("set ambient buf");
-    }
-  } else {
-    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-  }
-  
   return true;
 #else
   return false;
@@ -1158,7 +1153,7 @@ void IndexedVertexArray::draw_ltq(bool use_buff)
 {
   if(use_buff && !Scene::Instance().InOffscreenMode()) {
 #if OST_SHADER_SUPPORT_ENABLED
-#if 1
+#if 0
     /*
       for now, since v,n,c live in a packed format (formerly used
       with glInterleavedArrays), only a single buffer is
@@ -1166,20 +1161,17 @@ void IndexedVertexArray::draw_ltq(bool use_buff)
       in place of the absolute pointer
     */
     glBindBuffer(GL_ARRAY_BUFFER, buffer_id_[VA_VERTEX_BUFFER]);
-    glVertexPointer(3, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*7));
-    glNormalPointer(GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*4));
-    glColorPointer(4, GL_FLOAT, sizeof(Entry), 0);
+    glVertexPointer(3, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*9));
+    glNormalPointer(GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*6));
+    glColorPointer(4, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*2));
+    if(use_tex_) {
+      glTexCoordPointer(2, GL_FLOAT, sizeof(Entry), 0);
+    }
 #else
     glBindBuffer(GL_ARRAY_BUFFER, buffer_id_[VA_VERTEX_BUFFER]);
     glInterleavedArrays(GetFormat(),sizeof(Entry),NULL);
 #endif
 
-    if(use_ambient_) {
-      if(!ambient_data_.empty()) {
-        glBindBuffer(GL_ARRAY_BUFFER, buffer_id_[VA_AMBIENT_BUFFER]);
-        glTexCoordPointer(4,GL_FLOAT,0,NULL);
-      }
-    }
     glBindBuffer(GL_ARRAY_BUFFER,0);
 
     if(!tri_index_list_.empty() && (mode_ & 0x4)) {
@@ -1222,9 +1214,12 @@ void IndexedVertexArray::draw_p(bool use_buff)
   if(use_buff && !Scene::Instance().InOffscreenMode()) {
 #if OST_SHADER_SUPPORT_ENABLED
     glBindBuffer(GL_ARRAY_BUFFER, buffer_id_[VA_VERTEX_BUFFER]);
-    glVertexPointer(3, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*7));
-    glNormalPointer(GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*4));
-    glColorPointer(4, GL_FLOAT, sizeof(Entry), 0);
+    glVertexPointer(3, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*9));
+    glNormalPointer(GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*6));
+    glColorPointer(4, GL_FLOAT, sizeof(Entry), reinterpret_cast<void*>(sizeof(float)*2));
+    if(use_tex_) {
+      glTexCoordPointer(2, GL_FLOAT, sizeof(Entry), 0);
+    }
     glDrawArrays(GL_POINTS,0,entry_list_.size());
 #endif
   } else {
@@ -1410,10 +1405,4 @@ void IndexedVertexArray::draw_line_halo(bool use_buff)
   glLineWidth(line_width_);
 }
 
-void IndexedVertexArray::recalc_ambient_occlusion()
-{
-  ambient_data_.resize(4*entry_list_.size());
-  CalcAmbientTerms(*this);
-}
-
 }} // ns
diff --git a/modules/gfx/src/vertex_array.hh b/modules/gfx/src/vertex_array.hh
index eed4d2a7fdc97f4d3f92c3f883ed5caaed50e316..24025194806abd80e7cc4e7b4362678299ed2fe2 100644
--- a/modules/gfx/src/vertex_array.hh
+++ b/modules/gfx/src/vertex_array.hh
@@ -49,7 +49,8 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
  public:
   struct Entry {
     Entry();
-    Entry(const geom::Vec3& vv, const geom::Vec3& nn, const Color& cc);
+    Entry(const geom::Vec3& vv, const geom::Vec3& nn, const Color& cc, const geom::Vec2& tt);
+    float t[2];
     float c[4];
     float n[3];
     float v[3];
@@ -110,8 +111,8 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   void SetOutlineExpandFactor(float f);
   void SetOutlineExpandColor(const Color& c);
 
-  // vertex, normal, and color (C4F_N3F_V3F)
-  VertexID Add(const geom::Vec3& vert, const geom::Vec3& norm, const Color& col);
+  // vertex, normal, color and texcoord (T2F_C4F_N3F_V3F)
+  VertexID Add(const geom::Vec3& vert, const geom::Vec3& norm, const Color& col, const geom::Vec2& tex=geom::Vec2());
 
   unsigned int GetVertexCount() const;
   void DumpVertices() const;
@@ -134,7 +135,7 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   // add an icosahedral based sphere with the given params to the va
   void AddIcoSphere(const SpherePrim& prim, unsigned int detail);
 
-  void AddCylinder(const CylinderPrim& prim, unsigned int detail);
+  void AddCylinder(const CylinderPrim& prim, unsigned int detail,bool cap=false);
 
   geom::Vec3 GetVert(VertexID id) const;
   void SetVert(VertexID id, const geom::Vec3& vert);
@@ -145,19 +146,33 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   Color GetColor(VertexID id) const;
   void SetColor(VertexID id, const Color& col);
 
+  geom::Vec2 GetTexCoord(VertexID id) const;
+  void SetTexCoord(VertexID id, const geom::Vec2& tex);
+
+  void SetOpacity(float o);
+
   // OpenGL rendering call
   void RenderGL();
 
   // POVray export
   void RenderPov(PovState& pov, const std::string& name);
 
-  
+  // only removes the drawing elements
   void Clear();
+  // removes all elements and resets internal state to default
+  void Reset();
+
+  // forces re-calculation of some buffered features
   void FlagRefresh();
 
-  void CalcNormals(float smoothf);
+  // for debugging, draw all normals
   void DrawNormals(bool f);
 
+  // NOTE: all methods below could be delegated to the outside, 
+  // using the GetEntries() and Get*Indices() member functions
+
+  // experimental, do not use
+  void CalcNormals(float smoothf);
   // experimental, do not use
   void CalcFullNormals();
   // experimental, do not use
@@ -166,17 +181,15 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   void NPatch();
   // experimental, do not use
   void SmoothVertices(float smoothf);
-  // experimental, do not use
-  void UseAmbient(bool f);
+
+  void UseTex(bool b) {use_tex_=b;}
+  uint& TexID() {return tex_id_;}
 
   const EntryList& GetEntries() const {return entry_list_;}
   const IndexList& GetQuadIndices() const {return quad_index_list_;}
   const IndexList& GetTriIndices() const {return tri_index_list_;}
   const IndexList& GetLineIndices() const {return line_index_list_;}
 
-  Color GetAmbientColor(VertexID id) const;
-  void SetAmbientColor(VertexID id, const Color& col);
-  
  private:
   bool initialized_;
   
@@ -198,6 +211,7 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   bool aalines_flag_;
   float point_size_;
   float line_halo_;
+  float opacity_;
 
   int outline_mode_;
   float outline_width_;
@@ -209,11 +223,10 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
 
   bool draw_normals_;
 
-  unsigned int buffer_id_[7]; // magic number related to the .cc buffer use
+  bool use_tex_;
+  uint tex_id_;
 
-  bool use_ambient_;
-  bool ambient_dirty_;
-  std::vector<float> ambient_data_;
+  unsigned int buffer_id_[7]; // magic number related to the .cc buffer use
 
   void copy(const IndexedVertexArray& va);
   bool prep_buff();
@@ -221,7 +234,6 @@ class DLLEXPORT_OST_GFX IndexedVertexArray {
   void draw_p(bool use_buff);
   void draw_aalines();
   void draw_line_halo(bool use_buff);
-  void recalc_ambient_occlusion();
 };
 
 }} // ns
diff --git a/modules/gfx/tests/CMakeLists.txt b/modules/gfx/tests/CMakeLists.txt
index eff4ec11fa761b2dab392c8bd06c8e4952c8f249..227b9ff8dc2f15c51408a90e6d58b0768ef86a28 100644
--- a/modules/gfx/tests/CMakeLists.txt
+++ b/modules/gfx/tests/CMakeLists.txt
@@ -1,5 +1,6 @@
 set(OST_GFX_UNIT_TESTS
   tests.cc
+  test_gfx_node.cc
 )
 if (ENABLE_IMG)
   list(APPEND OST_GFX_UNIT_TESTS test_map_octree.cc)
diff --git a/modules/gfx/tests/test_gfx_node.cc b/modules/gfx/tests/test_gfx_node.cc
new file mode 100644
index 0000000000000000000000000000000000000000..8959d3c8957c610ff49b56a4431f43ecba91669c
--- /dev/null
+++ b/modules/gfx/tests/test_gfx_node.cc
@@ -0,0 +1,174 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+
+/*
+  Author: Marco Biasini
+ */
+#include <ost/string_ref.hh>
+#include <ost/platform.hh>
+#include <ost/gfx/gfx_node.hh>
+#include <ost/gfx/gfx_object.hh>
+#include <ost/gfx/scene.hh>
+#define BOOST_TEST_DYN_LINK
+#include <boost/test/unit_test.hpp>
+
+
+using boost::unit_test_framework::test_suite;
+using namespace ost;
+using namespace ost::gfx;
+
+// small RAII class to setup environment for unit tests. even though we don't
+// use any of the rendering functionality, we still need to initialize an 
+// offscreen buffer on mac to avoid segfaults.
+struct GfxTestEnv {
+  GfxTestEnv()
+  {
+    // we know OST_ROOT is set for unit tests
+    SetPrefixPath(getenv("OST_ROOT"));
+    Scene::Instance().StartOffscreenMode(100, 100);
+  }
+  
+  ~GfxTestEnv()
+  {
+    Scene::Instance().StopOffscreenMode();
+  }
+
+};
+
+
+struct Observer : public SceneObserver {
+  Observer(): added_count(0),removed_count(0) {}
+  
+  virtual void NodeAdded(const GfxNodeP& node)
+  {
+    added_count+=1;
+  }
+  
+  virtual void NodeRemoved(const GfxNodeP& node)
+  {
+    removed_count+=1;
+  }
+  
+  int added_count;
+  int removed_count;
+};
+
+BOOST_AUTO_TEST_SUITE(gfx_node)
+
+BOOST_AUTO_TEST_CASE(gfx_node_add) 
+{
+  GfxNodeP n1(new GfxNode("1"));
+  BOOST_CHECK_EQUAL(n1->GetParent(), GfxNodeP());
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  GfxNodeP n2(new GfxNode("2"));
+  n1->Add(n2);
+  BOOST_CHECK_EQUAL(n1->GetParent(), GfxNodeP());
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(1));   
+  BOOST_CHECK_EQUAL(n2->GetParent(), n1);
+  BOOST_CHECK_EQUAL(n2->GetChildCount(), size_t(0));
+  
+  // "move" node 2 from 1 to 3
+  GfxNodeP n3(new GfxNode("3"));
+  n3->Add(n2);
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  BOOST_CHECK_EQUAL(n2->GetParent(), n3);
+  BOOST_CHECK_EQUAL(n3->GetChildCount(), size_t(1));
+}
+
+BOOST_AUTO_TEST_CASE(gfx_node_add_duplicate) 
+{
+  GfxNodeP n1(new GfxNode("1"));
+  GfxNodeP n2(new GfxNode("2"));
+  GfxNodeP n3(new GfxNode("2"));
+  BOOST_CHECK_NO_THROW(n1->Add(n2));
+  BOOST_CHECK_THROW(n1->Add(n3), Error);
+}
+
+BOOST_AUTO_TEST_CASE(gfx_node_remove) 
+{
+  GfxNodeP n1(new GfxNode("1"));
+  BOOST_CHECK_EQUAL(n1->GetParent(), GfxNodeP());
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  GfxNodeP n2(new GfxNode("2"));
+  n1->Add(n2);
+  n1->Remove(n2);
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  BOOST_CHECK_EQUAL(n2->GetParent(), GfxNodeP());
+}
+
+BOOST_AUTO_TEST_CASE(gfx_node_remove_all) 
+{
+  GfxNodeP n1(new GfxNode("1"));
+  BOOST_CHECK_EQUAL(n1->GetParent(), GfxNodeP());
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  GfxNodeP n2(new GfxNode("2"));
+  GfxNodeP n3(new GfxNode("3"));
+  GfxNodeP n4(new GfxNode("4"));
+  n1->Add(n2);
+  n1->Add(n3);
+  n1->Add(n4);
+  n1->RemoveAll();
+  BOOST_CHECK_EQUAL(n1->GetChildCount(), size_t(0));
+  BOOST_CHECK_EQUAL(n2->GetParent(), GfxNodeP());
+}
+
+BOOST_AUTO_TEST_CASE(is_attached_to_scene) 
+{
+  GfxTestEnv env;
+  Scene::Instance().RemoveAll();  
+  GfxNodeP n1(new GfxNode("1"));
+  GfxNodeP n2(new GfxNode("2"));
+  n1->Add(n2);
+  BOOST_CHECK(!n1->IsAttachedToScene());
+  BOOST_CHECK(!n2->IsAttachedToScene());
+  
+  Scene::Instance().Add(n1);
+  BOOST_CHECK(n1->IsAttachedToScene());
+  BOOST_CHECK(n2->IsAttachedToScene());
+  
+  // root node is always connected to scene!
+  BOOST_CHECK(Scene::Instance().GetRootNode()->IsAttachedToScene());
+}
+
+BOOST_AUTO_TEST_CASE(observe_added_removed)
+{
+  GfxTestEnv env;
+  Observer o1;
+  Scene::Instance().RemoveAll();
+  Scene::Instance().AttachObserver(&o1);
+  GfxNodeP n1(new GfxNode("1"));
+  GfxNodeP n2(new GfxNode("2"));
+  GfxNodeP n3(new GfxNode("3"));
+  n1->Add(n2);
+  BOOST_CHECK_EQUAL(o1.added_count, 0);
+  BOOST_CHECK_EQUAL(o1.removed_count, 0);
+  Scene::Instance().Add(n1);
+  BOOST_CHECK_EQUAL(o1.added_count, 1);
+  BOOST_CHECK_EQUAL(o1.removed_count, 0);
+  n2->Add(n3);
+  BOOST_CHECK_EQUAL(o1.added_count, 2);
+  BOOST_CHECK_EQUAL(o1.removed_count, 0);
+  n2->Remove(n3);
+  BOOST_CHECK_EQUAL(o1.added_count, 2);
+  BOOST_CHECK_EQUAL(o1.removed_count, 1);
+}
+
+
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/modules/gui/pymod/CMakeLists.txt b/modules/gui/pymod/CMakeLists.txt
index 00a08e2578ab167f29bae1372f2b942e73e88993..a09c9c1e7cfb691ec37c5d894bc3803dd6f930f8 100644
--- a/modules/gui/pymod/CMakeLists.txt
+++ b/modules/gui/pymod/CMakeLists.txt
@@ -84,11 +84,14 @@ set(OST_GUI_PYMOD_MODULES
   init_spacenav.py
   init_splash.py
   traj.py
+  helpwidget.py
 )
 
 set(OST_GUI_PYMOD_DNG_MODULES
   __init__.py
   termuse.py
+  init.py
+  menu.py
 )
 
 pymod(NAME gui CPP ${OST_GUI_PYMOD_SOURCES} 
diff --git a/modules/gui/pymod/__init__.py b/modules/gui/pymod/__init__.py
index 500c31ece281ed8968dc3b5dc34ffcf6f77e580c..e8571e14d88621c5f993088c3d826f082f7b6462 100644
--- a/modules/gui/pymod/__init__.py
+++ b/modules/gui/pymod/__init__.py
@@ -42,6 +42,7 @@ def ClearMessageWidget():
 
 
 from PyQt4.QtGui import *
+from PyQt4.QtCore import *
 from ost import gfx
 
 def PickColor(default=gfx.WHITE):
@@ -59,4 +60,145 @@ def PickColor(default=gfx.WHITE):
   if not qt_color.isValid():
     return None
   return gfx.Color(qt_color.red()/256.0, qt_color.green()/256.0,
-                   qt_color.blue()/256.0)
\ No newline at end of file
+                   qt_color.blue()/256.0)
+                   
+def GetMenu(menu_name, create=False):
+  persp=GostyApp.Instance().perspective
+  if isinstance(menu_name[0], QAction):
+    return menu_name[0]
+  else:
+    node=persp.GetMenu(menu_name[0])
+    for name in menu_name[1:]:
+      found=False
+      for action in node.actions():
+        if str(action.text())==str(name):
+          found=True
+          node=action
+          break
+      if not found:
+        if create:
+          node=node.addMenu(name)  
+        else:
+          raise ValueError("Menu '%s' doesn't exist" % ', '.join(menu_name))
+    return node
+
+
+
+def AddMenuAction(*args, **kwargs):
+  """
+  Add menu action to main menu.
+
+  This function lets you conveniently add actions to the main menu. To add a new 
+  new action "Background Color" to the "Scene" menu, simply use
+  
+  .. code-block:: python
+  
+    def SetBackgroundColor():
+      scene.bg=gfx.PickColor(scene.bg)
+
+    AddMenuAction('Scene', "Background Color", SetBackgroundColor)
+    
+  This will add the menu "Scene" if it does not exist yet, register the action 
+  "Background Color" and execute the function SetBackgroundColor whenever the 
+  action is triggered.
+  
+  To assign a keyboard shortcut to the action, you can use the shortcut 
+  argument:
+  
+  .. code-block:: python
+  
+    AddMenuAction('Scene', 'Background Color', SetBackgroundColor,
+                  shortcut='Ctrl+B')
+
+  Whenever you press Ctrl+B (Cmd+B on MacOS X), the action will be executed.
+  
+  Very often menu actions are coupled to the current selected objects in the 
+  scene menu. These menu actions are either enabled or disabled depending on the 
+  type of the selected objects. To easily support this scenario, the "enable" 
+  state of the menu action can be tightly coupled to the scene menu by providing 
+  a callable to the enabled argument. As an example, the following menu action 
+  is only enabled when exactly one gfx.Entity is selected.
+  
+  .. code-block:: python
+  
+    AddMenuAction('Scene', 'PrintAtomCount', PrintAtomCount,
+                  enabled=OneOf(gfx.Entity))
+  
+  OneOf is a simple function object that takes any number of classes and returns 
+  true when the selected object is an instance. Alterantively, you might want to 
+  use ManyOf or supply a custom function that evaluates the state of the menu 
+  action to suit your needs.
+  """
+  class MenuActionEnabler(QObject):
+    def __init__(self, predicate, action):
+      QObject.__init__(self, action)
+      self.predicate=predicate
+      self.action=action
+      app=GostyApp.Instance()
+      QObject.connect(app.scene_win.qobject, SIGNAL('ActiveNodesChanged()'),
+                      self.TestEnable)
+      self.TestEnable()
+
+    def TestEnable(self):
+      self.action.setEnabled(self.predicate())
+  persp=GostyApp.Instance().perspective
+  menu_name=args[:-1]
+  function=args[-1]
+  if isinstance(menu_name[0], QMenu):
+    node=menu_name[0]
+  else:
+    node=persp.GetMenu(args[0])
+    for name in menu_name[1:-1]:
+      found=False
+      for action in node.actions():
+        if str(action.text())==str(name):
+          node=action
+          break
+      if not found:
+        node=node.addMenu(name)
+  action=node.addAction(str(menu_name[-1]))
+  if 'shortcut' in kwargs:
+    action.setShortcut(QKeySequence(kwargs['shortcut']))
+  if 'checkable' in kwargs:
+    action.setCheckable(kwargs['checkable'])
+  if 'checked' in kwargs:
+    action.setChecked(kwargs['checked'])
+  if 'enabled' in kwargs:
+    if callable(kwargs['enabled']):
+      enabler=MenuActionEnabler(kwargs['enabled'], action)
+    else:
+      action.setEnabled(kwargs['enabled'])
+  QObject.connect(action, SIGNAL('triggered()'), function)
+  return action
+
+
+class OneOf:
+  def __init__(self, *classes):
+    self.classes=classes
+  def __call__(self):
+    sel=SceneSelection.Instance()
+    if sel.GetActiveNodeCount()!=1:
+      return False
+    node=sel.GetActiveNode(0)
+    for cl in self.classes:
+      if isinstance(node, cl):
+        return True
+    return False
+    
+class ManyOf:
+  def __init__(self, *classes):
+    self.classes=classes
+  def __call__(self):
+    sel=SceneSelection.Instance()
+    if sel.GetActiveNodeCount()==0:
+      return False
+    for  i in range(sel.GetActiveNodeCount()):
+      node=sel.GetActiveNode(i)
+      found=False
+      for cl in self.classes:
+        if isinstance(node, cl):
+          found=True
+          break
+      if not found:
+        return False
+    return True
diff --git a/modules/gui/pymod/dng/init.py b/modules/gui/pymod/dng/init.py
new file mode 100644
index 0000000000000000000000000000000000000000..b56ce5ab2f83692720e1d2f2b8be96300adbf7bb
--- /dev/null
+++ b/modules/gui/pymod/dng/init.py
@@ -0,0 +1,222 @@
+import __main__
+import sys
+import os.path
+import optparse
+from ost import io, mol, seq, geom, conop, gui, settings, gfx
+
+import ost
+try: 
+  from ost import img
+  import ost.img.alg
+  _img_present=True
+except ImportError:
+  _img_present=False
+  pass
+import httplib
+
+from PyQt4 import QtGui, QtCore
+from ost.gui.scene.init_inspector import _InitInspector
+from ost.gui.init_menubar import _InitMenuBar
+from ost.gui.init_spacenav import _InitSpaceNav
+from ost.gui.init_context_menu import _InitContextMenu
+from ost.gui.init_splash import _InitSplash
+from ost.gui.dng import termuse
+from ost.gui.helpwidget import help
+import ost.gui.dng.menu
+from PyQt4.QtGui import *
+def _my_exit(code):
+  QtGui.QApplication.instance().quit()
+  gui.GostyApp.Instance().ProcessEvents()
+  sys._exit(code)
+
+sys._exit=sys.exit
+sys.exit=_my_exit
+
+def _InitRuleBasedBuilder():
+  compound_lib_path=os.path.join(ost.GetSharedDataPath(), 'compounds.chemlib')
+  if os.path.exists(compound_lib_path):
+    conop_inst=conop.Conopology.Instance()
+    compound_lib=conop.CompoundLib.Load(compound_lib_path)
+    conop_inst.RegisterBuilder(conop.RuleBasedBuilder(compound_lib), 'RBB')
+    conop_inst.SetDefaultBuilder('RBB')
+
+# switch to rule-based builder for high fidelity if compounds.chemlib is 
+# available
+_InitRuleBasedBuilder()
+
+def _CheckRestore():
+  settings = QtCore.QSettings()
+  restore = settings.value("restore_settings",QtCore.QVariant(False)).toBool()
+  if not restore:
+    settings.clear()
+  settings.setValue("restore_settings",QtCore.QVariant(True))
+
+def _InitPanels(app):
+  panels = app.perspective.panels
+  panels.AddWidgetToPool('ost.gui.FileBrowser', -1)
+  panels.AddWidgetToPool('ost.gui.PythonShell', 1)
+  panels.AddWidgetToPool('ost.gui.RemoteLoader', -1)
+  panels.AddWidgetToPool('ost.gui.SceneWin', 1)
+  panels.AddWidgetToPool('ost.gui.SequenceViewer', 1)
+  panels.AddWidgetToPool('ost.gui.MessageWidget', 1)
+  if not panels.Restore("ui/perspective/panels"):
+    panels.AddWidget(gui.PanelPosition.LEFT_PANEL, app.scene_win)
+    panels.AddWidgetByName(gui.PanelPosition.LEFT_PANEL, 
+                           'ost.gui.FileBrowser', False)    
+    panels.AddWidgetByName(gui.PanelPosition.LEFT_PANEL, 
+                           'ost.gui.RemoteLoader', False)
+    panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.seq_viewer)
+    panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.py_shell)
+    panels.AddWidget(gui.PanelPosition.RIGHT_PANEL, app.message_widget)
+    return False
+  return True
+
+
+def _InitFrontEnd(try_stereo):
+  _CheckRestore()
+  app=gui.GostyApp.Instance()
+  app.SetAppTitle("DNG")
+  app.TryStereo(try_stereo)
+  main_area=app.perspective.main_area
+  _InitSpaceNav(app)
+  _InitContextMenu(app)
+  main_area.AddPersistentWidget("3D Scene", "gl_win" , app.gl_win,
+                                int(QtCore.Qt.WindowMaximized))
+  _InitInspector(app)
+  ost.gui.dng.menu._InitMenu()
+  app.perspective.Restore()
+  additional_modules=getattr(__main__, 'ADDITIONAL_GUI_MODULES', [])
+  for module_name in additional_modules:
+    __import__(module_name)
+  app.ProcessEvents()
+  
+
+
+  if not _InitPanels(app):
+    _InitSplash()
+  
+def _load_files():
+  for pdb_id in options.pdb_ids:
+    pdb_id, sel=_SplitIDSel(pdb_id)
+    selection=_get_selection_query(sel)
+    gui.FileLoader.LoadFrom(pdb_id,"pdb.org",selection)
+    
+  input_files=[_SplitIDSel(arg) for arg in loading_list]
+  for f in input_files:
+    selection=_get_selection_query(f[1])
+    gui.FileLoader.LoadObject(f[0],selection)
+
+def _get_selection_query(sel):
+  if len(options.query)>0:
+    if len(sel)>0:
+      return '(%s) and (%s)' % (options.query, sel)
+    else:
+      return options.query
+  elif len(sel)>0:
+    return sel
+  return ""
+
+def _execute_script():
+  script=script_argv[0]
+  sys_argv_backup=sys.argv
+  sys.argv=script_argv
+  try:
+    execfile(script, __main__.__dict__)
+  finally:
+    sys.argv=sys_argv_backup     
+
+def show_help(option, opt, value, parser):
+  parser.print_help()
+  QtGui.QApplication.instance().exit()
+  sys.exit(-1)
+
+def parse_script_option(option, opt, value, parser):
+  script_argv.append(value)
+  for arg in parser.rargs:
+     script_argv.append(arg)
+  del parser.rargs[0:len(parser.rargs)]
+
+def _SplitIDSel(name):
+  pos=name.find('[')
+  if pos>-1:
+    return name[:pos], name[pos+1:-1]
+  return name, ''  
+
+def stop():
+  gui.GostyApp.Instance().StopScript()
+
+
+loading_list=[]
+script_argv=[]
+#images=[]
+#viewers=[]
+usage = 'usage: dng [options] [files to load]'
+class OstOptionParser(optparse.OptionParser):
+  def __init__(self, **kwargs):
+    optparse.OptionParser.__init__(self, **kwargs)
+  def exit(self, status_code, error_message):
+    print error_message,
+    QtGui.QApplication.instance().exit()
+    sys.exit(-1)
+
+parser=OstOptionParser(usage=usage,conflict_handler="resolve")
+parser.add_option("-h", "--help", action="callback", callback=show_help, help="show this help message and exit")
+parser.add_option("-v", "--verbosity_level", action="store", type="int", dest="vlevel", default=2, 
+                  help="sets the verbosity level [default: %default]")
+parser.add_option("-s", "--script", action="callback", default=[], dest="script", type="string", callback=parse_script_option, help="executes a script (syntax: -s SCRIPT [options] [args]) Anything that follows this option is passed to the script")
+parser.add_option("-p", "--pdb_id", dest="pdb_ids", default=[],action="append", help="PDB file ID. The file will be retrieved from PDB")
+parser.add_option("-b", "--builder", dest="builder", default="HEURISTIC", help="Type of builder used by the progam (either RULE_BASED or HEURISTIC) [default: %default]")
+parser.add_option("-c", "--compound_library", dest="complib", default="compounds.chemlib", help="Compound library for the RULE_BASED builder (only used if --builder option is set to RULE_BASED, otherwise ignored [default: %default]")
+parser.add_option("-q", "--query", dest="query", default="", help="Selection query to be highlighted automatically upon loading (only used together with -p option or when a PDB file is loaded, otherwise ignored [default: None]")
+parser.add_option("-S","--stereo", dest="try_stereo", default=False, action="store_true",help="try to get a quad-buffer stereo visual")
+parser.disable_interspersed_args()
+(options, args) = parser.parse_args()
+
+if len(parser.rargs)!=0:
+  for rargs_string in parser.rargs:
+    if not rargs_string.endswith('.py'):  
+      loading_list.append(rargs_string)
+    else:
+      print 'Error:  one of the files to load is a Python script, use -s flag to execute it\n'
+      QtGui.QApplication.instance().exit()
+      sys.exit(-1)    
+
+if len(options.script)!=0:
+  script_argv=options.script
+
+if options.builder=="RULE_BASED":
+  from ost import conop
+  compound_lib=conop.CompoundLib.Load(options.complib)
+  rbb=conop.RuleBasedBuilder(compound_lib)
+  conop.Conopology.Instance().RegisterBuilder(rbb,'rbb')
+  conop.Conopology.Instance().SetDefaultBuilder('rbb')
+
+home = os.getenv('HOME') or os.getenv('USERPROFILE')
+_ostrc=os.path.join(home, '.ostrc')
+if os.path.exists(_ostrc):
+  try:
+    exec(open(_ostrc))
+  except Exception, e:
+    print e
+else:
+  rcfile=open(_ostrc,"w")
+  print >> rcfile, '# This python file is parsed by ost and dng at startup'
+  print >> rcfile, '# Its content is made available in the global namespace'
+  print >> rcfile, '# It can be used to define custom variables and functions'
+  print >> rcfile, '# For example:'
+  print >> rcfile, '# IMPORTANT_DIR="path/to/important/dir"'
+  rcfile.close()
+
+ost.PushVerbosityLevel(options.vlevel)
+working_dir=settings.GetValue("DNG_WORKING_DIR",None)
+
+if working_dir != None and os.path.isdir(working_dir):
+  os.chdir(working_dir)
+
+_InitFrontEnd(options.try_stereo)
+
+if len(loading_list)!=0 or len(options.pdb_ids)!=0:
+  _load_files()
+  gfx.Scene().Autoslab()
+if len(script_argv)!=0:
+  _execute_script()
diff --git a/modules/gui/pymod/dng/menu.py b/modules/gui/pymod/dng/menu.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2b672c2b28e7a11a9855eec4aff08c722845016
--- /dev/null
+++ b/modules/gui/pymod/dng/menu.py
@@ -0,0 +1,259 @@
+from PyQt4.QtCore import *
+from PyQt4.QtGui import *
+from ost import gui, gfx, io
+from ost.gui.scene.loader_manager_widget import LoaderManagerWidget
+from ost.gui.init_splash import _InitSplash
+from ost.gui.dng import termuse
+import sys
+class FileMenu(QMenu):
+  def __init__(self, parent=None):
+    QMenu.__init__(self, parent)
+    self.setTitle('File')
+    gui.AddMenuAction(self, 'Open', self._Open, shortcut='Ctrl+O')
+    gui.AddMenuAction(self, 'Save As...', self._SaveAs, 
+                  shortcut='Ctrl+Shift+S', 
+                  enabled=gui.OneOf(gfx.Entity))
+  def _Open(self):
+    filename=QFileDialog.getOpenFileName(None, 'Open file','')
+    if(QFileInfo(filename).isFile()):
+      gui.FileLoader.LoadObject(str(filename))
+
+  def _SaveAs(self):
+    sel_node=gui.SceneSelection.Instance().GetActiveNode(0)
+    filename=QFileDialog.getSaveFileName(None, 'Save As', 
+                                         '%s.pdb' % sel_node.name)
+    io.SavePDB(sel_node.view, str(filename))
+    
+class ClipWidget(QWidget):
+  def __init__(self, width=500, height=500):
+    QWidget.__init__(self)
+    self.setWindowFlags(Qt.Tool)
+    l = QGridLayout(self)
+    l.addWidget(QLabel("Near"), 0, 0)
+    l.addWidget(QLabel("Far"), 1, 0)
+    bounds_near = QLineEdit(str(0))
+    bounds_near.setValidator(QIntValidator(0, 9999, bounds_near))
+    bounds_near.setMaxLength(4)
+    bounds_near.setMaximumWidth(50)
+    bounds_far = QLineEdit(str(200))
+    bounds_far.setValidator(QIntValidator(0, 9999, bounds_far))
+    bounds_far.setMaxLength(4)
+    bounds_far.setMaximumWidth(50)
+    l.addWidget(bounds_near, 0, 1, 2, 1)
+    l.addWidget(bounds_far, 0, 3, 2, 1)
+    self.near_ = QSlider(Qt.Horizontal)
+    self.near_.setMinimum(int(bounds_near.text()))
+    self.near_.setMaximum(int(bounds_far.text()))
+    self.near_.setValue(int(gfx.Scene().near))
+    self.far_ = QSlider(Qt.Horizontal)
+    self.far_.setMinimum(int(bounds_near.text()))
+    self.far_.setMaximum(int(bounds_far.text()))
+    far = int(gfx.Scene().far)
+    if far>sys.maxint:
+      far = sys.maxint
+    self.far_.setValue(far)
+    self.auto_ = QCheckBox("Continuous Automatic Clipping")
+    self.auto_.setChecked(gfx.Scene().GetAutoAutoslab())
+
+    l.addWidget(self.near_, 0, 2)
+    l.addWidget(self.far_, 1, 2)
+    l.addWidget(self.auto_, 2, 0, 1, 4)
+    self.connect(self.near_, SIGNAL('valueChanged(int)'), self.SetNear)
+    self.connect(self.far_, SIGNAL('valueChanged(int)'), self.SetFar)
+    self.connect(self.auto_, SIGNAL('stateChanged(int)'), self.SetAuto)
+    self.connect(bounds_near, SIGNAL('textEdited(QString)'), self.SetNearBounds)
+    self.connect(bounds_far, SIGNAL('textEdited(QString)'), self.SetFarBounds)
+
+  def SetNear(self, val):
+    gfx.Scene().near = val
+
+  def SetFar(self, val):
+    gfx.Scene().far = val
+
+  def SetAuto(self, val):
+    gfx.Scene().AutoAutoslab(val)
+    gfx.Scene().near = int(self.near_.value())
+    gfx.Scene().far = int(self.far_.value())
+
+  def SetNearBounds(self, text):
+    if text!='':
+      self.near_.setMinimum(int(text))
+      self.far_.setMinimum(int(text))
+
+  def SetFarBounds(self, text):
+    if text!='':
+      self.near_.setMaximum(int(text))
+      self.far_.setMaximum(int(text))
+
+class ExportSceneDialog(QDialog):
+  def __init__(self, width=500, height=500):
+    QDialog.__init__(self)
+    l=QGridLayout(self)
+    l.setColumnMinimumWidth(0, 100)
+    l.addWidget(QLabel("Width (px)"), 0, 0)
+    l.addWidget(QLabel("Height (px)"), 1, 0)
+    self.width_=QLineEdit(str(width))
+    self.height_=QLineEdit((str(height)))
+    self.width_.setValidator(QIntValidator(50, 3000, self.width_))
+    self.height_.setValidator(QIntValidator(50, 3000, self.height_))
+    self.opaque_=QCheckBox("Force Opaque Background")
+    l.addWidget(self.width_, 0, 1)
+    l.addWidget(self.height_, 1, 1)
+    l.addWidget(self.opaque_, 2, 1)
+    hbox=QHBoxLayout()
+    cancel=QPushButton("Cancel")
+    QObject.connect(cancel, SIGNAL('clicked()'), self.reject)
+    hbox.addWidget(cancel)
+    export=QPushButton("Export")
+    hbox.addWidget(export)
+    export.setDefault(True)
+    l.addLayout(hbox, 3, 1, 2, 1)
+    QObject.connect(export, SIGNAL('clicked()'), self.accept)
+  @property
+  def transparent(self):
+    return not self.opaque_.isChecked()
+
+  @property
+  def width(self):
+    return int(self.width_.text())
+
+  @property
+  def height(self):
+    return int(self.height_.text())
+
+class SceneMenu(QMenu):
+  def __init__(self, parent=None):
+    QMenu.__init__(self, parent)
+    self.setTitle('Scene')
+    QObject.connect(self, SIGNAL('aboutToShow()'), self._AboutToShow)
+    gui.AddMenuAction(self, 'Background Color', self._SetSceneBackground)
+    self.fog_action=gui.AddMenuAction(self, 'Depth Cueing', self._ToggleFog, 
+                                  shortcut='Ctrl+Shift+F', checkable=True, 
+                                  checked=gfx.Scene().fog)
+    gui.AddMenuAction(self, 'Center', self._Center,
+                  enabled=gui.ManyOf(gfx.GfxObj))
+    gui.AddMenuAction(self, 'Fit To Screen', self._FitToScreen,
+                  enabled=gui.OneOf(gfx.Entity))
+    gui.AddMenuAction(self, 'Save Snapshot', self._ExportScene)
+    gui.AddMenuAction(self, 'Scene Clipping', self._ClipScene, shortcut='Ctrl+Shift+C')
+    
+  def _ExportScene(self):
+    qd=ExportSceneDialog()
+    if not qd.exec_():
+      return
+    filename=QFileDialog.getSaveFileName(None, 'Save Snapshot', 
+                                         'snapshot.png')
+    if filename:
+      gfx.Scene().Export(str(filename), qd.width, qd.height, qd.transparent)
+
+  def _ClipScene(self):
+    self.cw = ClipWidget()
+    self.cw.show()
+
+  def _AboutToShow(self):
+    self.fog_action.setChecked(gfx.Scene().fog)
+    
+  def _Center(self):
+    sel=gui.SceneSelection.Instance()
+    gfx.Scene().center=sel.GetActiveNode(0).center
+
+  def _SetSceneBackground(self):
+    new_color=gui.PickColor(gfx.Scene().bg)
+    if new_color:
+      gfx.Scene().bg=new_color
+
+  def _ToggleFog(self):
+    gfx.Scene().fog=not gfx.Scene().fog
+    self.fog_action.setChecked(gfx.Scene().fog)
+
+  def _FitToScreen(self):
+    sel=gui.SceneSelection.Instance()
+    gfx.FitToScreen(sel.GetActiveNode(0))
+  
+class WindowMenu(QMenu):
+  def __init__(self, parent=None):
+    QMenu.__init__(self, parent)
+    self.setTitle('Window')
+    self.loader_manager=LoaderManagerWidget()
+    gosty=gui.GostyApp.Instance()
+    QObject.connect(self, SIGNAL('aboutToShow()'), self._AboutToShow)
+    inspector_visible=gosty.GetWidget('InspectorDialog').isVisible()
+    self._gl_win_action=gui.AddMenuAction(self, 'GL Window',  
+                                      self._ToggleShowGLWindow, checkable=True,
+                                      checked=gosty.gl_win.qobject.isVisible(),
+                                      shortcut='Ctrl+G')
+    self._inspector_action=gui.AddMenuAction(self, 'Inspector', 
+                                         self._ToggleShowInspector,
+                                         checkable=True,
+                                         checked=inspector_visible,
+                                         shortcut='Ctrl+I')
+    self.addSeparator()
+    self.addMenu(gosty.perspective.panels.menu)
+    gui.AddMenuAction(self, 'Reset View', self._ResetView)
+  def _AboutToShow(self):
+    gosty=gui.GostyApp.Instance()
+    self._gl_win_action.setChecked(gosty.gl_win.qobject.isVisible())
+    inspector_visible=gosty.GetWidget('InspectorDialog').isVisible()
+    self._inspector_action.setChecked(inspector_visible)
+    
+  def _ToggleShowGLWindow(self):
+    gosty=gui.GostyApp.Instance()
+    gl_win=gosty.GetGLWin()
+    if gl_win and gl_win.qobject.isHidden():
+      gl_win.Show()
+    else:
+      gl_win.Hide()
+
+  def _ToggleShowInspector(self):
+    gosty=gui.GostyApp.Instance()
+    inspector=gosty.GetWidget('InspectorDialog')
+    if inspector and inspector.isHidden():
+      inspector.show()
+    else:
+      inspector.hide()
+      
+  def _ResetView(self):
+    msg_box = QMessageBox()
+    msg_box.setWindowTitle("Reset the Panels and Widget");
+    msg_box.setIcon(QMessageBox.Question)
+    msg_box.setText("Do you really want to reset the Panels and Widgets?");
+    msg_box.setStandardButtons(QMessageBox.Yes |
+                               QMessageBox.Cancel);
+    msg_box.setDefaultButton(QMessageBox.Cancel);
+    ret = msg_box.exec_();
+    if(ret == QMessageBox.Yes):
+      settings = QSettings()
+      settings.setValue("restore_settings",QVariant(False))
+      info_box = QMessageBox()
+      info_box.setStandardButtons(QMessageBox.Ok)
+      info_box.setIcon(QMessageBox.Information)
+      info_box.setWindowTitle("Restart OpenStructure")
+      info_box.setText("You must restart OpenStructure for the changes to take effect!");
+      info_box.exec_();
+
+class HelpMenu(QMenu):
+  def __init__(self, parent=None):
+    QMenu.__init__(self, parent)
+    self.setTitle('Help')
+    gui.AddMenuAction(self, 'Documentation', self._VisitDocs)
+    gui.AddMenuAction(self, 'About', self._ShowAboutDialog)
+    if sys.platform=='darwin':
+      gui.AddMenuAction(self, 'Install Command Line Tool',
+                    termuse.InstallTerminalPrograms)
+  def _VisitDocs(self):
+    QDesktopServices.openUrl(QUrl("http://www.openstructure.org/docs/"))
+  
+  def _ShowAboutDialog(self):
+    _InitSplash()
+
+
+def _InitMenu():
+  mbar=gui.GostyApp.Instance().perspective.GetMenuBar()
+  file_menu=FileMenu(mbar)
+  scene_menu=SceneMenu(mbar)
+  win_menu=WindowMenu(mbar)
+  help_menu=HelpMenu(mbar)
+  mbar.addMenu(file_menu)
+  mbar.addMenu(scene_menu)
+  mbar.addMenu(win_menu)
+  mbar.addMenu(help_menu)
diff --git a/modules/gui/pymod/export_gosty.cc b/modules/gui/pymod/export_gosty.cc
index 239174a42c37b8b5c4732abffff6f9fab13d24d1..5a9ee652d658d2fe7364ddc2e491777d0279ce58 100644
--- a/modules/gui/pymod/export_gosty.cc
+++ b/modules/gui/pymod/export_gosty.cc
@@ -28,11 +28,15 @@ using namespace boost::python;
 #include <ost/gui/python_shell/python_shell.hh>
 #include <ost/gui/scene_win/scene_win.hh>
 #include <ost/gui/tools/tool_options_win.hh>
+#include <ost/gui/scene_win/scene_win.hh>
+#include <ost/gui/sequence_viewer/sequence_viewer.hh>
+#include <ost/gui/messages/message_widget.hh>
 
 #include "transfer_ownership.hh"
 #include "sip_handler.hh"
 
 #if OST_IMG_ENABLED
+  #include <ost/gui/data_viewer/data_viewer.hh>
 #include <ost/img/data.hh>
 #include <ost/gui/data_viewer/data_viewer.hh>
 using namespace ost::img::gui;
@@ -44,7 +48,9 @@ using namespace ost::gui;
 namespace {
 
 #if OST_IMG_ENABLED
-DataViewer* app_create_data_viewer1(GostyApp* app, const ost::img::Data& d, const QString& name)
+DataViewer* app_create_data_viewer1(GostyApp* app, 
+                                    const ost::img::Data& d, 
+                                    const QString& name)
 {
   return app->CreateDataViewer(d,name);
 }
@@ -73,12 +79,18 @@ void app_add_widget_to_app_b(GostyApp* app, const QString& ident,
   }
 }
 
+object get_widget(GostyApp* app, const QString& ident)
+{
+  return get_py_qobject<QWidget>(app->GetWidget(ident));
+}
+
 void export_Gosty()
 {
   class_<GostyApp, boost::noncopyable>("GostyApp", no_init)
     .def("Instance", &GostyApp::Instance,
          return_value_policy<reference_existing_object>()).staticmethod("Instance")
     .def("SetAppTitle", &GostyApp::SetAppTitle)
+    .def("StopScript",&GostyApp::StopScript)
     .def("GetPyShell", &GostyApp::GetPyShell,
         return_value_policy<reference_existing_object>())
     .add_property("py_shell", make_function(&GostyApp::GetPyShell,
@@ -97,6 +109,7 @@ void export_Gosty()
         return_value_policy<reference_existing_object>()))
     .def("GetToolOptionsWin", &GostyApp::GetToolOptionsWin,
         return_value_policy<reference_existing_object>())
+    .def("GetWidget", &get_widget)
     .add_property("tool_options_win", make_function(&GostyApp::GetToolOptionsWin,
         return_value_policy<reference_existing_object>()))
     .def("GetMessageWidget", &GostyApp::GetMessageWidget,
@@ -115,6 +128,7 @@ void export_Gosty()
     .def("AddWidgetToApp", &app_add_widget_to_app_b)
     .def("GetPerspective", &GostyApp::GetPerspective, 
          return_value_policy<reference_existing_object>())
+    .def("TryStereo",&GostyApp::TryStereo)
   ;
   register_ptr_to_python<GostyApp*>();
 }
diff --git a/modules/gui/pymod/export_perspective.cc b/modules/gui/pymod/export_perspective.cc
index bf5f14b3f133bc33a425e15ad7f3bffafa057fd4..17d522f5e4d6502bc249ecb0cf82f37691620a5f 100644
--- a/modules/gui/pymod/export_perspective.cc
+++ b/modules/gui/pymod/export_perspective.cc
@@ -22,6 +22,9 @@
 
 #include <ost/gui/perspective.hh>
 #include <ost/gui/main_area.hh>
+#include <ost/gui/panels/panel_manager.hh>
+#include <ost/gui/panels/button_bar.hh>
+#include <ost/gui/panels/panel_bar.hh>
 
 #include "sip_handler.hh"
 
diff --git a/modules/gui/pymod/export_plot.cc b/modules/gui/pymod/export_plot.cc
index a921472ad6c8134166d507c956f304f6306eff2f..b233efeb145ec8ae98fdf707845657c659a3246c 100644
--- a/modules/gui/pymod/export_plot.cc
+++ b/modules/gui/pymod/export_plot.cc
@@ -38,6 +38,7 @@ namespace {
 
 struct PlotFunctionWrap : PlotFunction, wrapper<PlotFunction>
 {
+  IOProfileWrap(PyObject*&, const ost::io::IOProfile&)
   Real  Func(Real val) const
   {
     return this->get_override("Func")(val);
diff --git a/modules/gui/pymod/export_sequence_viewer.cc b/modules/gui/pymod/export_sequence_viewer.cc
index 268b4dd2b28d3779d9b5d2260c978f21cdb0c293..20b56cf44a2de1ec4485d589f5485b93911061c7 100644
--- a/modules/gui/pymod/export_sequence_viewer.cc
+++ b/modules/gui/pymod/export_sequence_viewer.cc
@@ -96,12 +96,14 @@ std::vector<String> get_display_modes_c(SequenceViewer* seq_viewer, const seq::A
 
 void export_SequenceViewer()
 {
-  class_<SequenceViewer, boost::noncopyable >("SequenceViewer",init<>())
-    .def(init<bool, optional<QWidget*> >())
+  class_<SequenceViewer, boost::noncopyable >("SequenceViewer")
+    .def(init<optional<bool, bool, const QString&, 
+              QWidget*> >())
     .def("Show", &SequenceViewer::show)
     .def("Hide", &SequenceViewer::hide)
     .def("AddEntity", &SequenceViewer::AddEntity)
     .def("RemoveEntity", &SequenceViewer::RemoveEntity)
+    .def("SetAlignment", &SequenceViewer::SetAlignment)
     .def("AddAlignment", &SequenceViewer::AddAlignment)
     .def("RemoveAlignment", &SequenceViewer::RemoveAlignment)
     .def("GetDisplayModes", &get_display_modes_a)
diff --git a/modules/gui/pymod/export_tool.cc b/modules/gui/pymod/export_tool.cc
index 1d050038fb3854d45b797b56994c6bbe872d55df..11ee78b910a08049730e2adec7a42fc297869724 100644
--- a/modules/gui/pymod/export_tool.cc
+++ b/modules/gui/pymod/export_tool.cc
@@ -250,9 +250,5 @@ void export_Tool()
     .def("GetQObject",&get_py_qobject<ToolOptionsWin>)
     .add_property("qobject", &get_py_qobject<ToolOptionsWin>)
   ;
-
-  class_<gfx::NodePtrList>("NodePtrList", init<>())
-    .def(vector_indexing_suite<gfx::NodePtrList, true >())
-  ;
 }
 
diff --git a/modules/gui/pymod/helpwidget.py b/modules/gui/pymod/helpwidget.py
new file mode 100644
index 0000000000000000000000000000000000000000..117230ece30d2a1d1ec1488d9c66020b24ff100d
--- /dev/null
+++ b/modules/gui/pymod/helpwidget.py
@@ -0,0 +1,42 @@
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+from ost import gui
+class DocWidget(QWidget):
+  def __init__(self, parent=None):
+    QWidget.__init__(self, parent)
+    l=QVBoxLayout(self)
+    l.setMargin(0)
+    self.setWindowTitle('OpenStructure Help')
+    self.searchbox=QLineEdit(self)
+    l.addWidget(self.searchbox)
+    self.doctext=QTextEdit('', self)
+    l.addWidget(self.doctext)
+    self.setLayout(l)
+    QObject.connect(self.searchbox, SIGNAL('returnPressed()'),
+                    self.OnReturnPressed)
+  def OnReturnPressed(self):
+    help(str(self.searchbox.text()))
+doc_widget=DocWidget()
+doc_widget_for_panel=gui.Widget(doc_widget)
+panels=gui.GostyApp.Instance().perspective.panels
+panels.AddWidgetToPool("Doc",doc_widget_for_panel)
+
+
+class Help:
+  def __call__(self, what=None):
+    import pydoc
+    d=pydoc.HTMLDoc()
+    if what==None:
+      doc_widget.doctext.setHtml('')
+      doc_widget.show()
+      doc_widget.searchbox.setText('')
+      return
+    s=d.document(pydoc.resolve(what)[0])
+    doc_widget.doctext.setHtml(s)
+    doc_widget.searchbox.setText('')
+    if not doc_widget.isVisible():
+      panels.AddWidget(gui.PanelPosition.RIGHT_PANEL, doc_widget_for_panel, False)
+  def __repr__(self):
+    return 'Type help() for interactive help, or help(object) for help about object.'
+
+help=Help()
diff --git a/modules/gui/pymod/init_context_menu.py b/modules/gui/pymod/init_context_menu.py
index bddcda7fd2533e347ae910e7c5f361f680043cc4..750c123bc1337df940b79e98cd43a41f8c22987f 100644
--- a/modules/gui/pymod/init_context_menu.py
+++ b/modules/gui/pymod/init_context_menu.py
@@ -218,7 +218,7 @@ class SurfaceContextMenu(QtCore.QObject):
     for entity in ent_list:
       if isinstance(entity, gfx.Entity):
         try:
-          s=msms.CalculateSurface(entity.view.handle,
+          s=msms.CalculateSurface(entity.view,
                                   msms_exe=msms_exe,
                                   density=density,
                                   radius=radius,
diff --git a/modules/gui/pymod/init_menubar.py b/modules/gui/pymod/init_menubar.py
index ac5c23e23dd0aebcc57f297ea3bd42fa6d11386a..e0c05c620dfda0dd08a6f3f7bb3fb30c58e7049e 100644
--- a/modules/gui/pymod/init_menubar.py
+++ b/modules/gui/pymod/init_menubar.py
@@ -127,8 +127,8 @@ class InitMenuBar(QtCore.QObject):
       info_box.exec_();
             
 def _InitMenuBar(app):
-  InitMenuBar(app.perspective.menubar)
-  
+  #InitMenuBar(app.perspective.menubar)
+  pass
 ## \example menubar_example.py
 #
 # Shows how to use PyQt to add a menu from within Python and interact 
diff --git a/modules/gui/pymod/init_splash.py b/modules/gui/pymod/init_splash.py
index 33263606301d852f81414bfffcf62d2f8acfa215..ec5e3667cd23e8625b9bc29fcb811bd6eda0e3d5 100644
--- a/modules/gui/pymod/init_splash.py
+++ b/modules/gui/pymod/init_splash.py
@@ -6,6 +6,15 @@ from ost import gui
 
 LOGO_PATH = os.path.join(ost.GetSharedDataPath(), "gui", "images", "logo-small.png")
 
+
+SPLASH_TEXT=""""Welcome to <b>Openstructure</b>!<br/><br/>
+You are running version %s<br /><br />If you are new to OpenStructure, we 
+invite you to run the demos from the examples directory. Scripts can be 
+displayed by right clicking on the file and selecting 'Show source'.<br/><br/>
+Feel free visit our website at:<br /> 
+<a href='http://www.openstructure.org'>http://www.openstructure.org</a>
+""" % ost.VERSION
+
 class SplashDialog(QtGui.QDialog):
   def __init__(self, parent=None):
     QtGui.QDialog.__init__(self, parent)
@@ -15,9 +24,10 @@ class SplashDialog(QtGui.QDialog):
     self.pix_map = QtGui.QPixmap(LOGO_PATH);
     imageLabel.setPixmap(self.pix_map);
     layout.addWidget(imageLabel)
-    self.label = QtGui.QTextEdit()
+    self.label = QtGui.QTextBrowser()
     self.label.setReadOnly(True)
-    self.label.setHtml("Welcome to <b>Openstructure</b>!<br /><br />You are running version 1.0.0a<br /><br />If you are new to OpenStructure, we invite you to run the demos from the examples directory. Scripts can be displayed by right clicking on the file and selecting 'Show source'.<br /><br />Feel free visit our website at:<br /> http://www.openstructure.org")
+    self.label.setOpenExternalLinks(True)
+    self.label.setHtml(SPLASH_TEXT)
     layout.addWidget(self.label)
     
 def _InitSplash():
@@ -25,3 +35,6 @@ def _InitSplash():
   splash.exec_()
 
   #QtCore.QTimer.singleShot(30000, splash.close);
+
+
+__all__=('SplashDialog',)
diff --git a/modules/gui/pymod/scene/cpk_widget.py b/modules/gui/pymod/scene/cpk_widget.py
index 81070180de13f83eb3d817380ed9d1f43a3f8501..9a15dce91543a23bde329fff8b95411949c6bada 100644
--- a/modules/gui/pymod/scene/cpk_widget.py
+++ b/modules/gui/pymod/scene/cpk_widget.py
@@ -42,7 +42,10 @@ class CPKWidget(RenderModeWidget):
     
     self.sphere_spinbox_ = QtGui.QSpinBox()
     self.sphere_spinbox_.setRange(min_sphere_detail, max_sphere_detail)
-    
+    cpk_mode_label = QtGui.QLabel("Rendering Mode")
+    self.cpk_mode_ = QtGui.QComboBox()
+    self.cpk_mode_.addItem("Triangles")
+    self.cpk_mode_.addItem("3D Sprites")
     cpk_label = QtGui.QLabel(self.text_)
     font = cpk_label.font()
     font.setBold(True)
@@ -56,15 +59,21 @@ class CPKWidget(RenderModeWidget):
     self.setLayout(grid)
   
     QtCore.QObject.connect(self.sphere_spinbox_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateSphereDetail)
+    QtCore.QObject.connect(self.cpk_mode_, QtCore.SIGNAL("currentIndexChanged(int)"), self.UpdateSphereMode)
     
     self.setMinimumSize(250,60)
     
   def UpdateSphereDetail(self, value):
     self.GetOptions().SetSphereDetail(value)
     self.ApplyOptions()
+
+  def UpdateSphereMode(self, value):
+    self.GetOptions().SetSphereMode(value)
+    self.ApplyOptions()
     
   def UpdateGui(self,options):
     self.sphere_spinbox_.setValue(options.GetSphereDetail())
+    self.cpk_mode_.setCurrentIndex(options.GetSphereMode())
 
   def GetText(self):
     return self.text_
diff --git a/modules/gui/pymod/scene/hsc_widget.py b/modules/gui/pymod/scene/hsc_widget.py
index 8a0464841f48d262cb074fed1594ff47be9a6d5b..f5ca1ad00b6aa5c6058cd91c3661f900b2ee6cd9 100644
--- a/modules/gui/pymod/scene/hsc_widget.py
+++ b/modules/gui/pymod/scene/hsc_widget.py
@@ -132,7 +132,6 @@ class HSCWidget(RenderModeWidget):
     self.width_helix_slider_.setTickPosition(QtGui.QSlider.NoTicks)
     self.width_helix_slider_.setTickInterval(1)
     
-    
     #Helix Ratio
     ratio_helix_label = QtGui.QLabel("Thickness")
     
@@ -146,7 +145,6 @@ class HSCWidget(RenderModeWidget):
     self.thickness_helix_slider_.setTickPosition(QtGui.QSlider.NoTicks)
     self.thickness_helix_slider_.setTickInterval(1)
     
-    
     #Helix ECC
     ecc_helix_label = QtGui.QLabel("ECC")
     
@@ -165,6 +163,11 @@ class HSCWidget(RenderModeWidget):
     self.helix_profile_spinbox_ = QtGui.QSpinBox()
     self.helix_profile_spinbox_.setRange(min_profile, max_profile)
     
+    # Helix Rendering Mode
+    helix_mode_label = QtGui.QLabel("Helix Render Mode")
+    self.helix_mode_spinbox_ = QtGui.QSpinBox()
+    self.helix_mode_spinbox_.setRange(0, 1)
+    
     #Strand
     strand_label = QtGui.QLabel("Strand")
     font = strand_label.font()
@@ -183,7 +186,6 @@ class HSCWidget(RenderModeWidget):
     self.width_strand_slider_.setTickPosition(QtGui.QSlider.NoTicks)
     self.width_strand_slider_.setTickInterval(1)
     
-    
     #Strand Ratio
     ratio_strand_label = QtGui.QLabel("Thickness")
     
@@ -197,7 +199,6 @@ class HSCWidget(RenderModeWidget):
     self.thickness_strand_slider_.setTickPosition(QtGui.QSlider.NoTicks)
     self.thickness_strand_slider_.setTickInterval(1)
     
-    
     #Strand ECC
     ecc_strand_label = QtGui.QLabel("ECC")
     
@@ -216,6 +217,12 @@ class HSCWidget(RenderModeWidget):
     self.strand_profile_spinbox_ = QtGui.QSpinBox()
     self.strand_profile_spinbox_.setRange(min_profile, max_profile)
 
+    # Strand Rendering Mode
+    strand_mode_label = QtGui.QLabel("Strand Render Mode")
+    self.strand_mode_spinbox_ = QtGui.QSpinBox()
+    self.strand_mode_spinbox_.setRange(0, 1)
+
+    #
     row=1
     grid = QtGui.QGridLayout()
     grid.addWidget(poly_mode_label,row,0,1,1)
@@ -257,6 +264,9 @@ class HSCWidget(RenderModeWidget):
     grid.addWidget(helix_profile_label, row, 0, 1, 3)
     grid.addWidget(self.helix_profile_spinbox_, row, 4, 1, 1)
     row+=1
+    grid.addWidget(helix_mode_label, row, 0, 1, 3)
+    grid.addWidget(self.helix_mode_spinbox_, row, 4, 1, 1)
+    row+=1
     grid.addWidget(strand_label, row, 0, 1, 3)
     row+=1
     grid.addWidget(radius_strand_label, row, 0, 1, 1)
@@ -273,6 +283,9 @@ class HSCWidget(RenderModeWidget):
     row+=1
     grid.addWidget(strand_profile_label, row, 0, 1, 3)
     grid.addWidget(self.strand_profile_spinbox_, row, 4, 1, 1)
+    row+=1
+    grid.addWidget(strand_mode_label, row, 0, 1, 3)
+    grid.addWidget(self.strand_mode_spinbox_, row, 4, 1, 1)
     
     grid.setRowStretch(row+1,1)
     self.setLayout(grid)
@@ -294,6 +307,7 @@ class HSCWidget(RenderModeWidget):
     QtCore.QObject.connect(self.ecc_helix_spinbox_, QtCore.SIGNAL("valueChanged(double)"), self.UpdateHelixEcc)
     QtCore.QObject.connect(self.ecc_helix_slider_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateSliderHelixEcc)
     QtCore.QObject.connect(self.helix_profile_spinbox_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateHelixProfileType)
+    QtCore.QObject.connect(self.helix_mode_spinbox_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateHelixMode)
 
     QtCore.QObject.connect(self.width_strand_spinbox_, QtCore.SIGNAL("valueChanged(double)"), self.UpdateStrandWidth)
     QtCore.QObject.connect(self.width_strand_slider_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateSliderStrandWidth)
@@ -302,8 +316,9 @@ class HSCWidget(RenderModeWidget):
     QtCore.QObject.connect(self.ecc_strand_spinbox_, QtCore.SIGNAL("valueChanged(double)"), self.UpdateStrandEcc)
     QtCore.QObject.connect(self.ecc_strand_slider_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateSliderStrandEcc)    
     QtCore.QObject.connect(self.strand_profile_spinbox_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateStrandProfileType)
+    QtCore.QObject.connect(self.strand_mode_spinbox_, QtCore.SIGNAL("valueChanged(int)"), self.UpdateStrandMode)
     
-    self.setMinimumSize(250,420) #14*30
+    self.setMinimumSize(250,550)
     ########/UI########
   
   def UpdateGui(self,options):
@@ -318,10 +333,12 @@ class HSCWidget(RenderModeWidget):
     self.UpdateHelixThicknessGui(options.GetHelixThickness())
     self.UpdateHelixEccGui(options.GetHelixEcc())
     self.helix_profile_spinbox_.setValue(options.GetHelixProfileType())
+    self.helix_mode_spinbox_.setValue(options.GetHelixMode())
     self.UpdateStrandWidthGui(options.GetStrandWidth())
     self.UpdateStrandThicknessGui(options.GetStrandThickness())
     self.UpdateStrandEccGui(options.GetStrandEcc())
     self.strand_profile_spinbox_.setValue(options.GetStrandProfileType())
+    self.strand_mode_spinbox_.setValue(options.GetStrandMode())
     
   def UpdatePolyMode(self, value):
     self.GetOptions().SetPolyMode(value)
@@ -378,6 +395,10 @@ class HSCWidget(RenderModeWidget):
   def UpdateHelixProfileType(self, value):
     self.GetOptions().SetHelixProfileType(value)
     self.ApplyOptions()
+
+  def UpdateHelixMode(self, value):
+    self.GetOptions().SetHelixMode(value)
+    self.ApplyOptions()
     
   def UpdateSliderHelixEcc(self, value):
     self.GetOptions().SetHelixEcc(value/10.0)
@@ -411,6 +432,10 @@ class HSCWidget(RenderModeWidget):
     self.GetOptions().SetStrandProfileType(value)
     self.ApplyOptions()
     
+  def UpdateStrandMode(self, value):
+    self.GetOptions().SetStrandMode(value)
+    self.ApplyOptions()
+    
   def UpdateTubeRadiusGui(self,value):
     if(abs(value*10.0 - self.width_tube_slider_.value())>=self.width_tube_spinbox_.singleStep()):
       self.width_tube_slider_.setValue(value*10.0)
diff --git a/modules/gui/pymod/scene/init_inspector.py b/modules/gui/pymod/scene/init_inspector.py
index 462ef4b3b04121a7d42e11f17c86d0f45262ff11..5bd17ba3db87180376bb62c85df7275ebf07f3a2 100644
--- a/modules/gui/pymod/scene/init_inspector.py
+++ b/modules/gui/pymod/scene/init_inspector.py
@@ -23,28 +23,6 @@ from ost import gui
 from ost import gfx
 from PyQt4 import QtCore, QtGui
 from ost.gui.scene.inspector_widget import InspectorDialog
-
-class InitInspectorMenu(QtCore.QObject):
-  def __init__(self, inspectordialog, menu_bar=None):
-    QtCore.QObject.__init__(self, menu_bar)
-    
-    self.inspector_ = inspectordialog
-    persp=gui.GostyApp.Instance().perspective
-    options=persp.GetMenu("Options")
-    
-    self.show_ = options.addAction("&Inspector gadget")
-    self.show_.setShortcut('Ctrl+I')
-    self.show_.setCheckable(True)
-    self.show_.setChecked(not self.inspector_.isHidden())
-    self.connect(self.show_, QtCore.SIGNAL('triggered()'), self.Toggle)
-    self.connect(inspectordialog, QtCore.SIGNAL('visible'), self.UpdateCheckbox)
-  def Toggle(self):
-    self.inspector_.setVisible(not self.inspector_.isVisible())
-  
-  def UpdateCheckbox(self, visibility):
-    self.disconnect(self.show_, QtCore.SIGNAL('triggered()'), self.Toggle)
-    self.show_.setChecked(visibility)
-    self.connect(self.show_, QtCore.SIGNAL('triggered()'), self.Toggle)
   
 def _InitInspector(app):
   mywidget = InspectorDialog(app.gl_win.qobject)
@@ -52,5 +30,4 @@ def _InitInspector(app):
   mywidget.show()
   app.AddWidgetToApp("InspectorDialog", mywidget)  
   menu_bar=app.perspective.GetMenuBar()
-  InitInspectorMenu(mywidget,menu_bar)
 
diff --git a/modules/gui/pymod/scene/preset_list_model.py b/modules/gui/pymod/scene/preset_list_model.py
index 93d7426966a9de19100c4612bed156fb1d966a57..c35aa453f84ae45610933f91edbaea3bed3f0c9a 100644
--- a/modules/gui/pymod/scene/preset_list_model.py
+++ b/modules/gui/pymod/scene/preset_list_model.py
@@ -5,7 +5,7 @@ import ost
 from PyQt4 import QtCore, QtGui
 from immutable_preset_info_handler import ImmutablePresetInfoHandler
 from preset_info_handler import PresetInfoHandler
-
+from PyQt4.QtGui import QDesktopServices
 class PresetListModel(QtCore.QAbstractListModel):
   
   IMMUTABLE_PRESET_PATH = os.path.join(ost.GetSharedDataPath(),"scene", 
@@ -18,8 +18,15 @@ class PresetListModel(QtCore.QAbstractListModel):
     self.data_ = list()
     
     #Info Handler
-    self.immutable_infoh_ = ImmutablePresetInfoHandler(PresetListModel.IMMUTABLE_PRESET_PATH)
-    self.infoh_ = PresetInfoHandler(PresetListModel.MUTABLE_PRESET_PATH)
+
+    self.immutable_infoh_=ImmutablePresetInfoHandler(PresetListModel.IMMUTABLE_PRESET_PATH)
+    data_loc=QDesktopServices.storageLocation(QDesktopServices.DataLocation)    
+    mutable_path=os.path.join(str(data_loc), 'config',
+                              PresetListModel.MUTABLE_PRESET_PATH)
+    qdir=QtCore.QDir(data_loc)
+    if not qdir.exists():
+      qdir.mkpath("config")
+    self.infoh_=PresetInfoHandler(mutable_path)
     self.LoadPresetsFromInfo()
     
   def AddItem(self, preset, row, editable, save):
diff --git a/modules/gui/share/CMakeLists.txt b/modules/gui/share/CMakeLists.txt
index c87f561e8eb50e4a7743063d3b70d090280f24e1..816af7f807240d1d363ada12768a7d9d6c8f1f37 100644
--- a/modules/gui/share/CMakeLists.txt
+++ b/modules/gui/share/CMakeLists.txt
@@ -15,6 +15,7 @@ set(GUI_ICONS
   icons/site_icon.png
   icons/split_icon.png
   icons/warning_icon.png
+  icons/refresh.png
 )
 
 set(GUI_IMAGES
diff --git a/modules/gui/share/icons/refresh.png b/modules/gui/share/icons/refresh.png
new file mode 100644
index 0000000000000000000000000000000000000000..fd205a1a14d9756aa7d0f0746210ad171ccf7a32
Binary files /dev/null and b/modules/gui/share/icons/refresh.png differ
diff --git a/modules/gui/src/CMakeLists.txt b/modules/gui/src/CMakeLists.txt
index 1a5104a0ae28d8670eb8887fa8c3c85f4567c1ae..9ec4e834bd6b27991a71da94ca7e61d439ccfa44 100644
--- a/modules/gui/src/CMakeLists.txt
+++ b/modules/gui/src/CMakeLists.txt
@@ -453,7 +453,8 @@ module(NAME gui SOURCES ${OST_GUI_MOCS} ${OST_GUI_SOURCES}
                ${OST_GUI_HEADERS}
        DEPENDS_ON gfx io mol_alg seq_alg
        LINK ${QT_LIBRARIES} ${PYTHON_LIBRARIES} ${BOOST_PYTHON_LIBRARIES}
-            ${SPNAV_LIBRARIES})
+            ${SPNAV_LIBRARIES}
+        NO_STATIC)
             
 if (ADDITIONAL_LIBRARIES)
   target_link_libraries(ost_gui "${ADDITIONAL_LIBRARIES}")
diff --git a/modules/gui/src/file_browser.cc b/modules/gui/src/file_browser.cc
index ca7092684382517d25fdc7128b215e05f147ee4f..db12c019d0dd12a0209eeb4a6c7191d6e7f2f9da 100644
--- a/modules/gui/src/file_browser.cc
+++ b/modules/gui/src/file_browser.cc
@@ -112,7 +112,8 @@ void FileBrowser::Init(const QString& path)
   view_->setRootIndex(model_->index(path));
   view_->setAttribute(Qt::WA_MacShowFocusRect, false);
   view_->setContextMenuPolicy(Qt::CustomContextMenu);
-  connect(view_,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(ShowContextMenu(const QPoint&)));
+  connect(view_,SIGNAL(customContextMenuRequested(const QPoint&)),this,
+          SLOT(ShowContextMenu(const QPoint&)));
   UpdateMenu(path);
 
   QVBoxLayout* l=new QVBoxLayout(this);
@@ -138,9 +139,19 @@ void FileBrowser::Init(const QString& path)
   split_action->setToolTip("Split File Browser");
   split_action->setIcon(QIcon(icon_path.absolutePath()+QDir::separator()+QString("split_icon.png")));
   action_list_.append(split_action);
+  connect(split_action, SIGNAL(triggered(bool)), this, SLOT(Split()));  
+  QAction* refresh_action=new QAction(this);
+  refresh_action->setText("refresh");
+  refresh_action->setIcon(QIcon(icon_path.absolutePath()+QDir::separator()+QString("refresh.png")));
+  action_list_.append(refresh_action);
+  connect(refresh_action, SIGNAL(triggered(bool)), this, SLOT(Refresh()));
+}
 
-  connect(split_action, SIGNAL(triggered(bool)), this, SLOT(Split()));
+void FileBrowser::Refresh()
+{
+  model_->refresh();
 }
+
 ActionList FileBrowser::GetActions()
 {
   return action_list_;
diff --git a/modules/gui/src/file_browser.hh b/modules/gui/src/file_browser.hh
index 902291746cb23d08703ec670b33eedd8a10f78aa..219e5564bc06e30c7b13b19855ffd8fcaed23cfe 100644
--- a/modules/gui/src/file_browser.hh
+++ b/modules/gui/src/file_browser.hh
@@ -45,7 +45,8 @@ public:
 
 protected:
   virtual void keyPressEvent(QKeyEvent* event);
-
+public slots:
+  void Refresh();
 private slots:
   void Init(const QString& path);
   void DoubleClicked(const QModelIndex& index);
diff --git a/modules/gui/src/file_loader.cc b/modules/gui/src/file_loader.cc
index a874742bce365399da8a5c89328fd2d19436a1e3..74b4f240f8168bf910daaf7d9089dea722544314 100644
--- a/modules/gui/src/file_loader.cc
+++ b/modules/gui/src/file_loader.cc
@@ -45,9 +45,10 @@
 #include <ost/gui/sequence_viewer/sequence_viewer.hh>
 
 #if OST_IMG_ENABLED
-  #include <ost/io/img/load_map.hh>
-  #include <ost/gfx/map_iso.hh>
-  #include <ost/img/extent.hh>
+#  include <ost/io/img/load_map.hh>
+#  include <ost/gfx/map_iso.hh>
+#  include <ost/img/extent.hh>
+#  include <ost/gui/data_viewer/data_viewer.hh>
 #endif
 
 #include <QDir>
@@ -132,21 +133,24 @@ void FileLoader::AddToScene(const QString& filename, gfx::GfxObjP obj)
 
 gfx::GfxObjP FileLoader::NoHandlerFound(const QString& filename)
 {
-  FileTypeDialog dialog(filename);
+  /// FIXME: This currently leaks! I haven't found a way to allocate the dialog 
+  /// on the stack without crashing the program.
+  /// This is BZDNG-192
+  FileTypeDialog* dialog=new FileTypeDialog(filename);
   try{
-    if(dialog.exec()){
-      if(dialog.GetEntityHandler()){
-        return TryLoadEntity(filename, dialog.GetEntityHandler());
+    if(dialog->exec()){
+      if(dialog->GetEntityHandler()){
+        return TryLoadEntity(filename, dialog->GetEntityHandler());
       }
-      if(dialog.GetSequenceHandler()){
-        return TryLoadAlignment(filename, dialog.GetSequenceHandler());
+      if(dialog->GetSequenceHandler()){
+        return TryLoadAlignment(filename, dialog->GetSequenceHandler());
       }
-      if(dialog.GetSurfaceHandler()){
-        return TryLoadSurface(filename,dialog.GetSurfaceHandler());
+      if(dialog->GetSurfaceHandler()){
+        return TryLoadSurface(filename,dialog->GetSurfaceHandler());
       }
   #if OST_IMG_ENABLED
-      if(dialog.GetMapHandler()){
-        return TryLoadMap(filename,dialog.GetMapHandler());
+      if(dialog->GetMapHandler()){
+        return TryLoadMap(filename,dialog->GetMapHandler());
       }
   #endif
     }
@@ -245,13 +249,14 @@ gfx::GfxObjP FileLoader::TryLoadEntity(const QString& filename, io::EntityIOHand
     else{
       QFileInfo file_info(filename);
       mol::EntityHandle eh=mol::CreateEntity();
-      mol::XCSEditor xcs_lock=eh.RequestXCSEditor(mol::BUFFERED_EDIT);
+      mol::XCSEditor xcs_lock=eh.EditXCS(mol::BUFFERED_EDIT);
       handler->Import(eh,filename.toStdString());
       if(handler->RequiresBuilder()) {
           conop::BuilderP builder = conop::Conopology::Instance().GetBuilder();
           conop::Conopology::Instance().ConnectAll(builder,eh,0);
       }
-      gfx::GfxObjP obj(new gfx::Entity(file_info.baseName().toStdString(),eh,mol::Query(selection.toStdString())));
+      gfx::GfxObjP obj(new gfx::Entity(file_info.baseName().toStdString(),
+                       eh, mol::Query(selection.toStdString())));
       return obj;
     }
   }
@@ -367,7 +372,8 @@ void FileLoader::RunScript(const QString& filename)
   pi.RunCommand("sys.argv.append('"+QFileInfo(filename).fileName()+"')");
   pi.RunCommand("_dir=os.getcwd()");
   pi.RunCommand("os.chdir('"+QFileInfo(filename).absolutePath()+"')");
-  pi.RunCommand("execfile('"+QFileInfo(filename).fileName()+"')");
+  pi.RunScript(QFileInfo(filename).absoluteFilePath());
+  //pi.RunCommand("execfile('"+QFileInfo(filename).fileName()+"')");
   pi.RunCommand("os.chdir(_dir)");
   pi.RunCommand("del(_dir)");
   pi.RunCommand("sys.argv=_sys_argv_backup");
@@ -377,7 +383,7 @@ void FileLoader::RunScript(const QString& filename)
 
 void FileLoader::LoadPDB(const QString& filename, const QString& selection)
 {
-  io::PDBReader reader(filename.toStdString());
+  io::PDBReader reader(filename.toStdString(), io::IOProfile());
   QList<mol::EntityHandle> entities;
   conop::BuilderP builder=conop::Conopology::Instance().GetBuilder("DEFAULT");
   while (reader.HasNext()){
diff --git a/modules/gui/src/file_type_dialog.cc b/modules/gui/src/file_type_dialog.cc
index caf11bc83b38de6232557828feb57da9cd1e93cb..d0a45602eefe595d68d1de5e91e3e4f1b1fb804a 100644
--- a/modules/gui/src/file_type_dialog.cc
+++ b/modules/gui/src/file_type_dialog.cc
@@ -29,6 +29,75 @@
 #include <QHeaderView>
 namespace ost { namespace gui {
 
+
+namespace {
+
+class FileTypeList : public QTableWidget {
+public:
+  FileTypeList(QWidget* parent=NULL): QTableWidget(parent)
+  {
+    this->setShowGrid(false);
+    this->horizontalHeader()->setStretchLastSection(true);
+    this->setColumnCount(2);
+    this->setAttribute(Qt::WA_MacSmallSize);
+    this->verticalHeader()->setVisible(false);
+    this->horizontalHeader()->setVisible(false);
+    this->setSelectionBehavior(QAbstractItemView::SelectRows);
+    this->setSelectionMode(QAbstractItemView::SingleSelection); 
+    io::EntityIOHFList entity_handler = io::IOManager::Instance().GetAvailableEntityHandler();
+    for(unsigned int i = 0 ; i < entity_handler.size() ; i++){
+      QVariant handler = QVariant();
+      handler.setValue(entity_handler[i]);
+      this->AddRow(this->rowCount(),entity_handler[i]->GetFormatName().c_str(),entity_handler[i]->GetFormatDescription().c_str(),handler);
+    }
+
+    io::AlignmentIOFList alignment_handler = io::IOManager::Instance().GetAvailableAlignmentHandler();
+    for(unsigned int i = 0 ; i < alignment_handler.size() ; i++){
+      QVariant handler = QVariant();
+      handler.setValue(alignment_handler[i]);
+      this->AddRow(this->rowCount(),alignment_handler[i]->GetFormatName().c_str(),alignment_handler[i]->GetFormatDescription().c_str(),handler);
+    }
+
+#if OST_IMG_ENABLED
+    io::MapIOFList map_handler = io::IOManager::Instance().GetAvailableMapHandler();
+    for(unsigned int i = 0 ; i < map_handler.size() ; i++){
+      QVariant handler = QVariant();
+      handler.setValue(map_handler[i]);
+      this->AddRow(this->rowCount(),map_handler[i]->GetFormatName().c_str(),map_handler[i]->GetFormatDescription().c_str(),handler);
+    }
+#endif
+
+    io::SurfaceIOFList surf_handler = io::IOManager::Instance().GetAvailableSurfaceHandler();
+    for(unsigned int i = 0 ; i < surf_handler.size() ; i++){
+      QVariant handler = QVariant();
+      handler.setValue(surf_handler[i]);
+      this->AddRow(this->rowCount(),surf_handler[i]->GetFormatName().c_str(),surf_handler[i]->GetFormatDescription().c_str(),handler);
+    }
+  }
+  
+  virtual void mouseDoubleClickEvent(QMouseEvent* event)
+  {
+    QTableWidget::mouseDoubleClickEvent(event);
+    dynamic_cast<QDialog*>(parent())->accept();
+  }
+  
+  void AddRow(int row, const QString& format_name, const QString& format_descr, 
+              QVariant& variant)
+  {
+    this->insertRow(row);
+    QTableWidgetItem* new_item = new QTableWidgetItem(format_name);
+    new_item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
+    new_item->setData(Qt::UserRole,variant);
+    this->setItem(row, 0, new_item);
+    new_item = new QTableWidgetItem(format_descr);
+    new_item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
+    this->setItem(row, 1, new_item);
+  }
+};
+
+}
+
+
 FileTypeDialog::FileTypeDialog(const QString& file_name, QWidget* parent):
   QDialog(parent),entity_handler_(),seq_handler_(), surf_handler_()
 #if OST_IMG_ENABLED
@@ -41,16 +110,9 @@ FileTypeDialog::FileTypeDialog(const QString& file_name, QWidget* parent):
   label_ = new QLabel("The file format could not be recognized, "
                       "please select the type of the file from the list:");
   label_->setWordWrap(true);
-  list_ = new QTableWidget(this);
-  list_->setShowGrid(false);
-  list_->horizontalHeader()->setStretchLastSection(true);
-  list_->setColumnCount(2);
-  list_->setAttribute(Qt::WA_MacSmallSize);
-  list_->verticalHeader()->setVisible(false);
-  list_->horizontalHeader()->setVisible(false);
-  list_->setSelectionBehavior(QAbstractItemView::SelectRows);
-  list_->setSelectionMode(QAbstractItemView::SingleSelection);
-  QHBoxLayout* hb=new QHBoxLayout();  
+  list_ = new FileTypeList(this);
+
+  QHBoxLayout* hb=new QHBoxLayout;  
   vb->addWidget(label_);
   vb->addWidget(list_);
   hb->setDirection(QBoxLayout::LeftToRight);
@@ -63,52 +125,11 @@ FileTypeDialog::FileTypeDialog(const QString& file_name, QWidget* parent):
   load_btn->setDefault(true);
   connect(load_btn, SIGNAL(clicked()), this, SLOT(accept()));
   connect(cancel_btn, SIGNAL(clicked()), this, SLOT(reject()));
-
-  io::EntityIOHFList entity_handler = io::IOManager::Instance().GetAvailableEntityHandler();
-  for(unsigned int i = 0 ; i < entity_handler.size() ; i++){
-    QVariant handler = QVariant();
-    handler.setValue(entity_handler[i]);
-    this->AddRow(list_->rowCount(),entity_handler[i]->GetFormatName().c_str(),entity_handler[i]->GetFormatDescription().c_str(),handler);
-  }
-
-  io::AlignmentIOFList alignment_handler = io::IOManager::Instance().GetAvailableAlignmentHandler();
-  for(unsigned int i = 0 ; i < alignment_handler.size() ; i++){
-    QVariant handler = QVariant();
-    handler.setValue(alignment_handler[i]);
-    this->AddRow(list_->rowCount(),alignment_handler[i]->GetFormatName().c_str(),alignment_handler[i]->GetFormatDescription().c_str(),handler);
-  }
-
-#if OST_IMG_ENABLED
-  io::MapIOFList map_handler = io::IOManager::Instance().GetAvailableMapHandler();
-  for(unsigned int i = 0 ; i < map_handler.size() ; i++){
-    QVariant handler = QVariant();
-    handler.setValue(map_handler[i]);
-    this->AddRow(list_->rowCount(),map_handler[i]->GetFormatName().c_str(),map_handler[i]->GetFormatDescription().c_str(),handler);
-  }
-#endif
-
-  io::SurfaceIOFList surf_handler = io::IOManager::Instance().GetAvailableSurfaceHandler();
-  for(unsigned int i = 0 ; i < surf_handler.size() ; i++){
-    QVariant handler = QVariant();
-    handler.setValue(surf_handler[i]);
-    this->AddRow(list_->rowCount(),surf_handler[i]->GetFormatName().c_str(),surf_handler[i]->GetFormatDescription().c_str(),handler);
-  }
-
   list_->resizeColumnsToContents();
 }
 
-void FileTypeDialog::AddRow(int row, const QString& format_name, const QString& format_descr, QVariant& variant){
-  list_->insertRow(row);
-  QTableWidgetItem* new_item = new QTableWidgetItem(format_name);
-  new_item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
-  new_item->setData(Qt::UserRole,variant);
-  list_->setItem(row, 0, new_item);
-  new_item = new QTableWidgetItem(format_descr);
-  new_item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
-  list_->setItem(row, 1, new_item);
-}
-
-void FileTypeDialog::accept(){
+void FileTypeDialog::accept()
+{
   QList<QTableWidgetItem*> items = list_->selectedItems();
   for(int i=0; i<items.size();i++){
     if(items[i]->column()==0){
@@ -137,7 +158,7 @@ void FileTypeDialog::accept(){
 #endif
     }
   }
-  this->QDialog::accept();
+  QDialog::accept();
 }
 
 io::EntityIOHandlerP FileTypeDialog::GetEntityHandler(){
diff --git a/modules/gui/src/file_type_dialog.hh b/modules/gui/src/file_type_dialog.hh
index 2ce157556ddd2a9623b80417e9d2e48f1fc48d58..b711cbe2233d6d15ff8c551098913b1e1f6aae15 100644
--- a/modules/gui/src/file_type_dialog.hh
+++ b/modules/gui/src/file_type_dialog.hh
@@ -20,7 +20,7 @@
 #define OST_GUI_FILE_TYPE_DIALOG_HH
 
 /*
-  Author: Stefan Scheuber
+  Author: Stefan Scheuber, Marco Biasini
  */
 
 #include <ost/gui/module_config.hh>
@@ -51,14 +51,9 @@ public:
 #if OST_IMG_ENABLED
   io::MapIOHandlerPtr GetMapHandler();
 #endif
-
 public slots:
-  virtual void accept ();
-
+  virtual void accept();
 private:
-  void AddRow(int row, const QString& format_name, const QString& format_descr, QVariant& variant);
-
-
   QTableWidget* list_;
   QLabel* label_;
   io::EntityIOHandlerP entity_handler_;
diff --git a/modules/gui/src/gl_canvas.cc b/modules/gui/src/gl_canvas.cc
index e2029930c70560bd144d4cc3d708923403ad2d70..d1a7aa9b89c9c75b93e837cd48047b6339fedf1f 100644
--- a/modules/gui/src/gl_canvas.cc
+++ b/modules/gui/src/gl_canvas.cc
@@ -39,6 +39,10 @@
 #include <QApplication>
 #include <QClipboard>
 #include <QMenu>
+
+#if QT_VERSION >= 0x040600
+# include <QGesture>
+#endif
 #include "tools/tool_manager.hh"
 
 namespace ost { namespace gui {
@@ -47,20 +51,70 @@ using gfx::Scene;
 
 GLCanvas::GLCanvas(GLWin* gl_win,  QWidget* parent, const QGLFormat& f):
   QGLWidget(f,parent),
-  glwin_(gl_win)
+  glwin_(gl_win),
+  mouse_key_mask_(),
+  refresh_(true),
+  master_timer_(),
+  bench_flag_(false),
+  last_pos_(),
+  scene_menu_(NULL),
+  show_beacon_(false),
+  angular_speed_(0.0)
 {
   if(!isValid()) return;
-  refresh_=true;
   master_timer_.start(10,this);
   setFocusPolicy(Qt::StrongFocus);
-  bench_flag_=false;
-  setMouseTracking(false);
+  setMouseTracking(true);
   scene_menu_=new SceneMenu();
   this->setContextMenuPolicy(Qt::CustomContextMenu);
   connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this,
           SLOT(RequestContextMenu(const QPoint&)));
+#if QT_VERSION >= 0x040600
+  this->grabGesture(Qt::PinchGesture);
+#endif
+}
+
+bool GLCanvas::event(QEvent* event)
+{
+#if QT_VERSION >= 0x040600
+  if (event->type()==QEvent::Gesture) {
+    return this->GestureEvent(static_cast<QGestureEvent*>(event));
+  }
+#endif
+  return QGLWidget::event(event);
 }
 
+
+#if QT_VERSION >= 0x040600
+
+bool GLCanvas::GestureEvent(QGestureEvent* event)
+{
+  if (QGesture* pinch=event->gesture(Qt::PinchGesture)) {
+    QPinchGesture* pinch_gesture=static_cast<QPinchGesture*>(pinch);
+    QPinchGesture::ChangeFlags changeFlags = pinch_gesture->changeFlags();
+    if (changeFlags & QPinchGesture::RotationAngleChanged) {
+      qreal value=pinch_gesture->rotationAngle();
+      qreal lastValue=pinch_gesture->lastRotationAngle();
+      this->OnTransform(gfx::INPUT_COMMAND_ROTZ, 0, gfx::TRANSFORM_VIEW, 
+                  static_cast<Real>(value - lastValue));
+      this->update();
+      event->accept();
+      if (pinch_gesture->state()==Qt::GestureFinished) {
+        angular_speed_=value-lastValue;
+        if (!gesture_timer_.isActive())
+          gesture_timer_.start(10, this);
+      }
+      return true;
+    }
+  }
+  return false;
+}
+
+#endif
+
+
+
+
 void GLCanvas::MakeActive()
 {
   makeCurrent();
@@ -76,13 +130,6 @@ void GLCanvas::StatusMessage(const String& m)
   glwin_->StatusMessage(m);
 }
 
-void GLCanvas::SetStereo(bool s)
-{
-  QGLFormat f=this->format();
-  f.setStereo(s);
-  this->setFormat(f);
-}
-
 void GLCanvas::OnTransform(gfx::InputCommand com, int indx, 
                            gfx::TransformTarget trg, Real val)
 {
@@ -136,6 +183,9 @@ MouseEvent::Buttons GLCanvas::TranslateButtons(Qt::MouseButtons buttons) const
   
 void GLCanvas::mouseMoveEvent(QMouseEvent* event)
 {
+  if (!(show_beacon_ || event->buttons())) {
+    return;
+  }
   if (this->IsToolEvent(event)) {
     if (ToolManager::Instance().GetActiveTool()) {
       MouseEvent mouse_event(this->TranslateButtons(event->buttons()), 
@@ -165,7 +215,7 @@ void GLCanvas::mousePressEvent(QMouseEvent* event)
     this->HandleMousePressEvent(event);
   }
   last_pos_=QPoint(event->x(), event->y());
-  this->DoRefresh();  
+  this->DoRefresh();
 }
 
 void GLCanvas::mouseReleaseEvent(QMouseEvent* event)
@@ -183,7 +233,7 @@ void GLCanvas::mouseReleaseEvent(QMouseEvent* event)
     }
   }
   last_pos_=QPoint(event->x(), event->y());
-  this->DoRefresh();  
+  this->DoRefresh();
 }
 
 void GLCanvas::mouseDoubleClickEvent(QMouseEvent* event)
@@ -205,7 +255,9 @@ void GLCanvas::mouseDoubleClickEvent(QMouseEvent* event)
       scene.SetCenter(atom.GetPos());
     }
   }
-  this->DoRefresh();  
+  if (show_beacon_) {
+    this->DoRefresh();
+  }
 }
 
 void GLCanvas::RequestContextMenu(const QPoint& pos)
@@ -232,6 +284,10 @@ void GLCanvas::HandleMouseMoveEvent(QMouseEvent* event)
   int indx=0;
   gfx::TransformTarget trg=gfx::TRANSFORM_VIEW;  
 
+  if(show_beacon_) {
+    Scene::Instance().SetBeacon(event->x(),size().height()-event->y());
+  }
+
   QPoint delta=QPoint(event->x(), event->y())-last_pos_;
   if (event->buttons() & Qt::LeftButton) {
     if (event->buttons() & Qt::MidButton) {
@@ -327,6 +383,12 @@ void GLCanvas::CopySelectionToClipboard()
 
 void GLCanvas::keyPressEvent(QKeyEvent* event)
 {
+  if(event->key()==Qt::Key_Space) {
+    show_beacon_=true;
+    Scene::Instance().SetBeacon(last_pos_.x(),size().height()-last_pos_.y());
+    DoRefresh();
+    setCursor(Qt::BlankCursor);
+  }
   if((event->modifiers() & Qt::ControlModifier)) {
     // Ctrl pressed
     if(event->key()==Qt::Key_A) {
@@ -342,35 +404,43 @@ void GLCanvas::keyPressEvent(QKeyEvent* event)
       this->CopySelectionToClipboard();
       return;
     } else if(event->key()==Qt::Key_1) {
-      gfx::Scene::Instance().ActivateShader("");
+      gfx::Scene::Instance().SetShadingMode("fallback");
       DoRefresh();
       return;
     } else if(event->key()==Qt::Key_2) {
-      gfx::Scene::Instance().ActivateShader("basic");
+      gfx::Scene::Instance().SetShadingMode("basic");
       DoRefresh();
       return;
     } else if(event->key()==Qt::Key_3) {
-      gfx::Scene::Instance().ActivateShader("fraglight");
+      gfx::Scene::Instance().SetShadingMode("default");
       DoRefresh();
       return;
     } else if(event->key()==Qt::Key_4) {
-      gfx::Scene::Instance().ActivateShader("basic_shadow");
+      gfx::Scene::Instance().SetShadingMode("hf");
       DoRefresh();
       return;
     } else if(event->key()==Qt::Key_5) {
-      gfx::Scene::Instance().ActivateShader("fraglight_shadow");
+      gfx::Scene::Instance().SetShadingMode("toon1");
       DoRefresh();
       return;
     } else if(event->key()==Qt::Key_6) {
-      gfx::Scene::Instance().ActivateShader("hemilight");
+      gfx::Scene::Instance().SetShadingMode("toon2");
       DoRefresh();
       return;
-    } else if(event->key()==Qt::Key_7) {
-      gfx::Scene::Instance().ActivateShader("toon");
+    } else if(event->key()==Qt::Key_0) {
+      gfx::Scene::Instance().SetShadow(!gfx::Scene::Instance().GetShadow());
       DoRefresh();
       return;
-    } else if(event->key()==Qt::Key_8) {
-      gfx::Scene::Instance().ActivateShader("toon2");
+    } else if(event->key()==Qt::Key_9) {
+      gfx::Scene::Instance().SetAmbientOcclusion(!gfx::Scene::Instance().GetAmbientOcclusion());
+      DoRefresh();
+      return;
+    } else if(event->key()==Qt::Key_Equal) {
+      if(gfx::Scene::Instance().GetStereoMode()>0) {
+        gfx::Scene::Instance().SetStereoMode(0);
+      } else {
+        gfx::Scene::Instance().SetStereoMode(1);
+      }
       DoRefresh();
       return;
     }    
@@ -380,6 +450,13 @@ void GLCanvas::keyPressEvent(QKeyEvent* event)
 
 void GLCanvas::keyReleaseEvent(QKeyEvent* event)
 {
+  if(event->key()==Qt::Key_Space) {
+    show_beacon_=false;
+    Scene::Instance().SetBeaconOff();
+    DoRefresh();
+    setCursor(Qt::ArrowCursor);
+    return;
+  }
   if(event->key()==Qt::Key_Alt){
     emit ReleaseFocus();
     return;
@@ -397,6 +474,22 @@ Real delta_time(const timeval& t1, const timeval& t2)
 void GLCanvas::timerEvent(QTimerEvent * event)
 {
 
+#if QT_VERSION>= 0x040600
+  // gesture support
+  if (gesture_timer_.timerId()==event->timerId()) {
+    if (angular_speed_!=0.0) {
+      angular_speed_*=0.95;
+      this->OnTransform(gfx::INPUT_COMMAND_ROTZ, 0, gfx::TRANSFORM_VIEW, 
+                        static_cast<Real>(angular_speed_));
+      if (std::abs(angular_speed_)<0.001) {
+        angular_speed_=0.0;
+        gesture_timer_.stop();
+      }
+      this->update();
+    }
+    return;
+  }
+#endif
 #ifndef _MSC_VER
   static struct timeval time0,time1;
   static int count=0;
diff --git a/modules/gui/src/gl_canvas.hh b/modules/gui/src/gl_canvas.hh
index 82e25436c772644347cc28d834bfe4da41256504..db41234df1445d7cfda4de7f4dfc899cbcbd1970 100644
--- a/modules/gui/src/gl_canvas.hh
+++ b/modules/gui/src/gl_canvas.hh
@@ -54,7 +54,7 @@ public:
   virtual void MakeActive();
   virtual void DoRefresh();
   virtual void StatusMessage(const String& m);
-  virtual void SetStereo(bool s);
+  virtual bool HasStereo() const {return format().stereo();};
   virtual bool HasMultisample() const {return format().sampleBuffers();}
 
   // central point for sending input to the gfx layer
@@ -83,11 +83,14 @@ protected:
   virtual void keyReleaseEvent(QKeyEvent* event);
   virtual void timerEvent(QTimerEvent * event);
   virtual void wheelEvent(QWheelEvent* event);
-
+  virtual bool event(QEvent* event);
 private slots:
   virtual void RequestContextMenu(const QPoint& pos);
 
 private:
+#if QT_VERSION >= 0x040600  
+  bool GestureEvent(QGestureEvent* event);
+#endif
   bool IsToolEvent(QInputEvent* event) const;
   MouseEvent::Buttons TranslateButtons(Qt::MouseButtons buttons) const;
   void HandleMousePressEvent(QMouseEvent* event);
@@ -102,6 +105,11 @@ private:
   bool bench_flag_;
   QPoint last_pos_;
   SceneMenu* scene_menu_;
+  bool show_beacon_;
+  float angular_speed_;
+#if QT_VERSION>=0x04600
+  QBasicTimer gesture_timer_;
+#endif
 };
 
 }} // ns
diff --git a/modules/gui/src/gl_win.cc b/modules/gui/src/gl_win.cc
index 7f4f668d612ed443e304436fe27428665420decc..c2f544d7bb9613b4cb2312bcbad43a194bc2cb90 100644
--- a/modules/gui/src/gl_win.cc
+++ b/modules/gui/src/gl_win.cc
@@ -27,6 +27,9 @@
 #include <ost/gui/tools/manipulator.hh>
 #include <ost/gui/tools/measure_tool.hh>
 #include <ost/gui/perspective.hh>
+#include <ost/gui/gl_canvas.hh>
+#include <ost/gui/tools/tool.hh>
+#include <ost/gui/tools/tool_bar.hh>
 
 #if OST_IMG_ENABLED
 #  include <ost/gui/tools/map_tool.hh>
@@ -46,36 +49,64 @@
 
 namespace ost { namespace gui {
 
-GLWin::GLWin(QWidget* p):
-  Widget(NULL, p), 
-  gl_canvas_(NULL)
+GLWin::GLWin(QWidget* p, bool try_stereo):
+Widget(NULL, p), 
+gl_canvas_(NULL)
 {
   QMainWindow* main=new QMainWindow;
-  for(int format_id=2;format_id>=0;--format_id) {
-    gl_canvas_=new GLCanvas(this, main, GLWin::CreateFormat(format_id));
-    if(gl_canvas_->isValid()) {
-      break; // format is fine
-    } else {
-      delete gl_canvas_; // delete this canvas and try a less sophisticated format
+  
+  if(try_stereo) {
+    LOG_VERBOSE("GLCanvas: trying stereo visuals first");
+    for(int format_id=3;format_id>=0;--format_id) {
+      QGLFormat format=GLWin::CreateFormat(format_id);
+      if (try_stereo) {
+        format.setStereo(true);
+      }
+      gl_canvas_=new GLCanvas(this, main, format);
+      if(gl_canvas_->isValid() && gl_canvas_->format().stereo()) {
+        break; // format is fine
+      } else {
+        delete gl_canvas_; // delete this canvas and try a less sophisticated format
+        gl_canvas_=0;
+      }
+    }
+  }
+  if(!gl_canvas_) {
+    if(try_stereo) {
+      LOG_VERBOSE("GLCanvas: no stereo visual found, trying normal ones");
+    }
+    for(int format_id=3;format_id>=0;--format_id) {
+      QGLFormat format=GLWin::CreateFormat(format_id);
+      gl_canvas_=new GLCanvas(this, main, format);
+      if(gl_canvas_->isValid()) {
+        break; // format is fine
+      } else {
+        delete gl_canvas_; // delete this canvas and try a less sophisticated format
+        gl_canvas_=0;
+      }
     }
   }
 
-  if(!gl_canvas_->isValid()) {
-    LOG_ERROR("no valid GL context found, GL canvas could not be created");
+  if(!gl_canvas_ || !gl_canvas_->isValid()) {
+    LOG_ERROR("GLCanvas: no valid GL context found, this is pretty fatal");
     return;
   }
 
   this->SetInternalWidget(main);
   gfx::Scene::Instance().AttachObserver(this);
   QGLFormat format = gl_canvas_->format();
-  LOG_VERBOSE("GLCanvas created with rbits=" << format.redBufferSize() 
-              << " gbits=" << format.greenBufferSize() 
-              << " bbits=" << format.blueBufferSize() 
-              << " abits=" << format.alphaBufferSize() 
-              << " dbits=" << format.depthBufferSize()
-              << " accumbits=" << format.accumBufferSize()
-              << " multisample=" << format.sampleBuffers()
-              << " with samples=" << format.samples());
+
+  LOG_DEBUG("GLCanvas: rbits=" << format.redBufferSize() 
+               << " gbits=" << format.greenBufferSize() 
+               << " bbits=" << format.blueBufferSize() 
+               << " abits=" << format.alphaBufferSize() 
+               << " dbits=" << format.depthBufferSize()
+               << " accumbits=" << format.accumBufferSize()
+               << " multisample=" << format.sampleBuffers()
+               << " with samples=" << format.samples());
+  if(gl_canvas_->format().stereo()) {
+    LOG_VERBOSE("GLCanvas: using stereo visual");
+  }
   main->setCentralWidget(gl_canvas_);
   connect(gl_canvas_, SIGNAL(ReleaseFocus()), this, SIGNAL(ReleaseFocus()));
   connect(&ToolManager::Instance(), SIGNAL(ActiveToolChanged(Tool*)), this, SLOT(ActiveToolChanged(Tool*)));
@@ -87,10 +118,6 @@ GLWin::GLWin(QWidget* p):
 #if OST_IMG_ENABLED
   ToolManager::Instance().AddTool(new MapTool);
 #endif
-  QBoxLayout* l=new QVBoxLayout(this);
-  l->setMargin(0);
-  l->setSpacing(0);
-  l->addWidget(main);
 }
 
 void GLWin::ActiveToolChanged(Tool* t)
@@ -101,7 +128,16 @@ void GLWin::ActiveToolChanged(Tool* t)
 QGLFormat GLWin::CreateFormat(int fid)
 {
   QGLFormat format = QGLFormat::defaultFormat();
-  if(fid==2) {
+  if(fid==3) {
+    format.setDepthBufferSize(24);
+    format.setRedBufferSize(8);
+    format.setGreenBufferSize(8);
+    format.setBlueBufferSize(8);
+    format.setAlpha(true);
+    format.setAlphaBufferSize(8);
+    format.setAccum(true);
+    format.setSampleBuffers(true);
+  } else if(fid==2) {
     format.setDepthBufferSize(12);
     format.setRedBufferSize(8);
     format.setGreenBufferSize(8);
diff --git a/modules/gui/src/gl_win.hh b/modules/gui/src/gl_win.hh
index d634e37f41e2756dabe6e498ecd25b958d6f3763..eaaf248af89e93d6df8aa7515c8114e68e15afd3 100644
--- a/modules/gui/src/gl_win.hh
+++ b/modules/gui/src/gl_win.hh
@@ -24,14 +24,9 @@
 
 #include <ost/gui/module_config.hh>
 #include <ost/gui/widget.hh>
-#include <ost/gui/gl_canvas.hh>
 
-#include <ost/gui/tools/tool.hh>
-#include <ost/gui/tools/tool_bar.hh>
-
-#include <QMainWindow>
 #include <QAction>
-
+#include <QGLFormat>
 #include <QActionGroup>
 #include <QStatusBar>
 
@@ -40,11 +35,16 @@
  */
 namespace ost { namespace gui {
 
+
+class GLCanvas;
+class ToolBar;
+class Tool;
+
 class DLLEXPORT_OST_GUI GLWin: public Widget, public gfx::SceneObserver
 {
   Q_OBJECT;
 public:
-  GLWin(QWidget* p);
+  GLWin(QWidget* p, bool try_stereo=false);
   ~GLWin();
   void SetTestMode(bool f);
 
diff --git a/modules/gui/src/gosty_app.cc b/modules/gui/src/gosty_app.cc
index f162d57ffbffa6db3cd319a53c2b317f7dbd5273..342427a11ad9ece9609a12bb8b448c1e7319a6bc 100644
--- a/modules/gui/src/gosty_app.cc
+++ b/modules/gui/src/gosty_app.cc
@@ -25,7 +25,15 @@
 #include <ost/gui/tools/tool_options_win.hh>
 #include <ost/gui/perspective.hh>
 #include <ost/gui/main_area.hh>
+#include <ost/gui/python_shell/python_interpreter.hh>
 
+#include <ost/gui/scene_win/scene_win.hh>
+#include <ost/gui/sequence_viewer/sequence_viewer.hh>
+#include <ost/gui/messages/message_widget.hh>
+
+#if OST_IMG_ENABLED
+  #include <ost/gui/data_viewer/data_viewer.hh>
+#endif
 
 #include <QApplication>
 #include <QMainWindow>
@@ -45,7 +53,8 @@ GostyApp* GostyApp::app_=NULL;
 GostyApp::GostyApp():
   py_shell_(NULL), gl_win_(NULL), scene_win_(NULL), message_widget_(NULL), seq_viewer_(NULL),
   tool_options_win_(NULL), main_(new GostyMainWindow),
-  perspective_(NULL), external_widgets_(QMap<QString,WidgetGeomHandler *>())
+  perspective_(NULL), external_widgets_(QMap<QString,WidgetGeomHandler *>()),
+  try_stereo_(false)
 {
   assert(GostyApp::app_==NULL);
   GostyApp::app_=this;
@@ -95,7 +104,7 @@ SceneWin* GostyApp::GetSceneWin()
 SequenceViewer* GostyApp::GetSequenceViewer()
 {
   if (seq_viewer_==NULL) {
-    seq_viewer_=new SequenceViewer(false);
+    seq_viewer_=new SequenceViewer(false, true);
     seq_viewer_->SetDestroyOnClose(false);
   }
   return seq_viewer_;
@@ -117,10 +126,17 @@ PythonShell* GostyApp::GetPyShell()
   return py_shell_;
 }
 
-GLWin*  GostyApp::GetGLWin()
+
+void GostyApp::StopScript() 
+{
+  PythonInterpreter::Instance().StopScript();
+}
+
+
+GLWin* GostyApp::GetGLWin()
 {
   if (gl_win_==NULL) {
-    gl_win_=new GLWin(main_);
+    gl_win_=new GLWin(main_,try_stereo_);
     gl_win_->SetDestroyOnClose(false);    
   }
   return gl_win_;  
@@ -153,6 +169,14 @@ void GostyApp::AddWidgetToApp(const QString& ident, QWidget* widget)
   external_widgets_[ident]->LoadGeom("ui/external_widgets/");
 }
 
+QWidget* GostyApp::GetWidget(const QString& ident)
+{
+  if (external_widgets_.contains(ident)) {
+    return external_widgets_[ident]->GetWidget();
+  }
+  return NULL;
+}
+
 void GostyApp::RemoveWidgetFromApp(const QString& ident){
   if(external_widgets_.contains(ident)){
     external_widgets_[ident]->SaveGeom("ui/external_widgets/");
diff --git a/modules/gui/src/gosty_app.hh b/modules/gui/src/gosty_app.hh
index fd9b9d2234083ec0102c5333fbc37c14c0de54c6..b419fd7da841965c79c087ab37538fa1fc0da10d 100644
--- a/modules/gui/src/gosty_app.hh
+++ b/modules/gui/src/gosty_app.hh
@@ -28,13 +28,6 @@
 #include <ost/gui/module_config.hh>
 #include <ost/gui/main.hh>
 #include <ost/gui/widget_geom_handler.hh>
-#include <ost/gui/scene_win/scene_win.hh>
-#include <ost/gui/sequence_viewer/sequence_viewer.hh>
-#include <ost/gui/messages/message_widget.hh>
-
-#if OST_IMG_ENABLED
-  #include <ost/gui/data_viewer/data_viewer.hh>
-#endif
 
 
 #include <QObject>
@@ -46,14 +39,30 @@ class QMainWindow;
 class QMdiArea;
 class QWidget;
 
+namespace ost { 
+
+
+// forward declarations
+
+namespace img { 
+
+class Data;
+
+namespace gui { 
+class DataViewer; 
+
+}}  
 
-namespace ost { namespace gui {
+namespace gui {
 
 class PythonShell;
 class GLWin;
 class TextLogger;
 class ToolOptionsWin;
 class Perspective;
+class SequenceViewer;
+class SceneWin;
+class MessageWidget;
 
 /// The gosty app serves as a GUI Manager. It distinguishes between two types of
 /// windows: Windows that can only exist once (singletons) and windows with 
@@ -82,7 +91,7 @@ public:
   /// The GL window is initialized when this method is first called. All 
   /// subsequent calls will return the same GLWin instance.
   GLWin* GetGLWin();
-  
+
   /// \brief get scene menu
   /// 
   /// The scene menu window is initialized when this method is first called. All 
@@ -107,6 +116,11 @@ public:
   /// All subsequent calls will return the same MessageWidget instance.
   MessageWidget* GetMessageWidget();
 
+  /// \brief stop script execution
+  ///
+  /// Stops the execution of the script.
+  void StopScript(); 
+
 #if OST_IMG_ENABLED
   /// \brief create new DataViewer
   /// 
@@ -130,7 +144,8 @@ public:
   /// \param ident the ident is used to identify a custom widget. It must be unique. Otherwise there might occur an unexpected behaviour.
   /// \param widget the widget which will be added to the GostyApp
   void AddWidgetToApp(const QString& ident, QWidget* widget);
-
+  
+  QWidget* GetWidget(const QString& ident);
   /// \brief remove a custom QWidget from the gosty_app
   ///
   /// This method removes a custom widget from OpenStructure. If the given ident is not known, nothing happens. Read more about custom widgets at \ref #AddWidgetToApp() .
@@ -146,6 +161,9 @@ public:
   /// \param app_title Title that will be displayed in the title bar
   void SetAppTitle(const QString& app_title);
 
+  /// \brief attempt to get a stereo visual upon startup
+  void TryStereo(bool f) {try_stereo_=f;}
+  
 public slots:
   /// \brief This slot must be called when the application is going to be terminated.
   void OnQuit();
@@ -168,6 +186,8 @@ private:
   
   QMap<QString,WidgetGeomHandler *> external_widgets_;
 
+  bool try_stereo_;
+
   static GostyApp*  app_;
 };
 
diff --git a/modules/gui/src/messages/log_reader.cc b/modules/gui/src/messages/log_reader.cc
index f4089ee557d359d2d66f4f85ec86c1b8745842ca..26f502d83106a129391fbdbbef2a28219c533380 100644
--- a/modules/gui/src/messages/log_reader.cc
+++ b/modules/gui/src/messages/log_reader.cc
@@ -57,6 +57,7 @@ void LogReader::LogMessage(const String& message, int severity){
       }
     }
   }
+  std::cerr << message;
 }
 
 QMessageBox::Icon LogReader::GetIconForSeverity(int severity){
diff --git a/modules/gui/src/messages/message_box_widget.cc b/modules/gui/src/messages/message_box_widget.cc
index 1be4b817c57fb7353ae094475993eb534721819e..0f75b337ea423d5309166755c115ef48ff42de7a 100644
--- a/modules/gui/src/messages/message_box_widget.cc
+++ b/modules/gui/src/messages/message_box_widget.cc
@@ -25,7 +25,7 @@
 
 #include <ost/gui/perspective.hh>
 #include <ost/gui/widget_registry.hh>
-
+#include <ost/gui/messages/message_widget.hh>
 #include <ost/gui/panels/panel_manager.hh>
 
 #include "log_reader.hh"
@@ -35,6 +35,8 @@
 #include <QLabel>
 #include <QMenu>
 #include <QVBoxLayout>
+
+
 namespace ost {namespace gui {
 
 MessageLevel::MessageLevel(QPixmap icon, QWidget* parent): QWidget(parent), message_count_(0), count_label_(new QLabel(QString::number(message_count_)+"  ",this)){
diff --git a/modules/gui/src/messages/message_widget.cc b/modules/gui/src/messages/message_widget.cc
index 8a87b06c789e9c6f1e9ccf229ab594465e523045..001a9635d8683b2134690fe0b87e3f23acb499bc 100644
--- a/modules/gui/src/messages/message_widget.cc
+++ b/modules/gui/src/messages/message_widget.cc
@@ -76,7 +76,10 @@ MessageWidget::MessageWidget(QWidget* parent) :
       + QString("delete_icon.png")));
   connect(clear_action, SIGNAL(triggered(bool)), this, SLOT(Clear()));
   this->actions_.append(clear_action);
-
+  QObject::connect(&PythonInterpreter::Instance(),
+                   SIGNAL(ErrorOutput(unsigned int, const QString &)),
+                   this,
+                   SLOT(ErrorOutput(unsigned int, const QString &)));
   new LogReader(this);
 }
 
@@ -95,6 +98,11 @@ void MessageWidget::LogMessage(const QString& message, QMessageBox::Icon icon) {
   this->Increase(icon);
 }
 
+void MessageWidget::ErrorOutput(unsigned int id,const QString& output)
+{
+  this->LogMessage(output, QMessageBox::Critical);
+}
+
 void MessageWidget::LogMessage(QStandardItem* item) {
   item->setData(QVariant(QMessageBox::NoIcon));
   this->model_->appendRow(item);
diff --git a/modules/gui/src/messages/message_widget.hh b/modules/gui/src/messages/message_widget.hh
index f126e0929944089b8dc5832d809fd45f88ea446f..5686c2fd39831dde89b1ec53f5551afa08b37307 100644
--- a/modules/gui/src/messages/message_widget.hh
+++ b/modules/gui/src/messages/message_widget.hh
@@ -60,6 +60,7 @@ signals:
   void AllCleared();
 
 public slots:
+  void ErrorOutput(unsigned int id,const QString& output);
   void Clear();
   void RemoveSelected();
   void Update();
diff --git a/modules/gui/src/panels/tabbed_panel_bar.cc b/modules/gui/src/panels/tabbed_panel_bar.cc
index 36ec6e2bc5f75db9eec0968ffc8a1c81cb968756..2047af69a99cc4bfb081841947afcb6d1f735e17 100644
--- a/modules/gui/src/panels/tabbed_panel_bar.cc
+++ b/modules/gui/src/panels/tabbed_panel_bar.cc
@@ -21,12 +21,13 @@
 #include <ost/gui/gosty_app.hh>
 #include <ost/gui/perspective.hh>
 #include <ost/gui/widget_registry.hh>
-
+#include <ost/gui/panels/panel_manager.hh>
 #include "tabbed_panel_bar.hh"
 
 #include <QApplication>
 #include <QSettings>
 #include <QDir>
+
 namespace ost { namespace gui {
 
 TabbedPanelBar::TabbedPanelBar(PanelBar* parent):
diff --git a/modules/gui/src/perspective.cc b/modules/gui/src/perspective.cc
index 6af76c48090d1bc09529b97906290c34d7fd0272..bf6745b743f7f0b47a8e7e8f690c7642039616f1 100644
--- a/modules/gui/src/perspective.cc
+++ b/modules/gui/src/perspective.cc
@@ -25,6 +25,10 @@
 #include <ost/gui/main_area.hh>
 #include <ost/gui/messages/message_box_widget.hh>
 
+#include <ost/gui/panels/panel_manager.hh>
+#include <ost/gui/panels/button_bar.hh>
+#include <ost/gui/panels/panel_bar.hh>
+
 #include <QTextEdit>
 #include <QSizeGrip>
 #include <QMainWindow>
@@ -116,15 +120,17 @@ QMenuBar* Perspective::GetMenuBar()
 
 QMenu* Perspective::GetMenu(const QString& name)
 {
-  QMenu* menu;
-  if(!menus_.contains(name)){
-    menu = menu_bar_->addMenu(name);
-    menus_.insert(name,menu);
-  }
-  else{
-    menu = menus_[name];
+  QMenu* menu=NULL;
+  QList<QAction *> actions=menu_bar_->actions();
+  for (QList<QAction*>::iterator i=actions.begin(),
+       e=actions.end(); i!=e; ++i) {
+    if ((*i)->text()==name) {
+      return (*i)->menu();
+    }
   }
-  return menu;
+  QMenu* new_menu=new QMenu(name, menu_bar_);
+  menu_bar_->addMenu(new_menu);
+  return new_menu;
 }
 
 PanelManager* Perspective::GetPanels()
diff --git a/modules/gui/src/perspective.hh b/modules/gui/src/perspective.hh
index b52a7c8f0414fc5b759e82300e8fe5c30228a031..84a594981775670ee607a8c4b303c41ffe4dd414 100644
--- a/modules/gui/src/perspective.hh
+++ b/modules/gui/src/perspective.hh
@@ -19,13 +19,11 @@
 #ifndef OST_GUI_PERSPECTIVE_HH
 #define OST_GUI_PERSPECTIVE_HH
 
+/*
+  Author: Marco Biasini, Stefan Scheuber
+ */
 
-class QMainWindow;
-class QTextEdit;
 
-#include <ost/gui/panels/panel_manager.hh>
-#include <ost/gui/panels/button_bar.hh>
-#include <ost/gui/panels/panel_bar.hh>
 #include <ost/gui/module_config.hh>
 
 #include <QObject>
@@ -34,15 +32,23 @@ class QTextEdit;
 #include <QString>
 #include <QMenu>
 #include <QStatusBar>
-/*
-  Author: Marco Biasini, Stefan Scheuber
- */
- 
+
+
+class QMenu;
+class QMenuBar; 
+class QStatusBar;
+class QMainWindow;
+class QTextEdit;
+
 namespace ost { namespace gui {
 
+
 class SideBar;
 class ThinSplitter;
 class MainArea;
+class PanelManager;
+class MainArea;
+class ButtonBar;
 
 /// The perspective manages the layout of the widgets inside the main window.
 /// It contains important classes which itself manages again a sub part of the whole layout.
@@ -92,7 +98,6 @@ private:
   void SetupQuickAccessBar();
   QWidget*        central_;
   QMenuBar*        menu_bar_;
-  QMap<QString,QMenu*> menus_;
   MainArea*       main_area_;
   PanelManager*   panels_;
   QWidget*        quick_access_bar_;
diff --git a/modules/gui/src/python_shell/python_interpreter.cc b/modules/gui/src/python_shell/python_interpreter.cc
index 3dea745a5cdc9265fed41ffe9abbdb8aed624856..07f1e9674da648643b32d99586c9f8cf2a5d429d 100644
--- a/modules/gui/src/python_shell/python_interpreter.cc
+++ b/modules/gui/src/python_shell/python_interpreter.cc
@@ -83,6 +83,10 @@ void PythonInterpreter::Start()
     emit WakeWorker();
 }
 
+void PythonInterpreter::StopScript()
+{
+  PyErr_SetInterrupt();
+}
 
 
 unsigned int PythonInterpreter::RunScript(const QString& fname)
diff --git a/modules/gui/src/python_shell/python_interpreter.hh b/modules/gui/src/python_shell/python_interpreter.hh
index ec6639bbb8d10342b657afc43eda2096dea9c67a..940b520cffb32f1c8f37e90de83636b2e9c78e9f 100644
--- a/modules/gui/src/python_shell/python_interpreter.hh
+++ b/modules/gui/src/python_shell/python_interpreter.hh
@@ -82,6 +82,9 @@ public:
   /// 
   /// \sa Stop
   void Start();
+  /// \brief stop script execution
+  void StopScript();
+  
   
 
 public slots:
diff --git a/modules/gui/src/python_shell/python_interpreter_worker.cc b/modules/gui/src/python_shell/python_interpreter_worker.cc
index 494df6c0bca61cd5b4a67791d55128c7d27a5ab9..b89859142642c21d4fc6f624b9727aa27d35dc81 100644
--- a/modules/gui/src/python_shell/python_interpreter_worker.cc
+++ b/modules/gui/src/python_shell/python_interpreter_worker.cc
@@ -32,7 +32,8 @@ PythonInterpreterWorker::PythonInterpreterWorker():
   parse_expr_cmd_(),
   repr_(),
   main_namespace_(),
-  current_id_()
+  current_id_(),
+  awake_(false)
 {
   Py_InitializeEx(1);
   parse_expr_cmd_=bp::import("parser").attr("expr");
@@ -52,10 +53,14 @@ PythonInterpreterWorker::PythonInterpreterWorker():
 
 void PythonInterpreterWorker::Wake()
 {
+  if (awake_) return;
+
+  awake_=true;
   while (!exec_queue_.isEmpty()){
     std::pair<unsigned int, QString> pair=exec_queue_.dequeue();
     run_command_(pair);
   }
+  awake_=false;
 }
 
 unsigned int PythonInterpreterWorker::AddCommand(const QString& command)
diff --git a/modules/gui/src/python_shell/python_interpreter_worker.hh b/modules/gui/src/python_shell/python_interpreter_worker.hh
index 77295ca8612f5877555408774a41f1a945f56de9..7d38dd544b040c86a19106751bf4813fe165dd1f 100644
--- a/modules/gui/src/python_shell/python_interpreter_worker.hh
+++ b/modules/gui/src/python_shell/python_interpreter_worker.hh
@@ -46,6 +46,7 @@ protected:
   bp::object repr_;
   bp::dict main_namespace_;
   unsigned int current_id_;
+  bool         awake_;
 };
 
 }} //ns
diff --git a/modules/gui/src/python_shell/python_shell_widget.cc b/modules/gui/src/python_shell/python_shell_widget.cc
index 16d1d4ac2d441c831d345bac845b6ece25955e9d..dc1190018c8f04e65cb3c55041d4a2b11313b3ab 100644
--- a/modules/gui/src/python_shell/python_shell_widget.cc
+++ b/modules/gui/src/python_shell/python_shell_widget.cc
@@ -42,7 +42,7 @@
 #include <QScrollBar>
 #include <QDirModel>
 #include <QStringList>
-
+#include <QDebug>
 
 /*
  Authors: Marco Biasini, Andreas Schenk
@@ -469,7 +469,7 @@ void PythonShellWidget::OnHistoryDownStateEntered()
 void PythonShellWidget::OnExecuteStateEntered()
 {
   QTextCursor cursor=textCursor();
-  cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::MoveAnchor);
+  cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
   setTextCursor(cursor);
   set_block_type_(block_edit_start_,textCursor().block(),BLOCKTYPE_CODE);
   insertPlainText(QString(QChar::ParagraphSeparator));
@@ -737,6 +737,14 @@ QTextBlock PythonShellWidget::GetEditStartBlock()
 
 void PythonShellWidget::keyPressEvent(QKeyEvent* event)
 {
+  // BZDNG-173
+  if (event->key()==Qt::Key_Left) {
+    if (this->textCursor().position()==GetEditStartBlock().position() ||
+        this->textCursor().anchor()==GetEditStartBlock().position()) {
+      event->accept();
+      return;
+    }
+  }
   if (this->handle_custom_commands_(event)){
     return;
   }
@@ -791,7 +799,10 @@ QString PythonShellWidget::GetCommand()
   QTextCursor cursor(block_edit_start_);
   cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
   QString text= cursor.selectedText();
-  text.replace(QChar::LineSeparator,"\n");
+  // replace LineSeparator with an empty string, they are used by Qt to 
+  // designate soft line wraps
+  text.replace(QChar::LineSeparator,"");
+  // a real line end
   text.replace(QChar::ParagraphSeparator,"\n");
   return text;
 }
diff --git a/modules/gui/src/python_shell/python_syntax_highlighter.cc b/modules/gui/src/python_shell/python_syntax_highlighter.cc
index f37eb4d61f866bd097ad8ddfbbce68fa565b23aa..c4488112db908a4c98091393eec87c89d46fa29e 100644
--- a/modules/gui/src/python_shell/python_syntax_highlighter.cc
+++ b/modules/gui/src/python_shell/python_syntax_highlighter.cc
@@ -86,7 +86,9 @@ void PythonSyntaxHighlighter::highlightBlock(const QString& text_block) {
   } else if (currentBlockState() & BLOCKTYPE_CODE) {
     base_state=BLOCKTYPE_CODE;
   }
+#if QT_VERSION < 0x040700
   cursor.setBlockFormat(block_formats_[static_cast<BlockType>(base_state)]);
+#endif
   if (currentBlockState() & BLOCKTYPE_BLOCKEDIT || 
       currentBlockState() & BLOCKTYPE_ACTIVE || 
       currentBlockState() & BLOCKTYPE_CODE) {
diff --git a/modules/gui/src/python_shell/transition_guard.cc b/modules/gui/src/python_shell/transition_guard.cc
index c32898964cf3a17c7375b5824b9fa0343cd538e1..940d5bba15a96f7605ffa90348cf6f64933f9994 100644
--- a/modules/gui/src/python_shell/transition_guard.cc
+++ b/modules/gui/src/python_shell/transition_guard.cc
@@ -37,7 +37,7 @@ EditPositionGuard::EditPositionGuard(PythonShellWidget* shell, int flags1, int f
 
 bool EditPositionGuard::check()
 {
-  return check_flag(flags1_) &&  check_flag(flags2_);
+    return check_flag(flags1_) &&  check_flag(flags2_);
 }
 
 bool EditPositionGuard::check_flag(int flags)
diff --git a/modules/gui/src/scene_selection.cc b/modules/gui/src/scene_selection.cc
index 1ef2ee7ce38eab22a77ef5e9501b349c62150b73..c2ac7f630f1d58880a5fa14c4aec8414bbe91d37 100644
--- a/modules/gui/src/scene_selection.cc
+++ b/modules/gui/src/scene_selection.cc
@@ -29,11 +29,10 @@
 #include <ost/gfx/entity.hh>
 
 #if OST_IMG_ENABLED
-
-#include <ost/gfx/map_iso.hh>
-#include <ost/gui/main_area.hh>
-#include <ost/gui/perspective.hh>
-
+#  include <ost/gfx/map_iso.hh>
+#  include <ost/gui/main_area.hh>
+#  include <ost/gui/perspective.hh>
+#  include <ost/gui/data_viewer/data_viewer.hh>
 #endif
 
 #include <ost/gui/scene_win/scene_win.hh>
@@ -55,7 +54,7 @@ void SceneSelection::SetActiveNodes(gfx::NodePtrList nodes, gfx::EntityP entity,
 }
 
 gfx::GfxNodeP SceneSelection::GetActiveNode(unsigned int pos) const{
-  if(pos >= 0 && pos < nodes_.size()){
+  if(pos < nodes_.size()){
     return nodes_[pos];
   }
   else{
@@ -72,7 +71,7 @@ int SceneSelection::GetActiveViewCount() const{
 }
 
 mol::EntityView SceneSelection::GetActiveView(unsigned int pos) const{
-  if(pos >=0 && pos < views_.size()){
+  if(pos < views_.size()){
     return views_[pos].GetEntityView();
   }
   else{
@@ -124,6 +123,7 @@ void SceneSelection::Delete() {
   for(int i=0; i < selected_objects.size(); i++){
     gfx::Scene::Instance().Remove(selected_objects[i]);
   }
+  gfx::Scene::Instance().RequestRedraw();
 }
 
 #if OST_IMG_ENABLED
diff --git a/modules/gui/src/scene_win/current_selection_node.cc b/modules/gui/src/scene_win/current_selection_node.cc
index 9de4397a43989be2af8d4732e08f0adec8974f02..6f7eeddaae4d8be145d2b5e47a96e2782e1fbf20 100644
--- a/modules/gui/src/scene_win/current_selection_node.cc
+++ b/modules/gui/src/scene_win/current_selection_node.cc
@@ -19,7 +19,7 @@
 
 #include <ost/gui/gosty_app.hh>
 #include <ost/mol/query_view_wrapper.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include <ost/gfx/scene.hh>
 #include <ost/gfx/gfx_node.hh>
 
diff --git a/modules/gui/src/scene_win/custom_part_node.cc b/modules/gui/src/scene_win/custom_part_node.cc
index 18c9d9972f9646ef64d93b498a7316622eddcc55..e18e6d62c9cc898bda2713a7eadeba9c2e40de13 100644
--- a/modules/gui/src/scene_win/custom_part_node.cc
+++ b/modules/gui/src/scene_win/custom_part_node.cc
@@ -20,7 +20,7 @@
 #include "custom_part_node.hh"
 
 #include "entity_part_node.hh"
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include <ost/gfx/entity.hh>
 #include <ost/gfx/gfx_node.hh>
 
diff --git a/modules/gui/src/scene_win/entity_node.cc b/modules/gui/src/scene_win/entity_node.cc
index 3aa51c81ce37a0f9acdeebd6033d4573b008ee73..4f49dcc96e676a8df67f73179c266f2e029649bd 100644
--- a/modules/gui/src/scene_win/entity_node.cc
+++ b/modules/gui/src/scene_win/entity_node.cc
@@ -25,7 +25,7 @@
 #include <ost/mol/view_type_fw.hh>
 
 #include <ost/gui/scene_win/scene_win.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include "current_selection_node.hh"
 #include "entity_part_node.hh"
 #include "label_node.hh"
@@ -43,7 +43,6 @@ EntityNode::EntityNode(gfx::EntityP& entity, SceneNode* parent):
     GfxSceneNode(entity,parent),custom_view_(NULL){
   SceneWinModel* model = GostyApp::Instance()->GetSceneWin()->GetModel();
   model->AddNode(parent, this);
-
   new RenderModesNode(entity, this);
 
   SceneNode* chain_node = new LabelNode("Chains",this);
diff --git a/modules/gui/src/scene_win/entity_part_node.cc b/modules/gui/src/scene_win/entity_part_node.cc
index da8867d8bb6e8c5c03f93d7318de63ee6ef81762..bc1fb5a9f3f698ffa94d1c93b2569d7a1ac52f8b 100644
--- a/modules/gui/src/scene_win/entity_part_node.cc
+++ b/modules/gui/src/scene_win/entity_part_node.cc
@@ -18,14 +18,19 @@
 //------------------------------------------------------------------------------
 
 #include "entity_part_node.hh"
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include <ost/gfx/entity.hh>
 #include <ost/gfx/gfx_node.hh>
 
 #include <QFont>
 namespace ost { namespace gui {
 
-EntityPartNode::EntityPartNode(QString name, gfx::EntityP entity, mol::QueryViewWrapper part, SceneNode* parent):SceneNode(parent),name_(name),entity_(entity),query_view_(part),visible_(true){
+EntityPartNode::EntityPartNode(QString name, gfx::EntityP entity, 
+                               mol::QueryViewWrapper part, 
+                               SceneNode* parent):
+  SceneNode(parent),name_(name),entity_(entity),
+  query_view_(part),visible_(true)
+{
 }
 
 QVariant EntityPartNode::GetData(int column, int role){
diff --git a/modules/gui/src/scene_win/gfx_scene_node.cc b/modules/gui/src/scene_win/gfx_scene_node.cc
index 191007aee833f93a9f4e36b2c2e91a39df4eb4b4..048cee4467023d093c54eda1301d345c26bfbb79 100644
--- a/modules/gui/src/scene_win/gfx_scene_node.cc
+++ b/modules/gui/src/scene_win/gfx_scene_node.cc
@@ -18,7 +18,7 @@
 //------------------------------------------------------------------------------
 
 #include "gfx_scene_node.hh"
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include <ost/gfx/scene.hh>
 #include <ost/gfx/gfx_node.hh>
 
diff --git a/modules/gui/src/scene_win/label_node.cc b/modules/gui/src/scene_win/label_node.cc
index 8a01e6aec1a27ae35b59a1b3cf0c2f98e3d2fcf1..f6d2d72f549b124ca55395fbbe0f97489334ea4a 100644
--- a/modules/gui/src/scene_win/label_node.cc
+++ b/modules/gui/src/scene_win/label_node.cc
@@ -21,7 +21,7 @@
 
 #include <ost/gfx/entity.hh>
 #include <ost/gfx/gfx_node.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include <QFont>
 namespace ost { namespace gui {
 
diff --git a/modules/gui/src/scene_win/render_mode_node.cc b/modules/gui/src/scene_win/render_mode_node.cc
index 88e67dea8d5990dae5ffe25a885805df462a8ca2..de6bc6fe609a66cd302f7394e3179c72c97151a9 100644
--- a/modules/gui/src/scene_win/render_mode_node.cc
+++ b/modules/gui/src/scene_win/render_mode_node.cc
@@ -18,7 +18,7 @@
 //------------------------------------------------------------------------------
 
 #include <ost/mol/query_view_wrapper.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include "render_mode_node.hh"
 
 #include <QFont>
diff --git a/modules/gui/src/scene_win/render_modes_node.cc b/modules/gui/src/scene_win/render_modes_node.cc
index a343490b894a21123cd97e353433db66dee27562..611cc3561e1ceb55d6bfc24757be9ded52279542 100644
--- a/modules/gui/src/scene_win/render_modes_node.cc
+++ b/modules/gui/src/scene_win/render_modes_node.cc
@@ -24,7 +24,7 @@
 #include <ost/gfx/gfx_node.hh>
 
 #include <ost/gui/scene_win/scene_win.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
 #include "render_modes_node.hh"
 #include "render_mode_node.hh"
 #include <QFont>
diff --git a/modules/gui/src/scene_win/scene_win.cc b/modules/gui/src/scene_win/scene_win.cc
index ba685c3f62a4d58a6babb74dd65c3c8942428806..e398f96783c5a32d360a2207acf167ea38bf9162 100644
--- a/modules/gui/src/scene_win/scene_win.cc
+++ b/modules/gui/src/scene_win/scene_win.cc
@@ -23,7 +23,8 @@
 #include <ost/gui/gosty_app.hh>
 #include <ost/gui/widget_registry.hh>
 #include <ost/gui/scene_selection.hh>
-
+#include <ost/gui/scene_win/scene_win_model.hh>
+#include <ost/gui/scene_win/context_menu.hh>
 #include "scene_win.hh"
 
 #include <QVBoxLayout>
diff --git a/modules/gui/src/scene_win/scene_win.hh b/modules/gui/src/scene_win/scene_win.hh
index 612198db622f03e3e82bb138eb3ce9d2b85dc164..c0f16a5dc622b575586718aafa3982492e98853a 100644
--- a/modules/gui/src/scene_win/scene_win.hh
+++ b/modules/gui/src/scene_win/scene_win.hh
@@ -23,20 +23,24 @@
 #include <ost/mol/query_view_wrapper.hh>
 
 #include <ost/gfx/gfx_node_fw.hh>
+#include <ost/gfx/entity.hh>
 
 #include <ost/gui/module_config.hh>
 #include <ost/gui/widget.hh>
-#include <ost/gui/scene_win/scene_win_model.hh>
-#include <ost/gui/scene_win/context_menu.hh>
 
 #include <QTreeView>
 #include <QItemSelection>
+
+
 /*
   Authors: Marco Biasini, Ansgar Philippsen, Stefan Scheuber
 */
 
 namespace ost { namespace gui {
 
+class SceneWinModel;
+class ContextMenu;
+
 // the display window for all graphical objects
 class DLLEXPORT_OST_GUI SceneWin: public Widget
 {
diff --git a/modules/gui/src/scene_win/scene_win_model.cc b/modules/gui/src/scene_win/scene_win_model.cc
index 9e7542b0815c2a73267820ad1fa1b1991cf8cce9..6c833ba48c94ac4afa6a4ad6e1c61d8d7322f24c 100644
--- a/modules/gui/src/scene_win/scene_win_model.cc
+++ b/modules/gui/src/scene_win/scene_win_model.cc
@@ -35,6 +35,7 @@
 
 #include <QSize>
 #include <QFont>
+#include <QDebug>
 
 namespace ost { namespace gui {
 
@@ -105,19 +106,22 @@ gfx::EntityP SceneWinModel::GetEntityOfViews(QModelIndexList indexes){
   return entity;
 }
 
-void SceneWinModel::Update(){
+void SceneWinModel::Update()
+{
   emit this->dataChanged(QModelIndex(),QModelIndex());
 }
 
-QModelIndex SceneWinModel::index(int row, int col, const QModelIndex& parent) const
+QModelIndex SceneWinModel::index(int row, int col, 
+                                 const QModelIndex& parent) const
 {
   SceneNode* parent_node = GetItem(parent);
 
   SceneNode* child_node = parent_node->GetChild(row);
-  if (child_node)
-      return createIndex(row, col, child_node);
-  else
-      return QModelIndex();
+  if (child_node) {
+    return createIndex(row, col, child_node);
+  } else {
+    return QModelIndex();    
+  }
 }
 
 QModelIndex SceneWinModel::parent(const QModelIndex& index) const
@@ -231,24 +235,36 @@ QMimeData* SceneWinModel::mimeData(const QModelIndexList &indexes) const
 void SceneWinModel::NodeAdded(const gfx::GfxNodeP& node)
 {
   gfx::EntityP e=boost::dynamic_pointer_cast<gfx::Entity>(node);
-  if(e){
-    new EntityNode(e,scene_node_);
+  SceneNode* parent_node=this->FindGfxNode(node->GetParent());
+  if (parent_node==NULL) {
+    parent_node=scene_node_;
+  }
+  if (e) {
+    EntityNode* ent_node=new EntityNode(e,parent_node);
+    node_map_[node.get()]=ent_node;
   }
   else{
-    SceneNode* scene_node = new GfxSceneNode(node, scene_node_);
-    this->AddNode(scene_node_,scene_node);
+    SceneNode* scene_node = new GfxSceneNode(node, parent_node);
+    node_map_[node.get()]=scene_node;
+    this->AddNode(parent_node, scene_node);
+    for (gfx::GfxNodeVector::const_iterator i=node->GetChildren().begin(),
+         e=node->GetChildren().end(); i!=e; ++i) {
+      this->NodeAdded(*i);
+    }
   }
 }
 
 void SceneWinModel::NodeRemoved(const gfx::GfxNodeP& node)
 {
   SceneNode* scene_node = this->FindGfxNode(node);
-  if(scene_node->GetParent()){
+  if(scene_node && scene_node->GetParent()){
+    node_map_.remove(node.get());
     this->RemoveNode(scene_node);
   }
 }
 
-void SceneWinModel::SelectionChanged(const gfx::GfxObjP& obj, const mol::EntityView& sel)
+void SceneWinModel::SelectionChanged(const gfx::GfxObjP& obj, 
+                                     const mol::EntityView& sel)
 {
 }
 
@@ -268,8 +284,9 @@ SceneNode* SceneWinModel::GetItem(const QModelIndex &index) const
   return root_node_;
 }
 
-bool SceneWinModel::AddNode(SceneNode* parent, SceneNode* child){
-  QModelIndex parent_index = GetIndexOf(parent);
+bool SceneWinModel::AddNode(SceneNode* parent, SceneNode* child)
+{
+  QModelIndex parent_index=this->GetIndexOf(parent);
   if(parent_index.isValid()){
     int row = parent->GetChildCount();
     this->beginInsertRows(parent_index,row,row);
@@ -280,11 +297,12 @@ bool SceneWinModel::AddNode(SceneNode* parent, SceneNode* child){
   return false;
 }
 
-bool SceneWinModel::RemoveNode(SceneNode* node){
-  QModelIndex index = GetIndexOf(node);
-  SceneNode* parent = node->GetParent();
+bool SceneWinModel::RemoveNode(SceneNode* node)
+{
+  QModelIndex index=this->GetIndexOf(node);
+  SceneNode* parent=node->GetParent();
   if(parent && index.isValid()){
-    QModelIndex parent_index = GetIndexOf(parent);
+    QModelIndex parent_index =this->GetIndexOf(parent);
     int row = node->GetRow();
     this->beginRemoveRows(parent_index,row,row);
     parent->RemoveChild(node);
@@ -295,26 +313,45 @@ bool SceneWinModel::RemoveNode(SceneNode* node){
 }
 
 
-void SceneWinModel::AttachRenderModeObserver(RenderModesNode* node){
+void SceneWinModel::AttachRenderModeObserver(RenderModesNode* node)
+{
   render_observers_.insert(node->GetGfxNode(),node);
 }
 
-void SceneWinModel::DetachRenderModeObserver(RenderModesNode* node){
+void SceneWinModel::DetachRenderModeObserver(RenderModesNode* node)
+{
   if(render_observers_.contains(node->GetGfxNode())){
     render_observers_.remove(node->GetGfxNode());
   }
 }
 
-QModelIndex SceneWinModel::GetIndexOf(SceneNode* node, int column){
-  return GetIndex(node,index(0,0,QModelIndex()),column);
+QModelIndex SceneWinModel::GetIndexOf(SceneNode* node, int column) 
+{
+  std::vector<SceneNode*> trace;
+  SceneNode* parent=node->GetParent();
+  while (parent) {
+    trace.push_back(parent);
+    parent=parent->GetParent();
+    
+  }
+  if (!trace.empty()) {
+    trace.pop_back();
+  }
+  QModelIndex parent_index=this->index(0, 0, QModelIndex());
+  for (std::vector<SceneNode*>::reverse_iterator i=trace.rbegin(), 
+       e=trace.rend(); i!=e; ++i) {
+    SceneNode* cur=*i;
+    parent_index=this->GetIndex(cur, parent_index, 0);
+  }
+  return this->GetIndex(node, parent_index, column);
 }
 
-QModelIndex SceneWinModel::GetIndex(SceneNode* node, QModelIndex parent, int column){
+QModelIndex SceneWinModel::GetIndex(SceneNode* node, QModelIndex parent, 
+                                    int column) {
   if(parent.isValid()){
     SceneNode* parent_node =reinterpret_cast<SceneNode*>(parent.internalPointer());
-    if(parent_node == node)return parent;
-    int i=parent_node->GetChildCount()-1;
-    while(i>=0){
+    if (parent_node == node) return parent;
+    for (int i=parent_node->GetChildCount()-1; i>=0; --i) {
       SceneNode* child = parent_node->GetChild(i);
       if(child == node){
         if(column<child->GetColumnCount())
@@ -326,24 +363,18 @@ QModelIndex SceneWinModel::GetIndex(SceneNode* node, QModelIndex parent, int col
       if (found.isValid()) {
         return found;
       }
-      i--;
     }
   }
   return QModelIndex();
 }
 
-SceneNode* SceneWinModel::FindGfxNode(gfx::GfxNodeP node) const{
-  int i=0;
-  while(i<scene_node_->GetChildCount()){
-    GfxSceneNode* gfx_scene_node = qobject_cast<GfxSceneNode*>(scene_node_->GetChild(i));
-    if(gfx_scene_node && node==gfx_scene_node->GetGfxNode()){
-      return gfx_scene_node;
-    }
-    else{
-      i++;
-    }
+SceneNode* SceneWinModel::FindGfxNode(gfx::GfxNodeP node) 
+{
+  QMap<gfx::GfxNode*, SceneNode*>::iterator i=node_map_.find(node.get());
+  if (i!=node_map_.end()) {
+    return i.value();
   }
-  return root_node_;
+  return NULL;
 }
 
 }} // ns
diff --git a/modules/gui/src/scene_win/scene_win_model.hh b/modules/gui/src/scene_win/scene_win_model.hh
index 060b148816aaadb7b9734b8a3333589f97788d17..fbcee3d4bf777f95bd606b4f5be3a9ef5b2c9268 100644
--- a/modules/gui/src/scene_win/scene_win_model.hh
+++ b/modules/gui/src/scene_win/scene_win_model.hh
@@ -59,7 +59,7 @@ public:
 
   SceneNode* GetItem(const QModelIndex &index) const;
 
-  SceneNode* FindGfxNode(gfx::GfxNodeP node) const;
+  SceneNode* FindGfxNode(gfx::GfxNodeP node);
 
 
   bool AddNode(SceneNode* parent, SceneNode* child);
@@ -107,6 +107,7 @@ private:
   SceneNode* scene_node_;
 
   QMap<gfx::GfxNodeP, RenderModesNode*> render_observers_;
+  QMap<gfx::GfxNode*, SceneNode*>       node_map_;
 };
 
 }}
diff --git a/modules/gui/src/sequence_viewer/alignment_view_object.cc b/modules/gui/src/sequence_viewer/alignment_view_object.cc
index f5a08689be49aed7959370840aa7f2ce89dc79c2..1ce665c5c788ddf3f3b2e416d0de8fe7826f34b7 100644
--- a/modules/gui/src/sequence_viewer/alignment_view_object.cc
+++ b/modules/gui/src/sequence_viewer/alignment_view_object.cc
@@ -69,19 +69,6 @@ QMap<QString,int> GetGroupMap(){
   return map;
 }
 
-QColor GetColor(int cons){
-  int color = 255 - int((float(cons) / 100) * 200);
-  return QColor(color,color,color);
-}
-
-QColor GetForeGroundColor(QColor background){
-  if(background == Qt::transparent){
-    return Qt::black;
-  }
-  int gray = 255 - background.red();
-  return QColor(gray,gray,gray);
-}
-
 }
 
 QMap<QString,int> AlignmentViewObject::group_map_ = GetGroupMap();
@@ -93,7 +80,7 @@ const QString AlignmentViewObject::conservation_mode_2 = "Highlight conservation
 AlignmentViewObject::AlignmentViewObject(const seq::AlignmentHandle& alignment, QObject* parent): SequenceViewObject(parent), alignment_(alignment)
 {
   for(int i=0; i<alignment.GetCount(); i++){
-    seq::SequenceHandle seq_handle = alignment.GetSequence(i).Copy();
+    seq::ConstSequenceHandle seq_handle = alignment.GetSequence(i);
     this->AddSequence(seq_handle, seq_handle.GetName().c_str());
   }
 
diff --git a/modules/gui/src/sequence_viewer/secstr_row.cc b/modules/gui/src/sequence_viewer/secstr_row.cc
index 2610fc1a20493f14a50665270736addfb1718f35..506867d0002236ad3af6e42229d911bfdb910a1e 100644
--- a/modules/gui/src/sequence_viewer/secstr_row.cc
+++ b/modules/gui/src/sequence_viewer/secstr_row.cc
@@ -36,7 +36,7 @@ namespace ost { namespace gui {
 SecStrRow::SecStrRow(const QString& name, mol::ChainView& chain, SequenceViewObject* parent) : SequenceRow(name,parent)
 { this->SetChain(chain); }
 
-void SecStrRow::SetSequence(seq::SequenceHandle& sequence)
+void SecStrRow::SetSequence(seq::ConstSequenceHandle sequence)
 {
   //Do nothing
 }
diff --git a/modules/gui/src/sequence_viewer/secstr_row.hh b/modules/gui/src/sequence_viewer/secstr_row.hh
index 7a9d7991dc3e4dbf30f3d646eb4ba0d994591862..900659cd0968c4ced7bcdfd27495478f09f4ab89 100644
--- a/modules/gui/src/sequence_viewer/secstr_row.hh
+++ b/modules/gui/src/sequence_viewer/secstr_row.hh
@@ -38,12 +38,13 @@ class SecStrRow : public SequenceRow
   Q_OBJECT
 
 public:
-  SecStrRow(const QString& name, mol::ChainView& chain, SequenceViewObject* parent);
+  SecStrRow(const QString& name, mol::ChainView& chain, 
+            SequenceViewObject* parent);
 
   virtual QVariant GetData(int column, int role) const;
   virtual void DoubleClicked(int column);
 
-  void SetSequence(seq::SequenceHandle& sequence);
+  void SetSequence(seq::ConstSequenceHandle sequence);
   void SetChain(mol::ChainView& chain);
   const mol::ChainView& GetChain() const;
 
diff --git a/modules/gui/src/sequence_viewer/sequence_model.cc b/modules/gui/src/sequence_viewer/sequence_model.cc
index 342a04e1f258cfe8b87cd0488bb616d46b94ab2c..9852315401e422d937ad56b65e5cc4f7eaf9bfee 100644
--- a/modules/gui/src/sequence_viewer/sequence_model.cc
+++ b/modules/gui/src/sequence_viewer/sequence_model.cc
@@ -186,7 +186,7 @@ const PainterList& SequenceModel::GetPainters(const QModelIndex& index) const{
   return empty_painter_list_;
 }
 
-QPair<int, BaseViewObject*> SequenceModel::GetRowWithItem(int row) const{
+QPair<int, BaseViewObject*> SequenceModel::GetRowWithItem(int row) const {
   if(!objects_.isEmpty()){
     int rows = 0;
     int i = -1;
@@ -202,6 +202,36 @@ QPair<int, BaseViewObject*> SequenceModel::GetRowWithItem(int row) const{
   return QPair<int, BaseViewObject*>(-1, NULL);
 }
 
+void SequenceModel::EmitRowChanged(int row)
+{
+  emit this->dataChanged(this->index(row, 0), 
+                         this->index(row, this->columnCount()-1));
+}
+
+void SequenceModel::Clear()
+{
+  // remove everything but the title row. 
+  this->beginRemoveRows(QModelIndex(), 1, this->rowCount());
+  objects_.erase(objects_.begin()+1, objects_.end());
+  this->endRemoveRows();
+  this->beginRemoveColumns(QModelIndex(), 0, this->max_columns);
+  this->max_columns=0;
+  this->endRemoveColumns();
+}
+
+QPair<seq::AlignmentHandle, int> SequenceModel::GetAlignmentForRow(int row)
+{
+  QPair<int, BaseViewObject*> p=this->GetRowWithItem(row);
+  if (p.second) {
+    AlignmentViewObject* avo=dynamic_cast<AlignmentViewObject*>(p.second);
+    if (avo) {
+      return QPair<seq::AlignmentHandle, int>(avo->GetAlignment(), p.first);
+    }    
+  }
+  return QPair<seq::AlignmentHandle, int>(seq::AlignmentHandle(), -1);
+}
+
+
 QPair<int, BaseViewObject*> SequenceModel::GetRowWithItem(const QModelIndex& index) const{
   return this->GetRowWithItem(index.row());
 }
diff --git a/modules/gui/src/sequence_viewer/sequence_model.hh b/modules/gui/src/sequence_viewer/sequence_model.hh
index 5a105c66fd1b8aa6b95d9dc5883e998191192cba..0da09222e2ac39ea13fdd408c9bbe91da7ffaeac 100644
--- a/modules/gui/src/sequence_viewer/sequence_model.hh
+++ b/modules/gui/src/sequence_viewer/sequence_model.hh
@@ -60,7 +60,6 @@ public:
 
   int GetGlobalRow(BaseViewObject* obj, int row) const;
 
-
   const QStringList& GetDisplayModes();
   const QStringList& GetDisplayModes(const gfx::EntityP& entity);
   const QStringList& GetDisplayModes(const seq::AlignmentHandle& alignment);
@@ -84,7 +83,11 @@ public:
                       int role=Qt::DisplayRole) const;
 
   virtual Qt::ItemFlags flags(const QModelIndex& index=QModelIndex()) const;
-
+  QPair<seq::AlignmentHandle, int> GetAlignmentForRow(int row);
+  
+  void EmitRowChanged(int row);
+  
+  void Clear();
 public slots:
   void ZoomIn();
   void ZoomOut();
diff --git a/modules/gui/src/sequence_viewer/sequence_row.cc b/modules/gui/src/sequence_viewer/sequence_row.cc
index 5537b9f82e51b1c121163147cf9f0edc950bd81b..77bc27897aaaf94fe459385bdbaad567f04e093b 100644
--- a/modules/gui/src/sequence_viewer/sequence_row.cc
+++ b/modules/gui/src/sequence_viewer/sequence_row.cc
@@ -34,7 +34,7 @@
 #include <QtGui>
 namespace ost { namespace gui {
 
-SequenceRow::SequenceRow(const QString& name, seq::SequenceHandle& sequence, SequenceViewObject* parent) : BaseRow(QFont("Courier",11),parent), name_(name), name_font_(QFont("Courier",11)), sequence_(sequence)
+SequenceRow::SequenceRow(const QString& name, seq::ConstSequenceHandle sequence, SequenceViewObject* parent) : BaseRow(QFont("Courier",11),parent), name_(name), name_font_(QFont("Courier",11)), sequence_(sequence)
 {
   name_font_.setBold(true);
   name_font_.setItalic(true);
@@ -61,12 +61,12 @@ const QString& SequenceRow::GetName() const
   return this->name_;
 }
 
-void SequenceRow::SetSequence(seq::SequenceHandle& sequence)
+void SequenceRow::SetSequence(seq::ConstSequenceHandle sequence)
 {
   this->sequence_ = sequence;
 }
 
-const seq::SequenceHandle& SequenceRow::GetSequence() const
+const seq::ConstSequenceHandle& SequenceRow::GetSequence() const
 {
   return this->sequence_;
 }
diff --git a/modules/gui/src/sequence_viewer/sequence_row.hh b/modules/gui/src/sequence_viewer/sequence_row.hh
index 1665366ba447e0121b94a5c9a41fa5919616d291..b48c1c627db2ee1b893a575fdb4a44b751241346 100644
--- a/modules/gui/src/sequence_viewer/sequence_row.hh
+++ b/modules/gui/src/sequence_viewer/sequence_row.hh
@@ -38,7 +38,8 @@ class SequenceRow : public BaseRow
   Q_OBJECT
 
 public:
-  SequenceRow(const QString& name, seq::SequenceHandle& sequence, SequenceViewObject* parent);
+  SequenceRow(const QString& name, seq::ConstSequenceHandle sequence, 
+              SequenceViewObject* parent);
   SequenceRow(const QString& name, SequenceViewObject* parent);
 
   virtual int GetColumnCount() const;
@@ -50,15 +51,15 @@ public:
   void SetName(const QString& name);
   const QString& GetName() const;
 
-  virtual void SetSequence(seq::SequenceHandle& sequence);
-  const seq::SequenceHandle& GetSequence() const;
+  virtual void SetSequence(seq::ConstSequenceHandle sequence);
+  const seq::ConstSequenceHandle& GetSequence() const;
 
   virtual void SetSelection(const QSet<int>& added, const QSet<int>& removed);
 
 private:
   QString name_;
   QFont name_font_;
-  seq::SequenceHandle sequence_;
+  seq::ConstSequenceHandle sequence_;
 };
 
 }}
diff --git a/modules/gui/src/sequence_viewer/sequence_table_view.cc b/modules/gui/src/sequence_viewer/sequence_table_view.cc
index a4998dcf3419bd50c4a4b1153b1f78f5fbb8aff9..bbe7a2da32421e150db3703e4f4ee1e7f701422d 100644
--- a/modules/gui/src/sequence_viewer/sequence_table_view.cc
+++ b/modules/gui/src/sequence_viewer/sequence_table_view.cc
@@ -89,7 +89,6 @@ void SequenceTableView::InitStaticColumn()
   for(int col=1; col<this->model()->columnCount(); col++){
    static_column_->setColumnHidden(col, true);
   }
-
   static_column_->setColumnWidth(0, this->columnWidth(0) );
 
   static_column_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@@ -227,19 +226,21 @@ QModelIndex SequenceTableView::moveCursor(CursorAction action, Qt::KeyboardModif
 {
   QModelIndex current = QTableView::moveCursor(action, modifiers);
 
-  if(action == MoveLeft && current.column()>0
-     && this->visualRect(current).topLeft().x() < static_column_->columnWidth(0) ){
-   const int new_value = horizontalScrollBar()->value() + this->visualRect(current).topLeft().x() - static_column_->columnWidth(0);
+#if !(defined(__APPLE__) && (QT_VERSION>=0x040600))
+  if (action == MoveLeft && current.column()>0
+     && this->visualRect(current).topLeft().x() < static_column_->columnWidth(0)){
+  int new_value = horizontalScrollBar()->value() + this->visualRect(current).topLeft().x();
+   new_value-=static_column_->columnWidth(0);
+
    horizontalScrollBar()->setValue(new_value);
   }
 
-
-  if(action == MoveUp && current.row()>0
-     && this->visualRect(current).bottomLeft().y() < static_row_->rowHeight(0) ){
-   const int new_value = verticalScrollBar()->value() + this->visualRect(current).bottomRight().y() - static_row_->rowHeight(0);
+  if (action == MoveUp && current.row()>0 && this->visualRect(current).bottomLeft().y() < static_row_->rowHeight(0)){
+    int new_value = verticalScrollBar()->value() + this->visualRect(current).bottomRight().y();
+    new_value-=static_row_->rowHeight(0);   
    verticalScrollBar()->setValue(new_value);
   }
-
+#endif
   return current;
 }
 
@@ -378,8 +379,86 @@ void SequenceTableView::wheelEvent(QWheelEvent* event)
   }
 }
 
+std::pair<int, int> SequenceTableView::GetSimpleSelection(int row)
+{
+  QModelIndexList sel=this->selectionModel()->selectedIndexes();
+  QModelIndexList row_sel;
+  for (QModelIndexList::const_iterator i=sel.begin(), e=sel.end(); i!=e; ++i) {
+    if (i->row()==row) {
+      row_sel.push_back(*i);
+    }
+  }
+  if (row_sel.empty()) {
+    return std::make_pair(-1, -1);
+  }
+  std::sort(row_sel.begin(), row_sel.end(), std::less<QModelIndex>());
+  for (QModelIndexList::const_iterator i=row_sel.begin()+1, 
+       e=row_sel.end(); i!=e; ++i) {
+    if ((i-1)->column()!=i->column()-1) {
+      return std::make_pair(-1, -1);
+    }
+  }
+  return std::make_pair(row_sel.front().column()-1, row_sel.back().column()-1);
+}
+
 void SequenceTableView::keyPressEvent(QKeyEvent* event)
 {
+  if (this->IsSingleAlignment()) {
+    if (event->key()==Qt::Key_Space || event->key()==Qt::Key_Backspace) {
+      std::vector<QItemSelection> new_sel;
+      int row_count=this->model()->rowCount();
+      seq::AlignmentHandle changed_aln;
+      for (int i=1; i<row_count; ++i) {
+        std::pair<int, int> sel=this->GetSimpleSelection(i);      
+        if (sel.first==-1 && sel.second==-1) {
+          continue;
+        }
+
+        SequenceModel* smodel=dynamic_cast<SequenceModel*>(this->model());
+        QPair<seq::AlignmentHandle, int> aln=smodel->GetAlignmentForRow(i);
+        new_sel.push_back(QItemSelection(smodel->index(i, sel.first+1), 
+                                         smodel->index(i, sel.second+1)));
+        if (aln.second==-1) {
+          continue;
+        }
+        int amount=0;
+        if (event->key()==Qt::Key_Space) {
+          amount=1;
+          if (aln.first.GetLength()==sel.second) {
+            continue;
+          }
+          if (aln.first.GetSequence(aln.second)[sel.second+1]!='-') {
+            continue;
+          }
+        }
+        if (event->key()==Qt::Key_Backspace) {
+          amount=-1;
+          if (sel.first==0) {
+            continue;
+          }
+          if (aln.first.GetSequence(aln.second)[sel.first-1]!='-') {
+            continue;
+          }
+        }
+        changed_aln=aln.first;
+        aln.first.ShiftRegion(sel.first, sel.second+1, amount, aln.second);
+        new_sel.back()=QItemSelection(smodel->index(i, sel.first+amount+1), 
+                                      smodel->index(i, sel.second+amount+1));
+        smodel->EmitRowChanged(i);
+      }
+      QItemSelectionModel* sel_model=this->selectionModel();
+      sel_model->clear();
+      for (size_t i=0; i<new_sel.size(); ++i) {
+        sel_model->select(new_sel[i], QItemSelectionModel::SelectCurrent);
+      }
+      if (changed_aln.IsValid()) {
+        emit this->AlignmentChanged();
+      }
+      return;
+    }
+
+  }
+
   if(event->matches(QKeySequence::Copy)){
     emit CopyEvent(event);
   }
diff --git a/modules/gui/src/sequence_viewer/sequence_table_view.hh b/modules/gui/src/sequence_viewer/sequence_table_view.hh
index 3114a8f6e8c334cd40f46529f9f05707aa62dcac..28eaf3b19c3ab9cd32bdb095fbb713313f4416c0 100644
--- a/modules/gui/src/sequence_viewer/sequence_table_view.hh
+++ b/modules/gui/src/sequence_viewer/sequence_table_view.hh
@@ -42,10 +42,14 @@ public:
   QTableView* GetStaticField();
   ~SequenceTableView();
 
+
+  void SetSingleAlignment(bool flag) { single_alignment_=flag; }
+  
+  bool IsSingleAlignment() const { return single_alignment_; }
 signals:
   void MouseWheelEvent(QWheelEvent* event);
   void CopyEvent(QKeyEvent* event);
-
+  void AlignmentChanged();
 public slots:
   void columnCountChanged(const QModelIndex& index, int old_count, int new_count);
   void rowCountChanged(const QModelIndex& index, int old_count, int new_count);
@@ -69,11 +73,14 @@ private slots:
   void ResizeHeight(int index, int, int size);
 
 private:
+
+  std::pair<int, int> GetSimpleSelection(int row);
   QTableView* static_column_;
   QTableView* static_row_;
   QTableView* static_field_;
   SequenceDelegate* delegate_;
   QModelIndex last_double_click_;
+  bool        single_alignment_;
   void updateStaticColumn();
   void updateStaticRow();
   void updateStaticField();
diff --git a/modules/gui/src/sequence_viewer/sequence_view_object.cc b/modules/gui/src/sequence_viewer/sequence_view_object.cc
index 40a46a519d85158584d37338558bd70128fd7f6b..e884de755c74342180e4be5b88c9de08d012e551 100644
--- a/modules/gui/src/sequence_viewer/sequence_view_object.cc
+++ b/modules/gui/src/sequence_viewer/sequence_view_object.cc
@@ -100,7 +100,7 @@ void SequenceViewObject::Init()
   }
 }
 
-void SequenceViewObject::AddSequence(seq::SequenceHandle& sequence, const QString& name)
+void SequenceViewObject::AddSequence(seq::ConstSequenceHandle sequence, const QString& name)
 {
   SequenceRow* new_row = new SequenceRow(name, sequence, this);
   new_row->InsertPainter(background_painter);
@@ -163,7 +163,7 @@ QMap<int, QList<int> > SequenceViewObject::GetIndexesForView(const mol::EntityVi
     for(int i=0; i< rows_.size(); i++){
       if(SecStrRow* secstr_row = qobject_cast<SecStrRow*>(rows_[i])){
         mol::ChainView dst_chain=(secstr_row->GetChain());
-        seq::SequenceHandle seq = secstr_row->GetSequence();
+        seq::ConstSequenceHandle seq = secstr_row->GetSequence();
         if (mol::ChainView src_chain=view.FindChain(dst_chain.GetName())) {
           // for each residue in the selection deduce index in sequence
           for (mol::ResidueViewList::const_iterator j=src_chain.GetResidueList().begin(),
@@ -191,7 +191,7 @@ QMap<int, QList<int> > SequenceViewObject::GetIndexesForSubject(const QString& s
   for(int i=0; i< rows_.size(); i++){
     if(SequenceRow* secstr_row = qobject_cast<SequenceRow*>(rows_[i])){
       if(sequence_name.size()==0 || sequence_name==secstr_row->GetName()){
-        seq::SequenceHandle seq = secstr_row->GetSequence();
+        seq::ConstSequenceHandle seq = secstr_row->GetSequence();
         String seq_str=seq.GetString();
         size_t pos=0;
         size_t first=String::npos;
diff --git a/modules/gui/src/sequence_viewer/sequence_view_object.hh b/modules/gui/src/sequence_viewer/sequence_view_object.hh
index ba862c724efba112968fdc735f0f1cc1271a4492..9060052e80baf5dbc05143a3236461604aa4e9c6 100644
--- a/modules/gui/src/sequence_viewer/sequence_view_object.hh
+++ b/modules/gui/src/sequence_viewer/sequence_view_object.hh
@@ -55,7 +55,7 @@ public:
 
   void Init();
 
-  void AddSequence(seq::SequenceHandle& sequence, const QString& name=QString());
+  void AddSequence(seq::ConstSequenceHandle sequence, const QString& name=QString());
   void AddChain(mol::ChainView& chain, const QString& name=QString());
 
   void AttachGfxObject(gfx::EntityP& ent);
diff --git a/modules/gui/src/sequence_viewer/sequence_viewer.cc b/modules/gui/src/sequence_viewer/sequence_viewer.cc
index 79c13057f9e85b248bfc9590d3f5bc1af19929ad..82f3892ba8ecf7ba204d4083905481d623962ee7 100644
--- a/modules/gui/src/sequence_viewer/sequence_viewer.cc
+++ b/modules/gui/src/sequence_viewer/sequence_viewer.cc
@@ -38,6 +38,8 @@
 
 #include "sequence_model.hh"
 #include "sequence_viewer.hh"
+#include "sequence_search_bar.hh"
+#include "sequence_table_view.hh"
 
 #include <QAbstractItemView>
 #include <QApplication>
@@ -49,6 +51,7 @@
 #include <QShortcut>
 #include <QVBoxLayout>
 #include <QVarLengthArray>
+
 namespace ost { namespace gui {
 
 class SequenceViewerFactory: public WidgetFactory {
@@ -64,19 +67,30 @@ public:
 
 OST_REGISTER_WIDGET(SequenceViewer, SequenceViewerFactory);
 
+struct NodeParentPair {
+  NodeParentPair(gfx::GfxNodeP n, gfx::GfxNodeP p): node(n), parent(p) {}
+  
+  gfx::GfxNodeP node;
+  gfx::GfxNodeP parent;
+};
+
 struct GetNodesVisitor: public gfx::GfxNodeVisitor {
+
   GetNodesVisitor(): nodes_() {}
   virtual void VisitObject(gfx::GfxObj* o, const Stack& st) {
-    nodes_.push_back(o->shared_from_this());
+    nodes_.push_back(o->shared_from_this());    
   }
-  gfx::NodePtrList nodes_;
-  gfx::NodePtrList GetNodes(){return nodes_;}
+  gfx::GfxNodeVector nodes_;
+  gfx::GfxNodeVector GetNodes() {return nodes_; }
 };
 
-SequenceViewer::SequenceViewer(bool stand_alone, QWidget* parent): Widget(NULL,parent)
+SequenceViewer::SequenceViewer(bool stand_alone, bool observe_scene,
+                               const QString& title,
+                               QWidget* parent): Widget(NULL,parent)
 {
+  observe_scene_=observe_scene;
   model_ = new SequenceModel(this);
-
+  this->setWindowTitle(title);
   QVBoxLayout* layout = new QVBoxLayout(this);
   layout->setMargin(0);
   layout->setSpacing(0);
@@ -90,17 +104,18 @@ SequenceViewer::SequenceViewer(bool stand_alone, QWidget* parent): Widget(NULL,p
   }
   this->InitSearchBar();
   this->InitView();
-
-  if(!stand_alone){
+  if (observe_scene_) {
     gfx::Scene::Instance().AttachObserver(this);
     gfx::GfxNodeP root_node = gfx::Scene::Instance().GetRootNode();
     GetNodesVisitor gnv;
     gfx::Scene::Instance().Apply(gnv);
-    gfx::NodePtrList list = gnv.GetNodes();
+    gfx::GfxNodeVector list=gnv.GetNodes();
     for(unsigned int i=0; i<list.size();i++){
       this->NodeAdded(list[i]);
-    }
+    }    
   }
+  connect(seq_table_view_, SIGNAL(AlignmentChanged()),
+          this, SIGNAL(AlignmentChanged()));
 }
 
 void SequenceViewer::InitMenuBar()
@@ -170,6 +185,10 @@ void SequenceViewer::InitActions()
 
 void SequenceViewer::AddEntity(const gfx::EntityP& entity)
 {
+  if (!observe_scene_) {
+    return;
+  }
+  seq_table_view_->SetSingleAlignment(false);
   model_->InsertGfxEntity(entity);
   this->FitToContents();
   this->UpdateSearchBar();
@@ -177,11 +196,17 @@ void SequenceViewer::AddEntity(const gfx::EntityP& entity)
 
 void SequenceViewer::RemoveEntity(const gfx::EntityP& entity)
 {
+  if (!observe_scene_) {
+    return;
+  }
   model_->RemoveGfxEntity(entity);
 }
 
 void SequenceViewer::NodeAdded(const gfx::GfxNodeP& n)
 {
+  if (!observe_scene_) {
+    return;
+  }
   if (gfx::EntityP o=boost::dynamic_pointer_cast<gfx::Entity>(n)) {
     this->AddEntity(o);
   }
@@ -189,6 +214,9 @@ void SequenceViewer::NodeAdded(const gfx::GfxNodeP& n)
 
 void SequenceViewer::NodeRemoved(const gfx::GfxNodeP& node)
 {
+  if (!observe_scene_) {
+    return;
+  }
   if (gfx::EntityP o=boost::dynamic_pointer_cast<gfx::Entity>(node)) {
     this->RemoveEntity(o);
   }
@@ -197,11 +225,22 @@ void SequenceViewer::NodeRemoved(const gfx::GfxNodeP& node)
 void SequenceViewer::AddAlignment(const seq::AlignmentHandle& alignment)
 {
   if(alignment.GetCount()>0 && alignment.GetLength()>0){
+    if (model_->rowCount()>1) {
+      seq_table_view_->SetSingleAlignment(false);
+    } else {
+      seq_table_view_->SetSingleAlignment(true);
+    }
     model_->InsertAlignment(alignment);
     this->FitToContents();
   }
 }
 
+void SequenceViewer::SetAlignment(const seq::AlignmentHandle& alignment)
+{
+  model_->Clear();
+  this->AddAlignment(alignment);
+}
+
 void SequenceViewer::RemoveAlignment(const seq::AlignmentHandle& alignment)
 {
   model_->RemoveAlignment(alignment);
@@ -227,7 +266,10 @@ void SequenceViewer::SelectionModelChanged(const QItemSelection& sel, const QIte
 void SequenceViewer::SelectionChanged(const gfx::GfxObjP& o,
                                       const mol::EntityView& view)
 {
-  disconnect(seq_table_view_->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(SelectionModelChanged(const QItemSelection&, const QItemSelection&)));
+  disconnect(seq_table_view_->selectionModel(), 
+             SIGNAL(selectionChanged(const QItemSelection&, 
+                                     const QItemSelection&)), 
+             this, SLOT(SelectionModelChanged(const QItemSelection&, const QItemSelection&)));
   gfx::EntityP entity=boost::dynamic_pointer_cast<gfx::Entity>(o);
   if(entity){
     const QModelIndexList& list = model_->GetModelIndexes(entity, view);
diff --git a/modules/gui/src/sequence_viewer/sequence_viewer.hh b/modules/gui/src/sequence_viewer/sequence_viewer.hh
index 6a3c49efcabf852bf39a1bf47d6f503f75c2c5ea..7fadb40dbbc63a8bf5fd465745aacc2304a4c9bb 100644
--- a/modules/gui/src/sequence_viewer/sequence_viewer.hh
+++ b/modules/gui/src/sequence_viewer/sequence_viewer.hh
@@ -28,37 +28,50 @@
 
 #include <ost/gfx/scene.hh>
 #include <ost/gfx/gfx_object.hh>
-
+#include <ost/gfx/entity.hh>
 #include <ost/gui/widget.hh>
 
 #include <ost/gui/module_config.hh>
 
-#include "sequence_search_bar.hh"
-#include "sequence_model.hh"
-#include "sequence_table_view.hh"
 
 #include <QWidget>
 #include <QActionGroup>
 #include <QToolBar>
-namespace ost { namespace gui {
+#include <QModelIndex>
+#include <QItemSelection>
+
+namespace ost { 
+
+namespace gui {
+
+class SeqSearchBar;
+class SequenceModel;  
+class SequenceTableView;
+
 
 /// \brief QTableView with first column not moving
 class DLLEXPORT_OST_GUI SequenceViewer : public Widget, public gfx::SceneObserver  {
   Q_OBJECT
 public:
-  SequenceViewer(bool stand_alone=true, QWidget* parent=NULL);
+  SequenceViewer(bool stand_alone=true, bool observe_scene=false,
+                 const QString& title="Sequence Viewer",
+                 QWidget* parent=NULL);
   ~SequenceViewer();
 
   virtual void SelectionChanged(const gfx::GfxObjP& o, const mol::EntityView& view);
 
   virtual void AddEntity(const gfx::EntityP& entity);
   virtual void RemoveEntity(const gfx::EntityP& entity);
-
+  void SetObserveScene(bool flag) { observe_scene_=flag; }
+  bool IsObservingScene() const { return observe_scene_; }
   virtual void AddAlignment(const seq::AlignmentHandle& alignment);
-  virtual void RemoveAlignment(const seq::AlignmentHandle& alignment);
 
-  virtual bool Restore(const QString&){return true;};
-  virtual bool Save(const QString&){return true;};
+  void SetAlignment(const seq::AlignmentHandle& alignment);
+  
+  virtual void RemoveAlignment(const seq::AlignmentHandle& alignment);
+  
+  virtual bool Restore(const QString&){ return true; };
+  virtual bool Save(const QString&){ return true; };
 
   virtual const QStringList& GetDisplayModes();
   virtual const QStringList& GetDisplayModes(const seq::AlignmentHandle& alignment);
@@ -69,7 +82,8 @@ public:
   virtual const QString& GetCurrentDisplayMode(const gfx::EntityP& entity);
 
   virtual ActionList GetActions();
-
+signals:
+  void AlignmentChanged();
 public slots:
   void ChangeDisplayMode(const QString&);
   void ChangeDisplayMode(const seq::AlignmentHandle&, const QString&);
@@ -92,11 +106,11 @@ private:
   SeqSearchBar* seq_search_bar_;
   SequenceModel* model_;
   SequenceTableView* seq_table_view_;
-
+  
   ActionList action_list_;
 
   QActionGroup* display_mode_actions_;
-
+  bool observe_scene_;
 private slots:
   void ChangeDisplayMode();
   void FindInSequence();
diff --git a/modules/gui/src/tools/map_tool.cc b/modules/gui/src/tools/map_tool.cc
index ef2a784412153df6b475a8a74404ae0f99ee4aff..5b887283928901c6da5d9b9ddde105a039a5411b 100644
--- a/modules/gui/src/tools/map_tool.cc
+++ b/modules/gui/src/tools/map_tool.cc
@@ -17,13 +17,14 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 
-#include <ost/gui/gosty_app.hh>
 #include <ost/platform.hh>
-#include <ost/gfx/map_iso.hh>
 #include <ost/gfx/map_slab.hh>
 #include <ost/gfx/scene.hh>
+#include <ost/gfx/map_iso.hh>
 
+#include <ost/gui/gosty_app.hh>
 #include <ost/gui/scene_selection.hh>
+
 #include "map_tool.hh"
 
 #include <QDir>
diff --git a/modules/gui/src/tools/measure_tool.cc b/modules/gui/src/tools/measure_tool.cc
index 4247e2f830d7f859a03666693c522e530cfc88ae..fb12cad505e4f7bcbb9923e1cff3e9f5d2f6b1a4 100644
--- a/modules/gui/src/tools/measure_tool.cc
+++ b/modules/gui/src/tools/measure_tool.cc
@@ -205,12 +205,17 @@ Measurement::Measurement(mol::AtomHandleList ahl, gfx::Color col, Real line_widt
       type_=DIHE;
       name_=ahl_[0].GetQualifiedName()+" - "+ahl_[1].GetQualifiedName()+" - "
              +ahl_[2].GetQualifiedName()+" - "+ahl_[3].GetQualifiedName();
-      measurement_=57.2958*geom::Angle(geom::Plane(ahl_[0].GetPos(),
-                                                   ahl_[1].GetPos(),
-                                                   ahl_[2].GetPos()),
-                                       geom::Plane(ahl_[1].GetPos(),
-                                                   ahl_[2].GetPos(),
-                                                   ahl_[3].GetPos()));
+      geom::Plane pl1 = geom::Plane(ahl_[0].GetPos(),
+                                    ahl_[1].GetPos(),
+                                    ahl_[2].GetPos());
+      geom::Plane pl2 = geom::Plane(ahl_[1].GetPos(),
+                                    ahl_[2].GetPos(),
+                                    ahl_[3].GetPos());
+      measurement_=57.2958*geom::Angle(pl1, pl2);
+      geom::Vec3 v = geom::Vec3(ahl_[2].GetPos()-ahl_[3].GetPos());
+      if (geom::Dot(v, pl1.GetNormal())>0) {
+        measurement_*=-1;
+      }
       valid_=true;
       break;
     }
diff --git a/modules/gui/src/tools/selection_tool.cc b/modules/gui/src/tools/selection_tool.cc
index dfc45ca8f0aa55cc979336f8a54c0d9cbaf42730..4b3ad64822b893ca66f9e05f7d1ff6b8421d07c4 100644
--- a/modules/gui/src/tools/selection_tool.cc
+++ b/modules/gui/src/tools/selection_tool.cc
@@ -55,7 +55,8 @@ void SelectionTool::Click(const MouseEvent& event)
   int sel_mode=this->GetSelectionMode();
   gfx::Scene& scene=gfx::Scene::Instance();
   scene.SetSelectionMode(sel_mode);
-  scene.Pick(event.GetPos().x(), scene.GetViewport().height-event.GetPos().y(), 8);
+  scene.Pick(event.GetPos().x(), 
+             scene.GetViewport().height-event.GetPos().y(), 8);
 }
 
 
diff --git a/modules/gui/src/tools/tool_bar.cc b/modules/gui/src/tools/tool_bar.cc
index e4babc0ed2b85be84a2113f3f30a127a74e35bc8..7a59970ffb7453f005ddb96376e1b216b9a1888a 100644
--- a/modules/gui/src/tools/tool_bar.cc
+++ b/modules/gui/src/tools/tool_bar.cc
@@ -20,11 +20,15 @@
 #include <ost/gui/gosty_app.hh>
 #include <ost/mol/query_view_wrapper.hh>
 #include <ost/gui/tools/tool_manager.hh>
+
+#include <ost/gui/scene_win/scene_win.hh>
+
 #include "tool_bar.hh"
 
 #include <QAction>
 #include <QDebug>
 #include <QActionGroup>
+
 namespace ost { namespace gui {
 
 ToolBar::ToolBar(QWidget* parent):
diff --git a/modules/gui/src/widget.cc b/modules/gui/src/widget.cc
index b67f4b50fa97fef66985c237115a39a3c061a5f3..7a94cc0dd7cb595175f4100c3baa7194d9468126 100644
--- a/modules/gui/src/widget.cc
+++ b/modules/gui/src/widget.cc
@@ -17,6 +17,7 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 #include <cassert>
+#include <QVBoxLayout>
 
 #include "widget.hh"
 
@@ -52,6 +53,10 @@ void Widget::SetInternalWidget(QWidget* widget)
 {
   assert(internal_==NULL);
   internal_=widget;
+  QBoxLayout* l=new QVBoxLayout(this);
+  l->setMargin(0);
+  l->setSpacing(0);
+  l->addWidget(widget);
   widget->setParent(this);
 }
 
diff --git a/modules/gui/src/widget_geom_handler.hh b/modules/gui/src/widget_geom_handler.hh
index 164719ba4ae35222ceb4b60992a8465d7deed7bc..191a4c992e0f89cfc95760b71b93b3bba81a3bb2 100644
--- a/modules/gui/src/widget_geom_handler.hh
+++ b/modules/gui/src/widget_geom_handler.hh
@@ -34,7 +34,7 @@ class DLLEXPORT_OST_GUI WidgetGeomHandler: public QObject{
 
     void LoadGeom(const QString& prefix);
     void SaveGeom(const QString& prefix);
-
+    QWidget* GetWidget() { return widget_; }
   private:
     QWidget* widget_;
 };
diff --git a/modules/img/alg/pymod/export_transcendentals.cc b/modules/img/alg/pymod/export_transcendentals.cc
index 2a9f42cc72add271b1f37ad800470b5cb6eaacd6..e2f22e8c13a20af0b3342f9caf3ee2e737201e0b 100644
--- a/modules/img/alg/pymod/export_transcendentals.cc
+++ b/modules/img/alg/pymod/export_transcendentals.cc
@@ -28,16 +28,16 @@ using namespace boost::python;
 #include <ost/img/alg/transcendentals.hh>
 
 using namespace ost::img;
-using namespace ost::img::alg;
+//using namespace ost::img::alg;
 
 void export_Transcendentals()
 {
-  class_<Cos, bases<ConstModIPAlgorithm> >("Cos", init<>());
-  class_<Exp, bases<ConstModIPAlgorithm> >("Exp", init<>());
-  class_<Log, bases<ConstModIPAlgorithm> >("Log", init<>());
-  class_<Log10, bases<ConstModIPAlgorithm> >("Log10", init<>());
-  class_<Sin, bases<ConstModIPAlgorithm> >("Sin", init<>());
-  class_<Sqrt, bases<ConstModIPAlgorithm> >("Sqrt", init<>());
-  class_<Tan, bases<ConstModIPAlgorithm> >("Tan", init<>());
-  class_<Pow, bases<ConstModIPAlgorithm> >("Pow", init<Real>());
+  class_<alg::Cos, bases<ConstModIPAlgorithm> >("Cos", init<>());
+  class_<alg::Exp, bases<ConstModIPAlgorithm> >("Exp", init<>());
+  class_<alg::Log, bases<ConstModIPAlgorithm> >("Log", init<>());
+  class_<alg::Log10, bases<ConstModIPAlgorithm> >("Log10", init<>());
+  class_<alg::Sin, bases<ConstModIPAlgorithm> >("Sin", init<>());
+  class_<alg::Sqrt, bases<ConstModIPAlgorithm> >("Sqrt", init<>());
+  class_<alg::Tan, bases<ConstModIPAlgorithm> >("Tan", init<>());
+  class_<alg::Pow, bases<ConstModIPAlgorithm> >("Pow", init<Real>());
 }
diff --git a/modules/img/alg/src/alg_mirror.cc b/modules/img/alg/src/alg_mirror.cc
index 0a984c0c2656d37c8d64280f9d4b085050b283fd..f32a23616c8f0be239cb08f89d0d730218b734b2 100644
--- a/modules/img/alg/src/alg_mirror.cc
+++ b/modules/img/alg/src/alg_mirror.cc
@@ -20,11 +20,9 @@
 
 #include "alg_mirror.hh"
 
-namespace ost { namespace img {
+namespace ost { namespace img { namespace image_state {
 
-#ifndef NO_EXPL_INST
 template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::MirrorFnc>;
-#endif
 
-}} // ns
+}}} // ns
 
diff --git a/modules/img/alg/src/alg_shift.cc b/modules/img/alg/src/alg_shift.cc
index 48c1100867aecbcc7dd095c1d76e61e94fcd235c..7663bf63983535904aa6d1ed3ecbe71fe68ed867 100644
--- a/modules/img/alg/src/alg_shift.cc
+++ b/modules/img/alg/src/alg_shift.cc
@@ -20,11 +20,9 @@
 
 #include "alg_shift.hh"
 
-namespace ost { namespace img {
+namespace ost { namespace img { namespace image_state {
 
-#ifndef NO_EXPL_INST
 template class TEMPLATE_DEF_EXPORT ImageStateModOPAlgorithm<alg::ShiftFnc>;
-#endif
 
-}} // ns
+}}} // ns
 
diff --git a/modules/img/alg/src/alg_transform.cc b/modules/img/alg/src/alg_transform.cc
index 4bc23e362ccd5f671e0f37d9b5c9de94fc6c19ac..6cf049267d7078f8c0a96e5817797ae7912df60e 100644
--- a/modules/img/alg/src/alg_transform.cc
+++ b/modules/img/alg/src/alg_transform.cc
@@ -20,11 +20,9 @@
 
 #include "alg_transform.hh"
 
-namespace ost { namespace img {
-
+namespace ost { namespace img { namespace image_state {
 
 template class TEMPLATE_DEF_EXPORT ImageStateModOPAlgorithm<alg::TransformFnc>;
 
-
-}} // ns
+}}} // ns
 
diff --git a/modules/img/alg/src/auto_correlate.cc b/modules/img/alg/src/auto_correlate.cc
index c40e136a2da997861bce210196dbef8038ee5e02..cbf4b0c57668371c22c6e1453c95dc04beea004b 100644
--- a/modules/img/alg/src/auto_correlate.cc
+++ b/modules/img/alg/src/auto_correlate.cc
@@ -55,5 +55,7 @@ ImageStateBasePtr AutoCorrelateFnc::VisitState(const ImageStateImpl<V,D>& isi) c
 }
 
 }
+
+namespace image_state {
 template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::AutoCorrelateFnc>;
-}} //
+}}} //
diff --git a/modules/img/alg/src/auto_correlate.hh b/modules/img/alg/src/auto_correlate.hh
index 54237203276bd11f493e96006cfe6c69bf4fc446..813f62dd709511e657cfd42f82868e659c55d92d 100644
--- a/modules/img/alg/src/auto_correlate.hh
+++ b/modules/img/alg/src/auto_correlate.hh
@@ -43,10 +43,8 @@ private:
 
 typedef ImageStateConstModOPAlgorithm<AutoCorrelateFnc> AutoCorrelate;
 
-}
+}}} // ns
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateConstModOPAlgorithm<alg::AutoCorrelateFnc>)
-
-  }} // ns
+OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateConstModOPAlgorithm<ost::img::alg::AutoCorrelateFnc>)
 
 #endif
diff --git a/modules/img/alg/src/convolute.cc b/modules/img/alg/src/convolute.cc
index afb3deed5c323366ae53203fea58471f5c9c286b..31ea54807097a215834bf8febcfd8e90ccbbe5dd 100644
--- a/modules/img/alg/src/convolute.cc
+++ b/modules/img/alg/src/convolute.cc
@@ -91,7 +91,10 @@ ImageStateBasePtr ExplicitConvoluteFnc::VisitState(const ImageStateImpl<V,D>& is
 }
 
 }
-template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::ExplicitConvoluteFnc>;
 
-}} // ns
+namespace image_state {
+  
+template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::ExplicitConvoluteFnc>;  
+
+}}} // ns
 
diff --git a/modules/img/alg/src/discrete_shrink.hh b/modules/img/alg/src/discrete_shrink.hh
index a794bd82e4809fe8d1cc2c3e1f29a80e759698fa..8090774ea2637032eaa1dbeee05846892fd19382 100644
--- a/modules/img/alg/src/discrete_shrink.hh
+++ b/modules/img/alg/src/discrete_shrink.hh
@@ -55,10 +55,8 @@ typedef ImageStateConstModOPAlgorithm<DiscreteShrinkFnc> DiscreteShrink;
 
 }
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,image_state::ImageStateConstModOPAlgorithm<alg::DiscreteShrinkFnc>)
-
 }} // ns
 
-
+OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateConstModOPAlgorithm<ost::img::alg::DiscreteShrinkFnc>)
 
 #endif
diff --git a/modules/img/alg/src/fft.hh b/modules/img/alg/src/fft.hh
index 120f045edbe7b1949882ef58074440f9efe9c4d5..d306f8b3ea90220c5d3b7c781125361f2a797ea1 100644
--- a/modules/img/alg/src/fft.hh
+++ b/modules/img/alg/src/fft.hh
@@ -50,9 +50,11 @@ typedef image_state::ImageStateConstModOPAlgorithm<FFTFnc> FFT;
 
 }
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,image_state::ImageStateConstModOPAlgorithm<alg::FFTFnc>)
 
-  }} // ns
+}} // ns
+
+OST_IMG_ALG_EXPLICIT_INST_DECL(class, ImageStateConstModOPAlgorithm<ost::img::alg::FFTFnc>)
+
 
 #endif
 
diff --git a/modules/img/alg/src/gaussian.cc b/modules/img/alg/src/gaussian.cc
index 6e930a0860209476c1db439f554e117e8c5dfc86..2fc87aad3ade38ef51a4672d1b1f3acf9178e678 100644
--- a/modules/img/alg/src/gaussian.cc
+++ b/modules/img/alg/src/gaussian.cc
@@ -107,5 +107,8 @@ void GaussianFilterBase::calcBVals( Real q )
 
 } // ns
 
+namespace image_state {
+
 template class ImageStateModIPAlgorithm<alg::GaussianFilterBase>;
-}}
+  
+}}}
diff --git a/modules/img/alg/src/gaussian.hh b/modules/img/alg/src/gaussian.hh
index 6bfa922d7a6259ec6b8b6e8f72f8c9323254be65..42430a555a7d43d45681282b027c116a2607e5aa 100644
--- a/modules/img/alg/src/gaussian.hh
+++ b/modules/img/alg/src/gaussian.hh
@@ -139,7 +139,7 @@ typedef ImageStateModIPAlgorithm<GaussianFilterBase> GaussianFilter;
 
 
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,image_state::ImageStateModIPAlgorithm<alg::GaussianFilterBase>)
+OST_IMG_ALG_EXPLICIT_INST_DECL(class, ImageStateModIPAlgorithm<alg::GaussianFilterBase>)
 
 
 
diff --git a/modules/img/alg/src/histogram.cc b/modules/img/alg/src/histogram.cc
index 50753ddc5545018b9fb30c9df3f87e766f8e1d83..1552afa60f19342b05b6feb3adfc90d0d364abe3 100644
--- a/modules/img/alg/src/histogram.cc
+++ b/modules/img/alg/src/histogram.cc
@@ -80,5 +80,9 @@ void HistogramBase::VisitFunction(const Function& fnc)
 
 
 }
+
+namespace image_state {
+
 template class TEMPLATE_DEF_EXPORT ImageStateNonModAlgorithm<alg::HistogramBase>;
-}} // namespaces
+
+}}} // namespaces
diff --git a/modules/img/alg/src/histogram.hh b/modules/img/alg/src/histogram.hh
index 7805d40fcb86740c0d85eadc35d97111f17eed75..082fe428241d4e60eb7ec1b50ba4ca667c0eef21 100644
--- a/modules/img/alg/src/histogram.hh
+++ b/modules/img/alg/src/histogram.hh
@@ -74,7 +74,7 @@ typedef ImageStateNonModAlgorithm<HistogramBase> Histogram;
 
 }
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateNonModAlgorithm<alg::HistogramBase>)
+OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateNonModAlgorithm<ost::img::alg::HistogramBase>)
 
 }} // namespaces
 
diff --git a/modules/img/alg/src/local_sigma_threshold.cc b/modules/img/alg/src/local_sigma_threshold.cc
index b8bedca1e049b707952c01f750a4d8be6244ea75..4a11b707776cf45e5a5d2f6ae8e4c97bea280e4a 100644
--- a/modules/img/alg/src/local_sigma_threshold.cc
+++ b/modules/img/alg/src/local_sigma_threshold.cc
@@ -66,5 +66,10 @@ ImageStateBasePtr LocalSigmaThresholdBase::VisitState(const ImageStateImpl<T,D>&
 
 
 }
-template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::LocalSigmaThresholdBase>;
-}} // ns
+
+namespace image_state {
+  
+template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::LocalSigmaThresholdBase>;  
+
+}}} // ns
+
diff --git a/modules/img/alg/src/mask_image.cc b/modules/img/alg/src/mask_image.cc
index 5f1488b3e60e203b674a4d306466c0b891cd1b11..648e31ec41eaee25bad1dba1fa2e55efc45c4459 100644
--- a/modules/img/alg/src/mask_image.cc
+++ b/modules/img/alg/src/mask_image.cc
@@ -59,6 +59,8 @@ void MaskImageBase::VisitState(ImageStateImpl<T,D>& is) const
 
 }
 
-template class TEMPLATE_DEF_EXPORT ImageStateConstModIPAlgorithm<alg::MaskImageBase>;
+namespace image_state {
 
-}} // namespaces
+template class TEMPLATE_DEF_EXPORT ImageStateConstModIPAlgorithm<alg::MaskImageBase>;
+  
+}}} // namespaces
diff --git a/modules/img/alg/src/mask_image.hh b/modules/img/alg/src/mask_image.hh
index 51d9061c713fc4fb1f200ad212e5e520fe85f59f..7ccfd89cf02983a4fb5bdab28219ada9e8cab907 100644
--- a/modules/img/alg/src/mask_image.hh
+++ b/modules/img/alg/src/mask_image.hh
@@ -54,10 +54,10 @@ typedef ImageStateConstModIPAlgorithm<MaskImageBase> MaskImage;
 
 }
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateConstModIPAlgorithm<alg::MaskImageBase>)
 
+}} // namespaces
 
-  }} // namespaces
+OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateConstModIPAlgorithm<ost::img::alg::MaskImageBase>)
 
 #endif /*MASK_IMAGE_HH_*/
 
diff --git a/modules/img/alg/src/module_config.hh b/modules/img/alg/src/module_config.hh
index 5a8966bd2965961fdd55b57b0fa1d60d315e122b..9484d1de769873fdd06950841883cde4b8e4b92b 100644
--- a/modules/img/alg/src/module_config.hh
+++ b/modules/img/alg/src/module_config.hh
@@ -26,10 +26,10 @@
 #  if defined(_MSC_VER)
 #    define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t)
 #  else
-#    define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t) extern template TEMPLATE_EXPORT c t;
+#    define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t) extern template TEMPLATE_EXPORT c ost::img::image_state::t;
 #  endif
 #else
 #  define DLLEXPORT_IMG_ALG DLLIMPORT
-#  define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t) extern template c DLLIMPORT t;
+#  define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t) extern template c DLLIMPORT ost::img::image_state::t;
 #endif
 #endif
diff --git a/modules/img/alg/src/power_spectrum.cc b/modules/img/alg/src/power_spectrum.cc
index 38cd8ecf81fac47bef2faa85ba3e1cf8558120ed..97c0e7bc4c4e668176f397640357bbb7a3497c0c 100644
--- a/modules/img/alg/src/power_spectrum.cc
+++ b/modules/img/alg/src/power_spectrum.cc
@@ -104,6 +104,10 @@ ImageStateBasePtr PowerSpectrumFnc::VisitState(const ImageStateImpl<V,D>& isi) c
 }
 
 }
+
+namespace image_state {
+
 template class TEMPLATE_DEF_EXPORT ImageStateConstModOPAlgorithm<alg::PowerSpectrumFnc>;
-}} //
+
+}}} //
 
diff --git a/modules/img/alg/src/randomize.cc b/modules/img/alg/src/randomize.cc
index 9dd063ca2cba65a7a7b591f64a29b698f52b0c96..112abf0ec616fd4e9f2bf28bf9f0b1dc7a44733a 100644
--- a/modules/img/alg/src/randomize.cc
+++ b/modules/img/alg/src/randomize.cc
@@ -20,9 +20,9 @@
 
 #include "randomize.hh"
 
-namespace ost { namespace img { 
+namespace ost { namespace img { namespace image_state {
+  
+template class TEMPLATE_DEF_EXPORT ImageStateConstModIPAlgorithm<alg::RandomizeFnc>;  
 
-template class TEMPLATE_DEF_EXPORT ImageStateConstModIPAlgorithm<alg::RandomizeFnc>;
-
-}} // ns
+}}} // ns
 
diff --git a/modules/img/alg/src/smooth_mask_image.cc b/modules/img/alg/src/smooth_mask_image.cc
index f4156cc5b91978b757eef1790ede8606f1edc8d4..24409e7d49acb9a22e7294ac47eb7ae5f7663777 100644
--- a/modules/img/alg/src/smooth_mask_image.cc
+++ b/modules/img/alg/src/smooth_mask_image.cc
@@ -80,5 +80,10 @@ void SmoothMaskImageBase::VisitState(ImageStateImpl<T,D>& is)
 
 
 }
+
+namespace image_state {
+
 template class TEMPLATE_DEF_EXPORT ImageStateModIPAlgorithm<alg::SmoothMaskImageBase>;
-}} // namespaces
+
+
+}}} // namespaces
diff --git a/modules/img/alg/src/smooth_mask_image.hh b/modules/img/alg/src/smooth_mask_image.hh
index fad8bf38836637dcdfb79e50647a1f58c05ff98a..8ced4033661abf50c051c2276c415e46e3d341cd 100644
--- a/modules/img/alg/src/smooth_mask_image.hh
+++ b/modules/img/alg/src/smooth_mask_image.hh
@@ -55,8 +55,10 @@ typedef ImageStateModIPAlgorithm<SmoothMaskImageBase> SmoothMaskImage;
 
 }
 
-OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateModIPAlgorithm<alg::SmoothMaskImageBase>)
 
-  }} // namespaces
+
+}} // namespaces
+
+OST_IMG_ALG_EXPLICIT_INST_DECL(class,ImageStateModIPAlgorithm<ost::img::alg::SmoothMaskImageBase>)
 
 #endif /*SMOOTH_MASK_IMAGE_HH_*/
diff --git a/modules/img/alg/src/stat.cc b/modules/img/alg/src/stat.cc
index bf271ad1889abc5409d0205b490552420d8e6a04..2e4ea577d769d77570a72be5fdeb499fac072799 100644
--- a/modules/img/alg/src/stat.cc
+++ b/modules/img/alg/src/stat.cc
@@ -162,5 +162,8 @@ std::ostream& operator<<(std::ostream& o, const Stat& s)
 
 
 }
+namespace image_state {
+  
 template class TEMPLATE_DEF_EXPORT ImageStateNonModAlgorithm<alg::StatBase>;
-}} // ns
+
+}}} // ns
diff --git a/modules/img/alg/src/stat_min_max.cc b/modules/img/alg/src/stat_min_max.cc
index 6e24552bfd9179844eb036d9c2fa94263e5ad00e..fcdd3c71ff72e4b3639717a3ad94f3a0ada0b8d2 100644
--- a/modules/img/alg/src/stat_min_max.cc
+++ b/modules/img/alg/src/stat_min_max.cc
@@ -98,5 +98,9 @@ std::ostream& operator<<(std::ostream& o, const StatMinMax& s)
 
 
 }
-template class TEMPLATE_DEF_EXPORT ImageStateNonModAlgorithm<alg::StatMinMaxBase>;
-}} // ns
+
+namespace image_state {
+  
+template class TEMPLATE_DEF_EXPORT ImageStateNonModAlgorithm<alg::StatMinMaxBase>;  
+
+}}} // ns
diff --git a/modules/img/alg/src/threshold.cc b/modules/img/alg/src/threshold.cc
index 2408a7602aabff41b7f6bcc4a886ab7c25feb04f..d8e9155a5b3c1b0c3d4a369a2be8b35fe5bf4355 100644
--- a/modules/img/alg/src/threshold.cc
+++ b/modules/img/alg/src/threshold.cc
@@ -21,11 +21,9 @@
 
 
 
-namespace ost { namespace img {
-
-
+namespace ost { namespace img { namespace image_state {
 
 template class TEMPLATE_DEF_EXPORT ImageStateModIPAlgorithm<alg::ThresholdFnc>;
 
-}}
+}}}
 
diff --git a/modules/img/base/src/CMakeLists.txt b/modules/img/base/src/CMakeLists.txt
index 97ea2ed0b32297cf7e5298ec975d221a956da806..eba4707b0b6bb048b07a6422ced7d98c772feb38 100644
--- a/modules/img/base/src/CMakeLists.txt
+++ b/modules/img/base/src/CMakeLists.txt
@@ -76,7 +76,6 @@ util.cc
 module_config.hh
 value_util.hh
 vecmat.hh
-version.hh
 mask_base_fw.hh
 mask_base.hh
 composite_mask.hh
diff --git a/modules/img/base/src/image_state/image_state_visitor.hh b/modules/img/base/src/image_state/image_state_visitor.hh
index 408941d9c64ab1c2e331f76bc1484451d228a2d2..7b5d35ab1e309cf2a0ce86e9a967b3e348af4317 100644
--- a/modules/img/base/src/image_state/image_state_visitor.hh
+++ b/modules/img/base/src/image_state/image_state_visitor.hh
@@ -315,7 +315,7 @@ public:
 private:
   template <typename T, class D>
   void T_Visit_(const ImageStateImpl<T,D>& isi) {
-    VisitState(isi);
+    this->VisitState(isi);
   }
 };
 
@@ -368,7 +368,7 @@ public:
 private:
   template <typename T, class D>
   void T_Visit_(ImageStateImpl<T,D>& isi) {
-    VisitState(isi);
+    this->VisitState(isi);
   }
 };
 
@@ -423,7 +423,7 @@ public:
 private:
   template <typename T, class D>
   void T_Visit_(ImageStateImpl<T,D>& isi) const {
-    VisitState(isi);
+    this->VisitState(isi);
   }
 };
 
@@ -476,7 +476,7 @@ public:
 private:
   template <typename T, class D>
   ImageStateBasePtr T_Visit_(const ImageStateImpl<T,D>& isi) {
-    return VisitState(isi);
+    return this->VisitState(isi);
   }
 };
 
@@ -531,7 +531,7 @@ public:
 private:
   template <typename T, class D>
   ImageStateBasePtr T_Visit_(const ImageStateImpl<T,D>& isi) const {
-    return VisitState(isi);
+    return this->VisitState(isi);
   }
 };
 
@@ -584,7 +584,7 @@ public:
 private:
   template <typename T, class D>
   ImageStateBasePtr T_Visit_(ImageStateImpl<T,D>& isi) {
-    return VisitState(isi);
+    return this->VisitState(isi);
   }
 };
 
diff --git a/modules/img/base/src/vecmat.hh b/modules/img/base/src/vecmat.hh
index 0fe9d299dbd292e8365aa8e41a45292fcc72d8e4..d2c82ba9055e44dbba5c934621fe6c9b2cbe25e3 100644
--- a/modules/img/base/src/vecmat.hh
+++ b/modules/img/base/src/vecmat.hh
@@ -37,6 +37,7 @@
 namespace ost { namespace img {
 
 // this pulls the geom namespace into the img one
+// which is a bad idea
 using namespace ::geom;
 
 
diff --git a/modules/img/base/tests/test_image.cc b/modules/img/base/tests/test_image.cc
index dde2a034f900d1f93269f02bdf462324e2867894..2342cb11e5b0f88b408ba2e6fd437ab4f870fa79 100644
--- a/modules/img/base/tests/test_image.cc
+++ b/modules/img/base/tests/test_image.cc
@@ -25,7 +25,7 @@
 #include <iostream>
 
 #include "test_image.hh"
-
+#include <ost/invalid_handle.hh>
 #include <ost/img/image.hh>
 #include <ost/img/data_observer.hh>
 #include <ost/img/observable.hh>
@@ -612,6 +612,13 @@ void test_PointToCoord() {
   BOOST_CHECK(spatial.CoordToIndex(Vec3(11.0,11.0,11.0)) == Vec3(3.0,3.0,3.0));
 }
 
+void test_ThrowInvalidImageHandle() {
+  ImageHandle image;
+  BOOST_CHECK_THROW(ost::CheckHandleValidity(image), ost::InvalidHandle);
+  image=CreateImage(Size(1,1));
+  BOOST_CHECK_NO_THROW(ost::CheckHandleValidity(image));
+}
+
 } // ns
 
 test_suite* CreateImageTest()
@@ -633,6 +640,7 @@ test_suite* CreateImageTest()
   ts->add(BOOST_TEST_CASE(&test_Copy));
   ts->add(BOOST_TEST_CASE(&test_Extract));
   ts->add(BOOST_TEST_CASE(&test_Paste));
+  ts->add(BOOST_TEST_CASE(&test_ThrowInvalidImageHandle));
   ts->add(BOOST_TEST_CASE(&test_Mult));
   ts->add(BOOST_TEST_CASE(&test_AddSub));
   ts->add(BOOST_TEST_CASE(&test_Interpolation));
diff --git a/modules/index.rst b/modules/index.rst
index 147274735b6617024bf345b5d88c6ce4b031c8fa..b2f5bc3fb85ae35f058f08ee1213537d1dfe896f 100644
--- a/modules/index.rst
+++ b/modules/index.rst
@@ -21,13 +21,14 @@ OpenStructure documentation
   gui/gui
   newmodule
   external
+  contributing
   
 For Starters
 --------------------------------------------------------------------------------
 
 **Installation**: `install from binary <http://www.openstructure.org/download/>`_ | :doc:`install from source <install>`
 
-**Tutorial Style**: :doc:`introduction <intro>` | :doc:`molecules intro <intro-01>` | :doc:`images intro <intro-02>` | :doc:`graphics intro <intro-03>`
+**Tutorial Style**: :doc:`introduction <intro>` | :doc:`molecules intro <intro-01>` | :doc:`images intro <intro-02>` | :doc:`graphics intro <intro-03>` 
 
 
 
@@ -35,7 +36,7 @@ For Starters
 Molecules
 --------------------------------------------------------------------------------
 
-**Overview**: :doc:`molecules intro <intro-01>` | :doc:`mol overview <mol/base/mol>` | :doc:`graphical entity<gfx/entity>` | :doc:`entity <mol/base/entity>`
+**Overview**: :doc:`molecules intro <intro-01>` | :doc:`mol overview <mol/base/mol>` | :doc:`graphical entity<gfx/entity>` | :doc:`entity <mol/base/entity>` | :doc:`queries <mol/base/query>`
 
 **Input/Output**: :ref:`loading and saving molecules <mol-io>`
 
@@ -85,7 +86,7 @@ Graphical User Interface
 Extending OpenStructure
 --------------------------------------------------------------------------------
 
-**Howto:** :doc:`write new modules <newmodule>` | :doc:`integrate third-party tools <external>` | :doc:`logging <base/logging>`
+**Howto:** :doc:`write new modules <newmodule>` | :doc:`integrate third-party tools <external>` | :doc:`logging <base/logging>` | :doc:`instructions for developers <contributing>`
 
 
 
diff --git a/modules/io/doc/io.rst b/modules/io/doc/io.rst
index b2037b3addfce4c660774d6177e33c261db729a6..141a1434cd0522e476dc605fea0e8c8976ea9cee 100644
--- a/modules/io/doc/io.rst
+++ b/modules/io/doc/io.rst
@@ -5,6 +5,7 @@
   :hidden:
   
   formats
+  profile
 
 .. module:: ost.io
   :synopsis: Input and output of sequences, alignments, structures, images and density maps.
@@ -61,6 +62,10 @@ parameters that affect the import. PDB files can be loaded with
 :func:`~ost.io.LoadPDB`. It offers a tighter control over the exact loading 
 behaviour.
 
+
+:doc:`profile`
+
+
 .. autofunction:: ost.io.LoadPDB
 
 
diff --git a/modules/io/doc/profile.rst b/modules/io/doc/profile.rst
new file mode 100644
index 0000000000000000000000000000000000000000..8df9254e5aaf1ba3554b1e4fc8c9d39b442ed764
--- /dev/null
+++ b/modules/io/doc/profile.rst
@@ -0,0 +1,125 @@
+IO Profiles for entity importer
+================================================================================
+
+.. currentmodule:: ost.io
+
+As of version 1.1, OpenStructure introduces IO profiles to fine-tune the
+behaviour of the molecule importers. A profile aggregates flags and methods
+that affect the import of molecular structures and influence both the behaviour
+of :mod:`~ost.conop` and :mod:`~ost.io`.
+
+Basic usage of IO profiles
+--------------------------------------------------------------------------------
+
+You are most certainly reading this document because you were having trouble
+loading PDB files. In that case, as a first step you will want to set the profile parameter of  :func:`LoadPDB`. The profile
+parameter can either be the name of a profile or an instance of
+:class:`IOProfile`. Both of the following two examples are equivalent:
+
+.. code-block:: python
+
+  ent=io.LoadPDB('weird.pdb', profile=io.profiles['SLOPPY'])
+  ent=io.LoadPDB('weird.pdb', profile='SLOPPY')
+
+Profiles is a dictionary-like object containing all the profiles known to OpenStructure. You can add new ones by inserting them into the dictionary. If you are loading a lot of structures, you may want to set the default profile to avoid having to pass the profile every time you load a structure. This is done by assigning a different profile to ``DEFAULT``:
+
+.. code-block:: python
+
+  io.profiles['DEFAULT']='SLOPPY'
+  ent=io.LoadPDB('weird.pdb')
+
+Again, you can either assign the name of the profile, or the profile itself. If none of the profiles available by default suits your needs, feel free to create one to your liking.
+
+Available default profiles
+--------------------------------------------------------------------------------
+
+The following profiles are available by default. For a detailed description of what the different parameters mean, consult the documentation of the :class:`IOProfile` class.
+
+STRICT
+
+  This profile is the default and is known to work very well with PDB files
+  coming from the official PDB website. It is equivalent to the following
+  profile:
+
+  .. code-block:: python
+
+    IOProfile(dialect='PDB', strict_hydrogens=False, quack_mode=False,
+              fault_tolerant=False, join_spread_atom_records=False,
+              no_hetatms=False)
+
+SLOPPY:
+
+  This profile loads essentially everything
+
+  .. code-block:: python
+
+    IOProfile(dialect='PDB', strict_hydrogens=False, quack_mode=True,
+              fault_tolerant=True, join_spread_atom_records=False,
+              no_hetatms=False)
+
+CHARMM:
+
+  This format is the default when importing CHARMM trajectories and turns on the
+  CHARMM specific compound dictionary.
+
+  .. code-block:: python
+
+    IOProfile(dialect='CHARMM', strict_hydrogens=False, quack_mode=True,
+              fault_tolerant=True, join_spread_atom_records=True,
+              no_hetatms=False)
+
+
+The IOProfile Class
+--------------------------------------------------------------------------------
+
+.. class:: IOProfile(quack_mode=False, dialect='PDB', strict_hydrogens=False, fault_tolerant=False)
+
+  Aggregates flags that control the import of molecular structures.
+
+  .. attribute:: quack_mode
+
+    :type: bool
+
+    Read/write property. When quack_mode is enabled, the chemical class for
+    unknown residues is guessed based on its atoms and connectivity. Turn this
+    on, if you are working with non-standard conforming PDB files and are
+    experiencing problems with the rendering of the backbone trace and/or see
+    peptidic residues with unknown chemical class.
+
+  .. attribute:: dialect
+
+    :type: str
+
+    The dialect to be used for PDB files. At the moment, this is either CHARMM
+    or PDB. More will most likely come in the future. By setting the dialect to
+    CHARMM, the loading is optimized for CHARMM PDB files. This turns on
+    support for chain names with length up to 4 characters (column 72-76) and
+    increase the size of the residue name to 4 residues.
+
+  .. attribute:: strict_hydrogens
+
+    :type: bool
+
+    Whether hydrogen names should be strictly checked.  It is very common for
+    PDB files to not follow the correct naming conventions for hydrogen atoms.
+    That's why by default, the names of the hydrogens are not required to be
+    correct. Rather, the connectivity is inferred with distance-based checks. By
+    turning this flag on, the names of the hydrogen atoms are checked against
+    the names in the database like all other atom types.
+    
+  .. attribute:: no_hetatms
+  
+    If set to true, HETATM records are ignored during import.
+    
+  .. attribute:: fault_tolerant
+
+    :type: bool
+
+    If true, the import will succeed, even if the PDB contains faulty records.
+    The faulty records will be ignored and import continues as if the records
+    haven't been present.
+    
+  .. attribute::   join_spread_atom_records
+  
+    If set to true, atom records belonging to the same residue are joined, even 
+    if they do not appear sequentially in the PDB file.
diff --git a/modules/io/pymod/__init__.py b/modules/io/pymod/__init__.py
index 265f868f24815905318db728434bfcd4c3008bb5..e5f0a7834083ef5e2ea387d34e007598a2053664 100644
--- a/modules/io/pymod/__init__.py
+++ b/modules/io/pymod/__init__.py
@@ -21,6 +21,43 @@ import os, tempfile, ftplib, httplib
 from _io import *
 from ost import mol, conop
 
+profiles=None
+
+class IOProfiles:
+  def __init__(self):
+     self._dict={}
+
+  def __getitem__(self, key):
+    return IOProfileRegistry.Instance().Get(key)
+
+  def __setitem__(self, key, value):
+    if isinstance(value, str):
+      value=self[value]
+    IOProfileRegistry.Instance().Set(key, value)
+    self._dict[key]=value
+
+  def __len__(self):
+    return len(self._dict)
+
+  def __iter__(self):
+    return self._dict.__iter__()
+
+if not profiles:
+  profiles=IOProfiles()
+  profiles['STRICT']=IOProfile(dialect='PDB', fault_tolerant=False,
+                               strict_hydrogens=False, quack_mode=False)
+  profiles['SLOPPY']=IOProfile(dialect='PDB', fault_tolerant=True,
+                               strict_hydrogens=False, quack_mode=True)
+  profiles['CHARMM']=IOProfile(dialect='CHARMM', fault_tolerant=True,
+                               strict_hydrogens=False, quack_mode=False)
+  profiles['DEFAULT']='STRICT'
+
+def _override(val1, val2):
+  if val2!=None:
+    return val2
+  else:
+    return val1
+
 def __GetModelFromPDB(model_id, output_dir, file_pattern='pdb%s.ent.gz'):
   file_name = file_pattern % model_id
   file_path = os.path.join(output_dir,file_name)
@@ -45,56 +82,70 @@ def __GetModelFromPDB(model_id, output_dir, file_pattern='pdb%s.ent.gz'):
       return False
   return os.path.getsize(file_path) > 0
 
-def LoadPDB(filename, restrict_chains="", no_hetatms=False,
-            fault_tolerant=False, load_multi=False,
-            join_spread_atom_records=False, calpha_only=False, 
-            remote=False, dialect='PDB', strict_hydrogens=False):
+def LoadPDB(filename, restrict_chains="", no_hetatms=None,
+            fault_tolerant=None, load_multi=False, quack_mode=None,
+            join_spread_atom_records=None, calpha_only=None,
+            profile='DEFAULT', remote=False, dialect=None,
+            strict_hydrogens=None):
   """
   Load PDB file from disk and returns one or more entities. Several options 
-  allow to customize the exact behaviour of the PDB import.
+  allow to customize the exact behaviour of the PDB import. For more information 
+  on these options, see :doc:`profile`.
+  
+  Residues are flagged as ligand if they are mentioned in a HET record.
 
   :param restrict_chains: If not an empty string, only chains listed in the
      string will be imported.
 
-  :param fault_tolerant: If True, the import will succeed, even if the
-     PDB contains faulty records. The faulty records will be ignored and import 
-     continues as if the records haven't been present.
+  :param fault_tolerant: Enable/disable fault-tolerant import. If set, overrides 
+     the value of :attr:`IOProfile.fault_tolerant`.
 
-  :param no_hetatms: If set to True, HETATM records will be ignored
+  :param no_hetatms: If set to True, HETATM records will be ignored. Overrides 
+      the value of :attr:`IOProfile.no_hetatms`
 
   :param load_multi: If set to True, a list of entities will be returned instead
-     of only the first. This is useful when dealing with multi-PDB files.
+      of only the first. This is useful when dealing with multi-PDB files.
 
-  :param join_spread_atom_records: If set to true, atom records belonging to the
-     same residue are joined, even if they do not appear sequentially in the PDB
-     file.
+  :param join_spread_atom_records: If set, overrides the value of 
+      :attr:`IOProfile.join_spread_atom_records`.
   
-  :param remote: If set to true, the method tries to load the pdb from the remote
-     pdb repository www.pdb.org.
+  :param remote: If set to true, the method tries to load the pdb from the 
+     remote pdb repository www.pdb.org. The filename is then interpreted as the 
+     pdb id.
+     
   :rtype: :class:`~ost.mol.EntityHandle` or a list thereof if `load_multi` is 
       True.
-  :param dialect: Specifies the particular dialect to use. By default, the 
-     official PDB format is used. Alternatively, by setting the dialect to 
-     CHARMM, the loading is optimized for CHARMM PDB files. This turns on 
-     support for chain names with length up to 4 characters (column 72-76) and 
-     increase the size of the residue name to 4 residues.
+
+  :param dialect: Specifies the particular dialect to use. If set, overrides 
+    the value of :attr:`IOProfile.dialect`
 
   :type dialect: :class:`str`
   
-  :param strict_hydrogens: whether hydrogen names should be strictly checked.  
-      It is very common for PDB files to not follow the correct naming 
-      conventions for hydrogen atoms. That's why by default, the names of the 
-      hydrogens are not required to be correct. Rather, the connectivity is 
-      inferred with distance-based checks. By turning this flag on, the names 
-      of the hydrogen atoms are checked against the names in the database like 
-      all other atom types.
+  :param strict_hydrogens: If set, overrides the value of 
+     :attr:`IOProfile.strict_hydrogens`.
 
   :raises: :exc:`~ost.io.IOException` if the import fails due to an erroneous or 
       inexistent file
   """
-  
-  if dialect not in ('PDB', 'CHARMM',):
+  def _override(val1, val2):
+    if val2!=None:
+      return val2
+    else:
+      return val1
+  if isinstance(profile, str):
+    prof=profiles[profile].Copy()
+  else:
+    prof=profile.Copy()
+  if dialect not in (None, 'PDB', 'CHARMM',):
     raise ValueError('dialect must be PDB or CHARMM')
+  prof.calpha_only=_override(prof.calpha_only, calpha_only)
+  prof.no_hetatms=_override(prof.no_hetatms, no_hetatms)
+  prof.dialect=_override(prof.dialect, dialect)
+  prof.quack_mode=_override(prof.quack_mode, quack_mode)
+  prof.strict_hydrogens=_override(prof.strict_hydrogens, strict_hydrogens)
+  prof.fault_tolerant=_override(prof.fault_tolerant, fault_tolerant)
+  prof.join_spread_atom_records=_override(prof.join_spread_atom_records,
+                                          join_spread_atom_records)
 
   if remote:
     output_dir = tempfile.gettempdir()
@@ -105,25 +156,13 @@ def LoadPDB(filename, restrict_chains="", no_hetatms=False,
   
   conop_inst=conop.Conopology.Instance()
   builder=conop_inst.GetBuilder("DEFAULT")
-  if dialect=='PDB':
+  if prof.dialect=='PDB':
     builder.dialect=conop.PDB_DIALECT
-  elif dialect=='CHARMM':
+  elif prof.dialect=='CHARMM':
     builder.dialect=conop.CHARMM_DIALECT
-  builder.strict_hydrogens=strict_hydrogens
-  reader=PDBReader(filename)
-  flags=0
-  if calpha_only:
-    flags|=PDB.CALPHA_ONLY
-  if fault_tolerant:
-    flags|=PDB.SKIP_FAULTY_RECORDS
-  if no_hetatms:
-    flags|=PDB.NO_HETATMS
-  if join_spread_atom_records:
-    flags|=PDB.JOIN_SPREAD_ATOM_RECORDS
-  if dialect=='CHARMM':
-    flags|=PDB.CHARMM_FORMAT
+  builder.strict_hydrogens=prof.strict_hydrogens
+  reader=PDBReader(filename, prof)
   try:
-    PDB.PushFlags(PDB.Flags() | flags)
     if load_multi:
       ent_list=[]
       while reader.HasNext():
@@ -133,7 +172,6 @@ def LoadPDB(filename, restrict_chains="", no_hetatms=False,
         ent_list.append(ent)
       if len(ent_list)==0:
         raise IOError("File doesn't contain any entities")
-      PDB.PopFlags()
       return ent_list
     else:
       ent=mol.CreateEntity()
@@ -142,13 +180,11 @@ def LoadPDB(filename, restrict_chains="", no_hetatms=False,
         conop_inst.ConnectAll(builder, ent, 0)
       else:
         raise IOError("File doesn't contain any entities")
-      PDB.PopFlags()
       return ent
   except:
-    PDB.PopFlags()
     raise
 
-def SavePDB(models, filename, dialect='PDB'):
+def SavePDB(models, filename, dialect=None,  pqr=False, profile='DEFAULT'):
   """
   Save entity or list of entities to disk. If a list of entities is supplied the 
   PDB file will be saved as a multi PDB file. Each of the entities is wrapped 
@@ -160,18 +196,18 @@ def SavePDB(models, filename, dialect='PDB'):
   """
   if not getattr(models, '__len__', None):
     models=[models]
-  writer=PDBWriter(filename, dialect=='CHARMM')
-  try:
-    if len(models)>1:
-      PDB.PushFlags(PDB.Flags() |PDB.WRITE_MULTIPLE_MODELS)
-    else:
-      PDB.PushFlags(0)
-    for model in models:
-      writer.Write(model)
-    PDB.PopFlags()
-  except:
-    PDB.PopFlags()
-    raise
+  if isinstance(profile, str):
+    profile=profiles[profile].Copy()
+  else:
+    profile.Copy()
+  profile.dialect=_override(profile.dialect, dialect)
+  writer=PDBWriter(filename, profile)
+  writer.SetIsPQR(pqr)
+  if len(models)>1:
+    writer.write_multi_model=True
+  for model in models:
+    writer.Write(model)
+
 try:
   from ost import img
   LoadMap = LoadImage
@@ -190,8 +226,9 @@ def LoadImageList (files):
 
 LoadMapList=LoadImageList
 
-def LoadCHARMMTraj(crd, dcd_file=None, lazy_load=False, stride=1, 
-                   dialect='CHARMM'):
+def LoadCHARMMTraj(crd, dcd_file=None, profile='CHARMM',
+                   lazy_load=False, stride=1, 
+                   dialect=None):
   """
   Load CHARMM trajectory file.
   
@@ -206,12 +243,15 @@ def LoadCHARMMTraj(crd, dcd_file=None, lazy_load=False, stride=1,
   :param stride: The spacing of the frames to load. When set to 2, for example, 
       every second frame is loaded from the trajectory. By default, every frame 
       is loaded.
-  :param dialect: The dialect for the PDB file to use. See :func:`LoadPDB`.
+  :param dialect: The dialect for the PDB file to use. See :func:`LoadPDB`. If 
+      set, overrides the value of the profile
+  :param profile: The IO profile to use for loading the PDB file. See 
+      :doc:`profile`.
   """
   if not isinstance(crd, mol.EntityHandle):
     if dcd_file==None:
       dcd_file='%s.dcd' % os.path.splitext(crd)[0]    
-    crd=LoadPDB(crd, dialect=dialect)
+    crd=LoadPDB(crd, profile=profile, dialect=dialect)
 
   else:
     if not dcd_file:
diff --git a/modules/io/pymod/export_pdb_io.cc b/modules/io/pymod/export_pdb_io.cc
index 27e62dc1c5f02cb3e8fd71c73660903823b98618..c057534e0a9e61b030ef89181d5dca5fac80e707 100644
--- a/modules/io/pymod/export_pdb_io.cc
+++ b/modules/io/pymod/export_pdb_io.cc
@@ -19,6 +19,7 @@
 #include <boost/python.hpp>
 using namespace boost::python;
 
+#include <ost/io/mol/io_profile.hh>
 #include <ost/io/mol/pdb_reader.hh>
 #include <ost/io/mol/pdb_writer.hh>
 using namespace ost;
@@ -32,40 +33,49 @@ BOOST_PYTHON_FUNCTION_OVERLOADS(load_PDB_ov, LoadPDB, 1, 2)
 void (PDBWriter::*write_a)(const mol::EntityHandle&)=&PDBWriter::Write;
 void (PDBWriter::*write_b)(const mol::EntityView&)=&PDBWriter::Write;
 
-namespace {
-  void push_flags(unsigned int x) {PDB::PushFlags(x);}
-  unsigned int flags() {return PDB::Flags();}
-  void pop_flags() {PDB::PopFlags();}
-}
-
 void export_pdb_io()
 {
-  {
-    scope pdb_scope=class_<PDB>("PDB",no_init)
-      .def("PushFlags",&PDB::PushFlags)
-      .staticmethod("PushFlags")
-      .def("Flags",&PDB::Flags)
-      .staticmethod("Flags")
-      .def("PopFlags",&PDB::PopFlags)
-      .staticmethod("PopFlags")
-      ;
-    pdb_scope.attr("NO_HETATMS")=PDB::NO_HETATMS;
-    pdb_scope.attr("SKIP_FAULTY_RECORDS")=PDB::SKIP_FAULTY_RECORDS;
-    pdb_scope.attr("WRITE_MULTIPLE_MODELS")=PDB::WRITE_MULTIPLE_MODELS;
-    pdb_scope.attr("JOIN_SPREAD_ATOM_RECORDS")=PDB::JOIN_SPREAD_ATOM_RECORDS;
-    pdb_scope.attr("CALPHA_ONLY")=PDB::CALPHA_ONLY;    
-    pdb_scope.attr("CHARMM_FORMAT")=PDB::CHARMM_FORMAT;
-  }
-
-  class_<PDBReader, boost::noncopyable>("PDBReader", init<String>())
+  class_<IOProfile>("IOProfile",
+         init<String,bool,bool,bool,bool,bool,bool>((arg("dialect")="PDB",
+                                                     arg("strict_hydrogens")=false,
+                                                     arg("quack_mode")=false,
+                                                     arg("fault_tolerant")=false,
+                                                     arg("join_spread_atom_records")=false,
+                                                     arg("no_hetatms")=false,
+                                                     arg("calpha_only")=false)))
+    .def_readwrite("dialect", &IOProfile::dialect)
+    .def_readwrite("fault_tolerant", &IOProfile::fault_tolerant)
+    .def_readwrite("quack_mode", &IOProfile::quack_mode)
+    .def_readwrite("strict_hydrogens", &IOProfile::strict_hydrogens)
+    .def_readwrite("no_hetatms", &IOProfile::no_hetatms)
+    .def_readwrite("calpha_only", &IOProfile::calpha_only)
+    .def_readwrite("join_spread_atom_records", &IOProfile::join_spread_atom_records)
+    .def("Copy", &IOProfile::Copy)
+    .def(self_ns::str(self))
+  ;
+  class_<IOProfileRegistry>("IOProfileRegistry", no_init)
+    .def("Get", &IOProfileRegistry::Get,  
+         return_value_policy<reference_existing_object>())
+    .def("Set", &IOProfileRegistry::Set)
+    .def("Instance", &IOProfileRegistry::Instance,
+         return_value_policy<reference_existing_object>()).staticmethod("Instance")
+    .def("GetDefault", &IOProfileRegistry::GetDefault,
+         return_value_policy<reference_existing_object>())
+  ;
+  class_<PDBReader, boost::noncopyable>("PDBReader", init<String, const IOProfile&>())
     .def("HasNext", &PDBReader::HasNext)
     .def("Import", &PDBReader::Import, 
          X_import(args("entity", "restrict_chains")))
   ;
   
-  class_<PDBWriter, boost::noncopyable>("PDBWriter", init<String>())
-    .def(init<String, bool>())
+  class_<PDBWriter, boost::noncopyable>("PDBWriter", init<String, const IOProfile&>())
     .def("Write", write_a)
+    .def("SetIsPQR", &PDBWriter::SetIsPQR)
+    .def("IsPQR", &PDBWriter::IsPQR)
+    .def("SetWriteMultiModel", &PDBWriter::SetWriteMultiModel)
+    .def("GetWriteMultiModel", &PDBWriter::GetWriteMultiModel)
+    .add_property("write_multi_model", &PDBWriter::GetWriteMultiModel, 
+                  &PDBWriter::SetWriteMultiModel)
     .def("Write", write_b)    
   ;
 }
diff --git a/modules/io/src/img/map_io_spi_handler.cc b/modules/io/src/img/map_io_spi_handler.cc
index 6b308f91218053490d1c9c1254ccc3cf5cf1b257..85a68a978724fc6c8d8c299ff90f7659b4d16000 100644
--- a/modules/io/src/img/map_io_spi_handler.cc
+++ b/modules/io/src/img/map_io_spi_handler.cc
@@ -152,7 +152,7 @@ void prep_header(spider_header& header, const img::Size& size, const geom::Vec3&
   String date_for_header=time_string.substr(8,2) + "-" + time_string.substr(4,3) + "-" +
                          time_string.substr(22,4) + " ";
   String time_for_header=time_string.substr(11,8);
-  String title_for_header = "Generated by OST (www.img.org)";
+  String title_for_header = "Generated by OST (www.openstructure.org)";
 
   header.fNslice = nslice;
   header.fNrow = nrow;
@@ -274,8 +274,8 @@ void header_filler(std::istream& in,  spider_header& header)
   f.read(header.szITit,160);  
 
 
-  if(header.fIform!=3.0) {
-  throw(ost::io::IOException("spiderRead: can only read 3 (3D volume)\n"));
+  if(header.fIform!=3.0  && header.fIform!=1.0) {
+  throw(ost::io::IOException("spiderRead: can only read modes 1 (2D image) or 3 (3D volume)\n"));
   }
 
 }
diff --git a/modules/io/src/mol/CMakeLists.txt b/modules/io/src/mol/CMakeLists.txt
index 8498858451420988e3a4132c6df570b30e35eff0..1201eb58fcff984f0bf0b5887a29f011ed6fd7ac 100644
--- a/modules/io/src/mol/CMakeLists.txt
+++ b/modules/io/src/mol/CMakeLists.txt
@@ -3,7 +3,6 @@ entity_io_crd_handler.cc
 entity_io_mae_handler.cc	
 pdb_reader.cc
 entity_io_pdb_handler.cc	
-pdb_io.cc
 pdb_writer.cc
 entity_io_sdf_handler.cc	
 sdf_reader.cc
@@ -13,6 +12,7 @@ load_entity.cc
 surface_io_msms_handler.cc
 load_surface.cc
 chemdict_parser.cc
+io_profile.cc
 dcd_io.cc
 star_parser.cc
 PARENT_SCOPE
@@ -21,21 +21,21 @@ PARENT_SCOPE
 set(OST_IO_MOL_HEADERS
 chemdict_parser.hh
 star_parser.hh
+io_profile.hh
 dcd_io.hh
-entity_io_crd_handler.hh	
-entity_io_mae_handler.hh	
-pdb_io.hh
-entity_io_handler.hh		
+entity_io_crd_handler.hh
+entity_io_mae_handler.hh
+entity_io_handler.hh
 pdb_reader.hh
-entity_io_pdb_handler.hh	
+entity_io_pdb_handler.hh
 pdb_writer.hh
-entity_io_sdf_handler.hh	
+entity_io_sdf_handler.hh
 sdf_reader.hh
 sdf_writer.hh
 save_entity.hh
-load_entity.hh			
+load_entity.hh
 surface_io_handler.hh
-load_surface.hh			
+load_surface.hh
 surface_io_msms_handler.hh
 PARENT_SCOPE
 )
diff --git a/modules/io/src/mol/chemdict_parser.cc b/modules/io/src/mol/chemdict_parser.cc
index 2668221bafab38c5f682497cbe416906c09756ad..4e52b087713971e27ce475f09db65efab63ff8ba 100644
--- a/modules/io/src/mol/chemdict_parser.cc
+++ b/modules/io/src/mol/chemdict_parser.cc
@@ -6,6 +6,10 @@ using namespace ost::conop;
   
 bool ChemdictParser::OnBeginData(const StringRef& data_name) 
 {    
+  if (data_name==StringRef("UNL",3)) {
+    compound_=CompoundPtr();
+    return false;    
+  }
   compound_.reset(new Compound(data_name.str()));
   compound_->SetDialect(dialect_);
   if (last_!=data_name[0]) {
@@ -119,7 +123,7 @@ void ChemdictParser::OnDataItem(const StarDataItem& item)
 
 void ChemdictParser::OnEndData()
 {
-  if (insert_) {
+  if (insert_ && compound_) {
     if (compound_->GetAtomSpecs().empty()) {
       compound_->AddAtom(atom_);
     }
diff --git a/modules/io/src/mol/dcd_io.cc b/modules/io/src/mol/dcd_io.cc
index b7723de0aabe173fe750774d1aa28e23a2bbc7db..9a59b2dbb62317d4e3a5b67e41a8c38b2913cb70 100644
--- a/modules/io/src/mol/dcd_io.cc
+++ b/modules/io/src/mol/dcd_io.cc
@@ -188,12 +188,18 @@ mol::CoordGroupHandle load_dcd(const mol::AtomHandleList& alist2,
                                const String& trj_fn,
                                unsigned int stride)
 {
+  std::ifstream istream(trj_fn.c_str(), std::ios::binary);
+  if(!istream) {
+    std::ostringstream msg;
+    msg << "LoadCHARMMTraj: cannot open " << trj_fn;
+    throw(IOException(msg.str()));
+  }
   Profile profile_load("LoadCHARMMTraj");
 
   mol::AtomHandleList alist(alist2);
   std::sort(alist.begin(),alist.end(),less_index);
   
-  std::ifstream istream(trj_fn.c_str(), std::ios::binary);
+  
   DCDHeader header; 
   bool swap_flag=false, skip_flag=false, gap_flag=false;
   read_dcd_header(istream, header, swap_flag, skip_flag, gap_flag);
@@ -286,7 +292,7 @@ void DCDCoordSource::FetchFrame(uint frame)
     read_dcd_header(stream_, header_, swap_flag_, skip_flag_, gap_flag_);
     frame_start_=stream_.tellg();
     loaded_=true;
-    frame_count_=header_.num;
+    frame_count_=header_.num/stride_;
   }
   size_t frame_size=calc_frame_size(skip_flag_, gap_flag_, 
                                     header_.t_atom_count);  
@@ -315,7 +321,7 @@ mol::CoordGroupHandle LoadCHARMMTraj(const mol::EntityHandle& ent,
     DCDCoordSource* source=new DCDCoordSource(alist, trj_fn, stride);
     return mol::CoordGroupHandle(DCDCoordSourcePtr(source));
   }
-    LOG_INFO("Importing CHARMM trajectory with lazy_load=false");  
+  LOG_INFO("Importing CHARMM trajectory with lazy_load=false");  
   return load_dcd(alist, trj_fn, stride);
 }
 
@@ -370,11 +376,11 @@ void write_dcd_hdr(std::ofstream& out,
 
 void SaveCHARMMTraj(const mol::CoordGroupHandle& coord_group, 
                     const String& pdb_filename, const String& dcd_filename,
-                    unsigned int stepsize)
+                    unsigned int stepsize, const IOProfile& profile)
 {  
   if(stepsize==0) stepsize=1;
   if(!pdb_filename.empty()) {
-    PDBWriter writer(pdb_filename, true);
+    PDBWriter writer(pdb_filename, profile);
     writer.Write(coord_group.GetAtomList());
   }
   std::ofstream out(dcd_filename.c_str(), std::ios::binary);
diff --git a/modules/io/src/mol/dcd_io.hh b/modules/io/src/mol/dcd_io.hh
index 24d189e634e5f7ec0289eb09680f6debf039a45a..217da0bf7ac82b81644ee0ebf53c22cda0f97ae9 100644
--- a/modules/io/src/mol/dcd_io.hh
+++ b/modules/io/src/mol/dcd_io.hh
@@ -26,9 +26,11 @@
 
 #include <ost/io/module_config.hh>
 #include <ost/mol/coord_group.hh>
-
+#include <ost/io/mol/io_profile.hh>
 namespace ost { namespace io {
 
+
+
 /*! \brief import a CHARMM trajectory in dcd format with an existing entity
     requires the existing entity and the trajectory file - obviously the
     atom layout of the entity must match the trajectory file
@@ -46,7 +48,8 @@ mol::CoordGroupHandle DLLEXPORT_OST_IO LoadCHARMMTraj(const mol::EntityHandle& e
 void DLLEXPORT_OST_IO SaveCHARMMTraj(const mol::CoordGroupHandle& coord_group, 
                                      const String& pdb_filename, 
                                      const String& dcd_filename,
-                                     unsigned int stride=1);
+                                     unsigned int stride=1,
+                                     const IOProfile& profile=IOProfile());
 
 
 }} // ns
diff --git a/modules/io/src/mol/entity_io_crd_handler.cc b/modules/io/src/mol/entity_io_crd_handler.cc
index 320db5d1d667f81a895096b170ecac51920ca0e4..9f646861c1671cc85cb5167c098639def16c4838 100644
--- a/modules/io/src/mol/entity_io_crd_handler.cc
+++ b/modules/io/src/mol/entity_io_crd_handler.cc
@@ -74,20 +74,29 @@ void CRDReader::Import(mol::EntityHandle& ent)
   while(std::getline(in_,line)) {
     if(line[0]!='*') break;
   }
+
   // line contains atom count
+  std::vector<String> line_content;
   boost::trim(line);
-  //int acount = boost::lexical_cast<int>(line);
-
-  while(std::getline(in_,line)) {
-    ParseAndAddAtom(line,ent);
-  }
+  boost::split(line_content,line,boost::is_any_of(" "));
+  
+  // expanded charmm CARD format check
+  if (line_content.size() > 1 || boost::lexical_cast<int>(line_content[0]) > 99999)
+    while(std::getline(in_,line)) {
+      ParseAndAddAtomExpanded(line,ent);
+    }
+  else
+    while(std::getline(in_,line)) {
+      ParseAndAddAtom(line,ent);
+    }
+  
   LOG_INFO("imported " << chain_count_ << " chains, " << residue_count_
                 << " residues, " << atom_count_ << " atoms");  
 }
 
 void CRDReader::ParseAndAddAtom(const String& line, mol::EntityHandle& ent)
 {
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
 
   LOG_TRACE( "line: [" << line << "]" );
 
@@ -142,14 +151,69 @@ void CRDReader::ParseAndAddAtom(const String& line, mol::EntityHandle& ent)
 
   // finally add atom
   LOG_DEBUG("adding atom " << aname << " (" << ele << ") @" << apos);
-  mol::AtomProp aprop;
-  aprop.element=ele;
-  aprop.radius=conop::Conopology::Instance().GetDefaultAtomRadius(ele);
-  aprop.is_hetatm=false;
-  aprop.b_factor=0.0;
-  aprop.occupancy=1.0;
+  mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, ele);
+  sequential_atom_list_.push_back(ah);
+  ++atom_count_;
+}
+	
+void CRDReader::ParseAndAddAtomExpanded(const String& line, mol::EntityHandle& ent)
+{
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   
-  mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, aprop);
+  LOG_TRACE( "line: [" << line << "]" );
+    
+  //int anum = boost::lexical_cast<int>(boost::trim_copy(line.substr(0,5)));
+  String aname = boost::trim_copy(line.substr(32,8));
+  String ele = aname.substr(0,1);
+  String rname = boost::trim_copy(line.substr(22,8));
+  int irnum = boost::lexical_cast<int>(boost::trim_copy(line.substr(112,8)));
+  String s_chain = boost::trim_copy(line.substr(102.8,8));
+  geom::Vec3 apos(boost::lexical_cast<Real>(boost::trim_copy(line.substr(40,20))),
+                  boost::lexical_cast<Real>(boost::trim_copy(line.substr(60,20))),
+                  boost::lexical_cast<Real>(boost::trim_copy(line.substr(80,20))));
+    
+  mol::ResidueKey rkey(rname);
+    
+  // some postprocessing
+  LOG_TRACE( "s_chain: [" << s_chain << "]" );
+    
+  mol::ResNum rnum(irnum);
+  
+  // determine chain and residue update
+  bool update_chain=false;
+  bool update_residue=false;
+  if(!curr_chain_) {
+    update_chain=true;
+    update_residue=true;
+  } else if(curr_chain_.GetName()!=s_chain) {
+    update_chain=true;
+    update_residue=true;
+  }
+    
+  if(!curr_residue_) {
+    update_residue=true;
+  } else if(curr_residue_.GetNumber()!=rnum) {
+    update_residue=true;
+  }
+    
+  if(update_chain) {  
+    if (!(curr_chain_=ent.FindChain(s_chain))) {
+      LOG_DEBUG("new chain " << s_chain);      
+      curr_chain_=editor.InsertChain(s_chain);
+      ++chain_count_;      
+    }
+  }
+    
+  if(update_residue) {
+    LOG_DEBUG("new residue " << rkey << " " << rnum);
+    curr_residue_=editor.AppendResidue(curr_chain_, rkey, rnum);
+    assert(curr_residue_.IsValid());
+    ++residue_count_;
+  }
+    
+  // finally add atom
+  LOG_DEBUG("adding atom " << aname << " (" << ele << ") @" << apos);
+  mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, ele);
   sequential_atom_list_.push_back(ah);
   ++atom_count_;
 }
@@ -171,7 +235,15 @@ void CRDWriter::WriteHeader(const mol::EntityView& ent)
 {
   outstream_  << "* COOR FILE CREATED BY OPENSTRUCTURE" << std::endl;
   outstream_  << "*" << std::endl;
-  outstream_  << ent.GetAtomCount() << std::endl;
+  
+  atom_total_ = ent.GetAtomCount();
+	
+  if (atom_total_ > 99999) {
+    outstream_  << format("%10i") % ent.GetAtomCount() << "  EXT" << std::endl;
+  }
+  else {
+    outstream_  << format("%5i") % ent.GetAtomCount() << std::endl;
+  }
 }
 
 bool CRDWriter::VisitAtom(const mol::AtomHandle& atom)
@@ -181,19 +253,34 @@ bool CRDWriter::VisitAtom(const mol::AtomHandle& atom)
   if (e_name=="") {
     e_name="MOL";
   }
+	
   mol::ResidueHandle res=atom.GetResidue();
-  outstream_  << format("%5i") % atom_count_
-              << format("%5i") % res.GetNumber() << " "
-              << format("%4s") % res.GetKey() << " "
-              << format("%-4s") % atom.GetName()
-              << format("%10.5f") % atom.GetPos().x
-              << format("%10.5f") % atom.GetPos().y
-              << format("%10.5f") % atom.GetPos().z << " "
-              << format("%-4s") % e_name << " "
-              << format("%-5i") % res.GetNumber() << " "
-              << format("%8.5f") % atom.GetBFactor()
-              << std::endl;
 
+  if (atom_total_ > 99999) {
+    outstream_  << format("%10i") % atom_count_
+                << format("%10i") % res.GetNumber() << "  "
+          	    << format("%-8s") % res.GetKey() << "  "
+                << format("%-8s") % atom.GetName()
+                << format("%20.10f") % atom.GetPos().x
+                << format("%20.10f") % atom.GetPos().y
+                << format("%20.10f") % atom.GetPos().z << "  "
+                << format("%-8s") % e_name << "  "
+                << format("%-8i") % res.GetNumber()
+                << format("%20.10f") % atom.GetBFactor()
+                << std::endl;
+  } else {
+    outstream_  << format("%5i") % atom_count_
+                << format("%5i") % res.GetNumber() << " "
+			    << format("%4s") % res.GetKey() << " "
+                << format("%-4s") % atom.GetName()
+                << format("%10.5f") % atom.GetPos().x
+                << format("%10.5f") % atom.GetPos().y
+                << format("%10.5f") % atom.GetPos().z << " "
+                << format("%-4s") % e_name << " "
+                << format("%-5i") % res.GetNumber() << " "
+                << format("%8.5f") % atom.GetBFactor()
+                << std::endl;
+  }
   return true;
 }
 
@@ -264,7 +351,7 @@ mol::EntityHandle LoadCRD(const String& file_name)
   conop::BuilderP builder = conop::Conopology::Instance().GetBuilder();  
   CRDReader reader(file_name);
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   reader.Import(ent);
   conop::Conopology::Instance().ConnectAll(builder,ent);    
   return ent;
diff --git a/modules/io/src/mol/entity_io_crd_handler.hh b/modules/io/src/mol/entity_io_crd_handler.hh
index 29ffa6705e78e7b3b0fcd768bba00a13435843cd..f32693025458919f459644fc5fe1fd30ef1eeb97 100644
--- a/modules/io/src/mol/entity_io_crd_handler.hh
+++ b/modules/io/src/mol/entity_io_crd_handler.hh
@@ -41,6 +41,7 @@ public:
 private:
 
   void ParseAndAddAtom(const String& line, mol::EntityHandle& h);
+  void ParseAndAddAtomExpanded(const String& line, mol::EntityHandle& h);
 
   std::vector<mol::AtomHandle> sequential_atom_list_;
   mol::ChainHandle curr_chain_;
@@ -67,6 +68,7 @@ private:
   std::ofstream   outfile_;
   std::ostream&   outstream_;
   int atom_count_;
+  int atom_total_;
 };
 
 class DLLEXPORT_OST_IO EntityIOCRDHandler: public EntityIOHandler {
diff --git a/modules/io/src/mol/entity_io_mae_handler.cc b/modules/io/src/mol/entity_io_mae_handler.cc
index e810c9089efc13896ce0e418815e846a27ba43cb..0322c18cc9f9862857a086553313d81b07a4b311 100644
--- a/modules/io/src/mol/entity_io_mae_handler.cc
+++ b/modules/io/src/mol/entity_io_mae_handler.cc
@@ -58,7 +58,7 @@ using boost::format;
         if(in_string) {
           if(line[p1]=='"') {
             in_string=false;
-            nrvo.push_back(line.substr(p0,p1-p0));
+            nrvo.push_back(std::string(line.substr(p0,p1-p0)));
             ++p1;
             p0=p1;
             while(isspace(line[p1]) && p1<line.size()) {++p0;++p1;}
@@ -66,7 +66,7 @@ using boost::format;
           }
         } else {
           if(isspace(line[p1])) {
-            nrvo.push_back(line.substr(p0+1,p1-p0-1));
+            nrvo.push_back(std::string(line.substr(p0+1,p1-p0-1)));
             ++p1;
             p0=p1;
             while(isspace(line[p1]) && p1<line.size()) {++p0;++p1;}
@@ -119,32 +119,40 @@ void MAEReader::Import(mol::EntityHandle& ent)
   int i_res_num=-1;
   int i_chain_name=-1;
 
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
-
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
+  
   while(std::getline(in_,line)) {
     line = boost::trim_copy(line);
     if(in_ct_block) {
       if(in_atom_block) {
         if(parsing_atoms) {
           if(boost::regex_match(line,r_delim)) {
-            LOG_DEBUG( "stopping atom parsing" );
+            LOG_TRACE( "stopping atom parsing" );
             parsing_atoms=false;
             prop_list.clear();
+            i_atom_name=-1;
+            i_atom_xpos=-1;
+            i_atom_ypos=-1;
+            i_atom_zpos=-1;
+            i_res_name=-1;
+            i_res_num=-1;
+            i_chain_name=-1;
           } else {
             // parsing atom line
             std::vector<std::string> tokens=tokenize(line);
             for(size_t i=0;i<tokens.size();++i) {
-              LOG_DEBUG( "[" << tokens[i] << "] ");
+              LOG_TRACE( "[" << tokens[i] << "] ");
             }
-            LOG_DEBUG("");
+            LOG_TRACE("");
+
             add_atom(ent,editor,
-                     tokens[i_atom_name],
-                     tokens[i_atom_xpos],
-                     tokens[i_atom_ypos],
-                     tokens[i_atom_zpos],
-                     tokens[i_res_name],
-                     tokens[i_res_num],
-                     tokens[i_chain_name]);
+                     i_atom_name>=0 && i_atom_name<(int)tokens.size() ? tokens[i_atom_name] : "X",
+                     i_atom_xpos>=0 && i_atom_xpos<(int)tokens.size() ? tokens[i_atom_xpos] : "0",
+                     i_atom_ypos>=0 && i_atom_ypos<(int)tokens.size() ? tokens[i_atom_ypos] : "0",
+                     i_atom_zpos>=0 && i_atom_zpos<(int)tokens.size() ? tokens[i_atom_zpos] : "0",
+                     i_res_name>=0 && i_res_name<(int)tokens.size() ? tokens[i_res_name] : "X",
+                     i_res_num>=0 && i_res_num<(int)tokens.size() ? tokens[i_res_num] : "0",
+                     i_chain_name>=0 && i_chain_name<(int)tokens.size() ? tokens[i_chain_name] : "X");
           }
         } else { // not parsing atoms
           if(boost::regex_match(line,r_delim)) {
@@ -153,21 +161,20 @@ void MAEReader::Import(mol::EntityHandle& ent)
                i_atom_ypos==-1 ||
                i_atom_zpos==-1 ||
                i_res_name==-1 ||
-               i_res_num==-1 ||
-               i_chain_name==-1) {
+               i_res_num==-1) {
               throw IOException("missing atom prop");
             }
-            LOG_DEBUG( "starting atom parsing" );
+            LOG_TRACE( "starting atom parsing" );
             parsing_atoms=true;
           } else if(line[0]=='}') {
-            LOG_DEBUG( "exiting atom block" );
+            LOG_TRACE( "exiting atom block" );
             in_atom_block=false;
           } else {
             // parsing property line
             if(line[0]!='#') {
               int pid=prop_list.size()+1;
               prop_list.push_back(line);
-              LOG_DEBUG( "found property '" << prop_list.back() << "' id=" << pid );
+              LOG_TRACE( "found property '" << prop_list.back() << "' id=" << pid );
               if(line=="s_m_pdb_atom_name") i_atom_name=pid;
               else if(line=="r_m_x_coord") i_atom_xpos=pid;
               else if(line=="r_m_y_coord") i_atom_ypos=pid;
@@ -180,16 +187,16 @@ void MAEReader::Import(mol::EntityHandle& ent)
         }
       } else { // not in atom block
         if(boost::regex_match(line,r_atom_block)) {
-          LOG_DEBUG( "entering atom block" );
+          LOG_TRACE( "entering atom block" );
           in_atom_block=true;
         } else if(line[0]=='}') {
-          LOG_DEBUG( "exiting ct block" );
+          LOG_TRACE( "exiting ct block" );
           in_ct_block=false;
         }
       }
     } else { // not in ct block
       if(boost::regex_match(line,r_ct_block)) {
-        LOG_DEBUG( "entering ct block" );
+        LOG_TRACE( "entering ct block" );
         in_ct_block=true;
       }
     }
@@ -213,7 +220,7 @@ void MAEReader::add_atom(mol::EntityHandle ent,
   std::string aname=boost::trim_copy(aname2);
   std::string rname=boost::trim_copy(rname2);
   std::string cname=boost::trim_copy(cname2);
-  std::string ele=aname.substr(0,1);
+  std::string ele=aname.empty() ? "X" : aname.substr(0,1);
   if(isdigit(ele[0])) ele="H";
 
   int irnum = atoi(s_rnum.c_str());
@@ -245,10 +252,10 @@ void MAEReader::add_atom(mol::EntityHandle ent,
   if(update_chain) {  
     if (!(curr_chain_=ent.FindChain(cname))) {
       curr_chain_=editor.InsertChain(cname);
-      LOG_DEBUG("new chain " << curr_chain_);      
+      LOG_TRACE("new chain " << curr_chain_);      
       ++chain_count_;      
     } else {
-      LOG_DEBUG("old chain " << curr_chain_);      
+      LOG_TRACE("old chain " << curr_chain_);      
     }
   }
 
@@ -256,22 +263,16 @@ void MAEReader::add_atom(mol::EntityHandle ent,
     if (!(curr_residue_=curr_chain_.FindResidue(rnum))) {
       curr_residue_=editor.AppendResidue(curr_chain_, rkey, rnum);
       assert(curr_residue_.IsValid());
-      LOG_DEBUG(" new residue " << curr_residue_);
+      LOG_TRACE(" new residue " << curr_residue_);
       ++residue_count_;
     } else {
-      LOG_DEBUG(" old residue " << curr_residue_);
+      LOG_TRACE(" old residue " << curr_residue_);
     }
   }
 
   // finally add atom
-  LOG_DEBUG("  atom " << aname << " (" << ele << ") @" << apos);
-  mol::AtomProp aprop;
-  aprop.element=ele;
-  aprop.radius=conop::Conopology::Instance().GetDefaultAtomRadius(ele);
-  aprop.is_hetatm=false;
-  aprop.b_factor=0.0;
-  aprop.occupancy=1.0;
-  mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, aprop);
+  LOG_TRACE("  atom " << aname << " (" << ele << ") @" << apos);
+  mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, ele);
 }
   
 
@@ -331,7 +332,7 @@ mol::EntityHandle LoadMAE(const String& file_name)
   conop::BuilderP builder = conop::Conopology::Instance().GetBuilder();  
   MAEReader reader(file_name);
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   reader.Import(ent);
   conop::Conopology::Instance().ConnectAll(builder,ent);    
   return ent;
diff --git a/modules/io/src/mol/entity_io_pdb_handler.cc b/modules/io/src/mol/entity_io_pdb_handler.cc
index 99b8ea49560a7dbe9ef2ca79ab9dbbc855c94dbe..bd4fe5ee25a84f39af2595eb46c268065757374f 100644
--- a/modules/io/src/mol/entity_io_pdb_handler.cc
+++ b/modules/io/src/mol/entity_io_pdb_handler.cc
@@ -48,20 +48,17 @@ bool EntityIOPDBHandler::RequiresBuilder() const
 void EntityIOPDBHandler::Export(const mol::EntityView& ent,
                                 const boost::filesystem::path& loc) const 
 {
-  PDBWriter writer(loc);
+  PDBWriter writer(loc, IOProfileRegistry::Instance().GetDefault());
   if (boost::iequals(boost::filesystem::extension(loc), ".pqr")) {
-    PDB::PushFlags(PDB::Flags() | PDB::PQR_FORMAT);
-    writer.Write(ent);
-    PDB::PopFlags();
-  } else {
-    writer.Write(ent);
+    writer.SetIsPQR(true);
   }
+  writer.Write(ent);
 }
 
 void EntityIOPDBHandler::Import(mol::EntityHandle& ent, 
                                 std::istream& stream)
 {
-  PDBReader reader(stream);
+  PDBReader reader(stream, IOProfileRegistry::Instance().GetDefault());
   if (reader.HasNext()) {
     reader.Import(ent, "");
   }
@@ -70,7 +67,7 @@ void EntityIOPDBHandler::Import(mol::EntityHandle& ent,
 void EntityIOPDBHandler::Export(const mol::EntityView& ent,
                                 std::ostream& stream) const 
 {
-  PDBWriter writer(stream);
+  PDBWriter writer(stream, IOProfileRegistry::Instance().GetDefault());
   writer.Write(ent);
 }
 
@@ -99,7 +96,7 @@ bool pdb_handler_is_responsible_for(const boost::filesystem::path& loc,
 void EntityIOPDBHandler::Import(mol::EntityHandle& ent,
                                 const boost::filesystem::path& loc)
 {
-  PDBReader reader(loc);
+  PDBReader reader(loc, IOProfileRegistry::Instance().GetDefault());
   if (reader.HasNext()) {
     reader.Import(ent, "");
   }
diff --git a/modules/io/src/mol/io_profile.cc b/modules/io/src/mol/io_profile.cc
new file mode 100644
index 0000000000000000000000000000000000000000..d27f3918f055cc12b754c4b9e84c1a80efaaacc4
--- /dev/null
+++ b/modules/io/src/mol/io_profile.cc
@@ -0,0 +1,16 @@
+#include "io_profile.hh"
+
+namespace ost { namespace io {
+
+IOProfileRegistry& IOProfileRegistry::Instance()
+{
+  static IOProfileRegistry reg;
+  return reg;
+}
+
+IOProfileRegistry::IOProfileRegistry()
+{
+  profiles_["DEFAULT"]=IOProfile();
+}
+
+}}
diff --git a/modules/io/src/mol/io_profile.hh b/modules/io/src/mol/io_profile.hh
new file mode 100644
index 0000000000000000000000000000000000000000..0fe9ffc2f7fbda8e76d5364b79f68c7e4574c226
--- /dev/null
+++ b/modules/io/src/mol/io_profile.hh
@@ -0,0 +1,90 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#ifndef OST_IO_IO_PROFILE_HH
+#define OST_IO_IO_PROFILE_HH
+
+#include <iostream>
+#include <map>
+#include <ost/mol/entity_handle.hh>
+#include <ost/io/module_config.hh>
+namespace ost { namespace io {
+
+struct DLLEXPORT IOProfile {
+public:
+  IOProfile(String d, bool sh, bool qm, bool ft, bool js, bool nh, bool co):
+    dialect(d), strict_hydrogens(sh), quack_mode(qm), fault_tolerant(ft),
+    join_spread_atom_records(js), no_hetatms(nh), calpha_only(co)
+  { }
+  IOProfile(): dialect("PDB"), strict_hydrogens(true), quack_mode(false),
+    fault_tolerant(false), join_spread_atom_records(false), no_hetatms(false),
+    calpha_only(false)
+  { }
+  virtual ~IOProfile() { }
+
+  String dialect;
+  bool   strict_hydrogens;
+  bool   quack_mode;
+  bool   fault_tolerant;
+  bool   join_spread_atom_records;
+  bool   no_hetatms;
+  bool   calpha_only;
+
+  IOProfile Copy()
+  {
+    return IOProfile(dialect, strict_hydrogens, quack_mode, fault_tolerant,
+                     join_spread_atom_records, no_hetatms, calpha_only);
+  }
+  virtual void PostImport(mol::EntityHandle ent) { }
+};
+
+inline  std::ostream& operator<<(std::ostream& stream, const IOProfile& p)
+{
+  stream << "IOProfile(dialect='" << p.dialect << "', strict_hydrogens="
+         << (p.strict_hydrogens ? "True" : "False") << ", quack_mode="
+         << (p.quack_mode ? "True" : "False") << ", join_spread_atom_records="
+         << (p.join_spread_atom_records ? "True" : "False") << ", no_hetatms="
+         << (p.no_hetatms ? "True" : "False") << ", calpha_only="
+         << (p.calpha_only ? "True" : "False") << ", fault_tolerant="
+         << (p.fault_tolerant ? "True" : "False") << ")";
+  return stream;
+}
+
+class DLLEXPORT_OST_IO IOProfileRegistry {
+public:
+  static IOProfileRegistry& Instance();
+  
+  IOProfile& Get(const String& key) 
+  { 
+    return profiles_[key];
+  }
+  
+  void Set(const String& key, const IOProfile& profile)
+  {
+    profiles_[key]=profile;
+  }
+  
+  IOProfile& GetDefault() { return profiles_["DEFAULT"]; }
+private:
+  IOProfileRegistry();
+  std::map<String, IOProfile> profiles_;
+};
+
+}}
+
+#endif
diff --git a/modules/io/src/mol/load_entity.cc b/modules/io/src/mol/load_entity.cc
index 4eda99b4a01acb435819e0a9f3905e5e01db9a39..f35178546f766148e7d5317a1c1286969ca90198 100644
--- a/modules/io/src/mol/load_entity.cc
+++ b/modules/io/src/mol/load_entity.cc
@@ -60,7 +60,7 @@ mol::EntityHandle LoadEntity(const String& filename, int flag)
 {
   LOG_DEBUG("creating emtpy entity");
   mol::EntityHandle eh=mol::CreateEntity();
-  mol::XCSEditor xcs_lock=eh.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor xcs_lock=eh.EditXCS(mol::BUFFERED_EDIT);
   Import(eh,filename,flag);
   return eh;
 }
diff --git a/modules/io/src/mol/pdb_io.cc b/modules/io/src/mol/pdb_io.cc
deleted file mode 100644
index eba9c8877083eaea23bbb1ad81269269fe8d6d96..0000000000000000000000000000000000000000
--- a/modules/io/src/mol/pdb_io.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-//------------------------------------------------------------------------------
-// This file is part of the OpenStructure project <www.openstructure.org>
-//
-// Copyright (C) 2008-2010 by the OpenStructure authors
-//
-// This library 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 3.0 of the License, or (at your option)
-// any later version.
-// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-//------------------------------------------------------------------------------
-#include "pdb_io.hh"
-
-namespace ost { namespace io {
-
-  PDB& PDB::Instance() {
-    static PDB x;
-    return x;
-  }
-
-  const unsigned int PDB::SKIP_FAULTY_RECORDS=0x1;
-  const unsigned int PDB::NO_HETATMS=0x2;
-  const unsigned int PDB::WRITE_MULTIPLE_MODELS=0x4;
-  const unsigned int PDB::PQR_FORMAT=0x8;
-  const unsigned int PDB::JOIN_SPREAD_ATOM_RECORDS=0x10;
-  const unsigned int PDB::CALPHA_ONLY=0x20;
-  const unsigned int PDB::CHARMM_FORMAT=0x40;  
-
-  void PDB::PushFlags(unsigned int flags) {PDB::Instance().fstack.push(flags);}
-  unsigned int PDB::Flags() {return PDB::Instance().fstack.empty() ? 0 : PDB::Instance().fstack.top();}
-  void PDB::PopFlags() {PDB::Instance().fstack.pop();}
-
-
-}} // ns
diff --git a/modules/io/src/mol/pdb_io.hh b/modules/io/src/mol/pdb_io.hh
deleted file mode 100644
index c4fc19e035f2b6bf02d135facf06091cb1c38250..0000000000000000000000000000000000000000
--- a/modules/io/src/mol/pdb_io.hh
+++ /dev/null
@@ -1,92 +0,0 @@
-//------------------------------------------------------------------------------
-// This file is part of the OpenStructure project <www.openstructure.org>
-//
-// Copyright (C) 2008-2010 by the OpenStructure authors
-//
-// This library 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 3.0 of the License, or (at your option)
-// any later version.
-// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-//------------------------------------------------------------------------------
-#ifndef OST_IO_PDB_IO_HH
-#define OST_IO_PDB_IO_HH
-
-#include <stack>
-#include <ost/io/module_config.hh>
-
-namespace ost { namespace io {
-  
-
-/// \brief flags that incluence the behaviour of the PDBReader and PDBWriter
-struct DLLEXPORT_OST_IO PDB {
-
-    /// \brief skip faulty records
-    /// This flag tells the PDB loader to ignore faulty records. By default,
-    /// faulty records abort import.
-  static const unsigned int SKIP_FAULTY_RECORDS;
-
-    /// \brief do not import HETATM records
-  static const unsigned int NO_HETATMS;
-
-    /// \brief enable writing of multiple models
-  static const unsigned int WRITE_MULTIPLE_MODELS;
-
-    /// \brief enable for PQR
-  static const unsigned int PQR_FORMAT;
-
-  /// \brief enables parsing of charmm-style PDBs
-  /// 
-  /// CHARMM files don't use the chain column to mark different chains, but 
-  /// rather put the name in the last columns that is isually used for the atom 
-  /// element an occupancy. Note that it is perfectly possible to parse CHARRM 
-  /// PDB files without this flag, but the mileage may vary as some of the 
-  /// elements are incorrectly assigned.
-  static const unsigned int CHARMM_FORMAT;
-  
-  /// \brief Join atom records into one residue, even if the atom records
-  ///     are not sequential.
-  /// 
-  /// This is useful in the following case:
-  /// 
-  /// \verbatim
-  /// ATOM     43  N  AALA P   4
-  /// ATOM     45  CA AALA P   4 
-  /// ATOM     47  C  AALA P   4
-  /// ATOM     48  O  AALA P   4
-  /// ATOM     49  N  APRO P   5
-  /// ATOM     50  CD APRO P   5
-  /// ATOM     53  CA APRO P   5
-  /// ATOM     55  CB APRO P   5
-  /// ATOM     58  CG APRO P   5
-  /// ATOM     61  C  APRO P   5
-  /// ATOM     62  O  APRO P   5
-  /// ATOM    550  CB AALA P   4
-  /// \endverbatim
-  /// 
-  /// By default, the atom 550 will start a new residue instead of being
-  /// joined with atoms 43-48 into one residue.
-  static const unsigned int JOIN_SPREAD_ATOM_RECORDS;
-
-    /// \brief only import C-alpha atoms
-  static const unsigned int CALPHA_ONLY;
-
-  static void PushFlags(unsigned int flags);
-  static unsigned int Flags();
-  static void PopFlags();
-
-  static PDB& Instance();
-
-  std::stack<unsigned int> fstack;
-};
-
-}}
-
-#endif
diff --git a/modules/io/src/mol/pdb_reader.cc b/modules/io/src/mol/pdb_reader.cc
index 6fad3dc2c2b9fa3c0b2ae0fc86c010e115ac119e..5d5f121dd18d1b6b1a4bf0773231c5fcc2785a8c 100644
--- a/modules/io/src/mol/pdb_reader.cc
+++ b/modules/io/src/mol/pdb_reader.cc
@@ -47,7 +47,7 @@ bool IEquals(const StringRef& a, const StringRef& b)
     return false;
   }
   for (size_t i=0; i<a.size(); ++i) {
-    if (toupper(a[i])!=toupper(b[i])) {
+    if (toupper(a[i])!=b[i]) {
       return false;
     }
   }
@@ -61,26 +61,29 @@ mol::ResNum to_res_num(int num, char ins_code)
 
 }
 
-PDBReader::PDBReader(std::istream& instream):
-  infile_(), instream_(instream)
+PDBReader::PDBReader(std::istream& instream, const IOProfile& profile):
+  infile_(), instream_(instream), profile_(profile)
 {
   this->Init(boost::filesystem::path(""));
 }
 
-PDBReader::PDBReader(const String& filename)
-  : infile_(filename), instream_(infile_)
+PDBReader::PDBReader(const String& filename, const IOProfile& profile)
+  : infile_(filename), instream_(infile_), profile_(profile)
 {
   this->Init(boost::filesystem::path(filename));
 }
 
-PDBReader::PDBReader(const boost::filesystem::path& loc):
-  infile_(loc), instream_(infile_)
+PDBReader::PDBReader(const boost::filesystem::path& loc, 
+                     const IOProfile& profile):
+  infile_(loc), instream_(infile_), profile_(profile)
 {
   this->Init(loc);
 }
 
 void PDBReader::Init(const boost::filesystem::path& loc)
 {
+  warned_name_mismatch_=false;
+  charmm_style_=profile_.dialect=="CHARMM";
   num_model_records_=0;
   if (boost::iequals(".gz", boost::filesystem::extension(loc))) {
     in_.push(boost::iostreams::gzip_decompressor());
@@ -108,12 +111,13 @@ bool PDBReader::HasNext()
      StringRef curr_line(curr_line_.c_str(), curr_line_.length());
      if (curr_line.size()>5 && 
          (IEquals(curr_line.substr(0, 6), StringRef("ATOM  ", 6)) ||
-         (!(PDB::Flags() & PDB::NO_HETATMS) &&
+         (!profile_.no_hetatms &&
           IEquals(curr_line.substr(0, 6),StringRef("HETATM ", 6))) ||
           IEquals(curr_line.substr(0, 6),StringRef("ANISOU ", 6)) ||
          IEquals(curr_line.substr(0, 6), StringRef("SHEET ", 6)) ||
          IEquals(curr_line.substr(0, 6), StringRef("HELIX ", 6)) ||
-         IEquals(curr_line.substr(0, 6), StringRef("MODEL ", 6)))) {
+         IEquals(curr_line.substr(0, 6), StringRef("MODEL ", 6)) ||
+         IEquals(curr_line.substr(0, 6), StringRef("HET   ", 6)))) {
        return true;
      } else if (IEquals(curr_line.rtrim(), StringRef("END", 3))) {
        hard_end_=true;
@@ -126,7 +130,7 @@ bool PDBReader::HasNext()
 void PDBReader::Import(mol::EntityHandle& ent,
                        const String& restrict_chains)
 {
-  LOG_DEBUG("PDBReader: current flags: " << PDB::Flags());
+  LOG_DEBUG("PDBReader: " << profile_);
 
   Profile profile_import("PDBReader::Import");
   this->ClearState();
@@ -149,7 +153,7 @@ void PDBReader::Import(mol::EntityHandle& ent,
           this->ParseAndAddAtom(curr_line, line_num_, ent, 
                                 StringRef("ATOM", 4));
         } else if (IEquals(curr_line.substr(0, 6), StringRef("ANISOU", 6))) {
-          if (!(PDB::Flags() & PDB::CHARMM_FORMAT)) {
+          if (!charmm_style_) {
             LOG_TRACE("processing ANISOU entry");
             this->ParseAnisou(curr_line, line_num_, ent);            
           }
@@ -179,15 +183,30 @@ void PDBReader::Import(mol::EntityHandle& ent,
           continue;
         }
         if (IEquals(curr_line.substr(0, 6), StringRef("HETATM", 6))) {
-          if (PDB::Flags() & PDB::NO_HETATMS)
+          if (profile_.no_hetatms)
             continue;
           LOG_TRACE("processing HETATM entry");
           this->ParseAndAddAtom(curr_line, line_num_, ent, 
                                 StringRef("HETATM", 6));
         } else if (IEquals(curr_line.substr(0, 6), StringRef("HELIX ", 6))) {
-          if (!(PDB::Flags() & PDB::CHARMM_FORMAT)) {
+          if (!charmm_style_) {
             this->ParseHelixEntry(curr_line);            
           }
+        } else if (IEquals(curr_line.substr(0, 6), StringRef("HET   ", 6))) {
+          // remember het entry to mark the residues as ligand during ATOM import
+          char chain=curr_line[12];
+          std::pair<bool, int> num=curr_line.substr(13, 4).ltrim().to_int();
+          if (!num.first) {
+            if (profile_.fault_tolerant) {
+              LOG_WARNING("Invalid HET entry on line " << line_num_);
+              continue;
+            } else {
+              String msg=str(format("Invalid HET entry on line %d")%line_num_);
+              throw IOException(msg);
+            }
+          }
+          hets_.push_back(HetEntry(chain, to_res_num(num.second,
+                                   curr_line[17])));
         }
         break;
       case 'M':
@@ -200,7 +219,7 @@ void PDBReader::Import(mol::EntityHandle& ent,
           if (num_model_records_<2) {
             continue;
           }
-          if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+          if (profile_.fault_tolerant) {
             go_on=false;
             num_model_records_=1;
             break;
@@ -215,7 +234,7 @@ void PDBReader::Import(mol::EntityHandle& ent,
           continue;
         }
         if (IEquals(curr_line.substr(0, 6), StringRef("SHEET ", 6))) {
-          if (!(PDB::Flags() & PDB::CHARMM_FORMAT)) {
+          if (!charmm_style_) {
             this->ParseStrandEntry(curr_line);
           }
         }
@@ -231,6 +250,12 @@ void PDBReader::Import(mol::EntityHandle& ent,
                << helix_list_.size() << " helices and "
                << strand_list_.size() << " strands");
   this->AssignSecStructure(ent);
+  for (HetList::const_iterator i=hets_.begin(), e=hets_.end(); i!=e; ++i) {
+    mol::ResidueHandle res=ent.FindResidue(String(1, i->chain), i->num);
+    if (res.IsValid()) {
+      res.SetIsLigand(true);
+    }      
+  }
 }
 
 
@@ -285,12 +310,13 @@ void PDBReader::ClearState()
   hard_end_=false;
   helix_list_.clear();
   strand_list_.clear();
+  hets_.clear();
 }
 
 bool PDBReader::EnsureLineLength(const StringRef& line, size_t size)
 {
   if (line.length()<size) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+    if (profile_.fault_tolerant) {
       return false;
     }    
     throw IOException(str(format("premature end of line %d") %line_num_));
@@ -306,7 +332,13 @@ bool PDBReader::ParseAtomIdent(const StringRef& line, int line_num,
   if (!this->EnsureLineLength(line, 27)) {
     return false;
   }
-  if (PDB::Flags() & PDB::CHARMM_FORMAT) {
+  atom_name=line.substr(12, 4).trim();
+  if (profile_.calpha_only) {
+    if (atom_name!=StringRef("CA", 2)) {
+      return false;
+    }
+  }
+  if (charmm_style_) {
     if (line.size()>73) {
       size_t width=std::min(line.size()-72, size_t(4));
       chain_name=line.substr(72, width).trim().str();      
@@ -321,17 +353,17 @@ bool PDBReader::ParseAtomIdent(const StringRef& line, int line_num,
 
   std::pair<bool, int> a_num=line.substr(6, 5).ltrim().to_int();
   if (!a_num.first) {
-    if (!(PDB::Flags() & PDB::SKIP_FAULTY_RECORDS)) {
+    if (!(profile_.fault_tolerant)) {
       throw IOException(str(format("invalid atom number on line %d") %line_num));      
     }
     LOG_WARNING("invalid atom number on line " << line_num);
   }
-  atom_name=line.substr(12, 4).trim();
+
   alt_loc=line[16];
-  res_name=line.substr(17, (PDB::Flags() & PDB::CHARMM_FORMAT) ? 4 : 3).trim();
+  res_name=line.substr(17, charmm_style_ ? 4 : 3).trim();
   std::pair<bool, int> res_num=line.substr(22, 4).ltrim().to_int();;
   if (!res_num.first) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+    if (profile_.fault_tolerant) {
       return false;
     }
     throw IOException(str(format("invalid res number on line %d") % line_num));
@@ -339,15 +371,6 @@ bool PDBReader::ParseAtomIdent(const StringRef& line, int line_num,
 
   char  ins_c=line[26];  
   resnum=to_res_num(res_num.second, ins_c);
-  if (PDB::Flags() & PDB::CALPHA_ONLY) {
-    if (record_type[0]=='H' || record_type[0]=='h') {
-      return false;
-    } 
-    if (atom_name!=StringRef("CA", 2)) {
-      return false;
-    }
-    return true;
-  }
   return true;
 }
 
@@ -369,7 +392,7 @@ void PDBReader::ParseAnisou(const StringRef& line, int line_num,
   for (int i=0;i<6; ++i) {
     std::pair<bool, int> result=line.substr(29+i*7, 6).ltrim().to_int();
     if (!result.first) {
-      if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+      if (profile_.fault_tolerant) {
         return;
       }
       throw IOException(str(format("invalid ANISOU record on line %d")%line_num));
@@ -378,8 +401,7 @@ void PDBReader::ParseAnisou(const StringRef& line, int line_num,
   }
   String aname(atom_name.str());
   if (!curr_residue_.IsValid()) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS || 
-        PDB::Flags() & PDB::CALPHA_ONLY) {
+    if (profile_.fault_tolerant || profile_.calpha_only) {
       return;
     } 
     const char* fmt_str="invalid ANISOU record for inexistent atom on line %d";
@@ -387,23 +409,20 @@ void PDBReader::ParseAnisou(const StringRef& line, int line_num,
   }
   mol::AtomHandle atom=curr_residue_.FindAtom(aname);
   if (!atom.IsValid()) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS ||
-        PDB::Flags() & PDB::CALPHA_ONLY) {
+    if (profile_.fault_tolerant || profile_.calpha_only) {
       return;
     } 
     const char* fmt_str="invalid ANISOU record for inexistent atom on line %d";
     throw IOException(str(format(fmt_str) % line_num));      
   }
   //get properties which are already set and extend them by adding the ANISOU info
-  mol::AtomProp aprop=atom.GetAtomProps();
+  
+
   geom::Mat3 mat(anisou[0], anisou[3], anisou[4],
                  anisou[3], anisou[1], anisou[5],
                  anisou[4], anisou[5], anisou[2]);
-  aprop.anisou=mat;
-  //divide by 10**4 to actually reflect the real values
-  aprop.anisou/=10000;
-  aprop.has_anisou=true;
-  atom.SetAtomProps(aprop);
+  mat/=10000;
+  atom.SetAnisou(mat);
 }
 
 void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
@@ -413,7 +432,7 @@ void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
   if (!this->EnsureLineLength(line, 54)) {
     return;
   }
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   char alt_loc=0;
   String chain_name;
   StringRef res_name, atom_name;
@@ -429,7 +448,7 @@ void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
   for (int i=0;i<3; ++i) {
     std::pair<bool, float> result=line.substr(30+i*8, 8).ltrim().to_float();
     if (!result.first) {
-      if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+      if (profile_.fault_tolerant) {
         return;
       }
       throw IOException(str(format("invalid coordinate on line %d")%line_num));
@@ -497,15 +516,7 @@ void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
   }
 
   if(update_chain) {
-    curr_chain_=mol::ChainHandle();
-#if 0
-    // TODO: should this depend on JOIN_SPREAD as well?
-    if (PDB::Flags() & PDB::JOIN_SPREAD_ATOM_RECORDS) {
-      curr_chain_=ent.FindChain(s_chain);
-    }
-#else
-      curr_chain_=ent.FindChain(chain_name);
-#endif
+    curr_chain_=ent.FindChain(chain_name);
     if(!curr_chain_.IsValid()) {
       LOG_DEBUG("new chain " << chain_name);
       curr_chain_=editor.InsertChain(chain_name);
@@ -515,42 +526,34 @@ void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
   }
   if(update_residue) {
     curr_residue_=mol::ResidueHandle();
-    if (PDB::Flags() & PDB::JOIN_SPREAD_ATOM_RECORDS) {
+    if (profile_.join_spread_atom_records) {
       curr_residue_=curr_chain_.FindResidue(res_num);
     }
     if (!curr_residue_.IsValid()) {
       LOG_DEBUG("new residue " << res_name << " " << res_num);
       curr_residue_=editor.AppendResidue(curr_chain_, res_name.str(), res_num);
+      warned_name_mismatch_=false;
       ++residue_count_; 
     }
     assert(curr_residue_.IsValid());
   }
   // finally add atom
   LOG_DEBUG("adding atom " << aname << " (" << s_ele << ") @" << apos);
-  mol::AtomProp aprop;
-  aprop.element=s_ele;
-  if(is_pqr_) {
-    if (radius.first) {
-      aprop.radius=radius.second;
-    } else {
-      aprop.radius=0.0;
+  mol::AtomHandle ah;
+  if (curr_residue_.GetName()!=res_name.str()) {
+    if (!profile_.fault_tolerant) {
+      std::stringstream ss;
+      ss << "error on line " << line_num << ": "
+         << "residue with number " << res_num << " has more than one name.";
+      throw IOException(ss.str());
     }
-  } else {
-    aprop.radius=0.0;
-  }
-
-  if (temp.first) {
-    aprop.b_factor=temp.second;
-  }
-  if (occ.first) {
-    aprop.occupancy=occ.second;
-  }
-  if (charge.first) {
-    aprop.charge=charge.second;
+    if (!warned_name_mismatch_) {
+      LOG_INFO("Residue with number " << res_num << " has more than one name."
+               "Ignoring atoms for everything but the first");      
+    }
+    warned_name_mismatch_=true;
+    return;
   }
-
-  aprop.is_hetatm=record_type[0]=='H' ? true : false;
-
   if (alt_loc!=' ') {
     // Check if there is already a atom with the same name.
     mol::AtomHandle me=curr_residue_.FindAtom(aname);
@@ -562,15 +565,31 @@ void PDBReader::ParseAndAddAtom(const StringRef& line, int line_num,
                      "with name " << aname << ", but without an alt loc");
         return;
       }
+      return;
     } else {
-      mol::AtomHandle ah=editor.InsertAltAtom(curr_residue_, aname,
-                                              String(1, alt_loc), apos, aprop);
+      ah=editor.InsertAltAtom(curr_residue_, aname,
+                              String(1, alt_loc), apos, s_ele);
       ++atom_count_;
     }
   } else {
-    mol::AtomHandle ah = editor.InsertAtom(curr_residue_, aname, apos, aprop);
+    ah=editor.InsertAtom(curr_residue_, aname, apos, s_ele);
     ++atom_count_;
   }
+  if(is_pqr_) {
+    if (radius.first) {
+      ah.SetRadius(radius.second);
+    }
+  }
+  if (temp.first) {
+    ah.SetBFactor(temp.second);
+  }
+  if (occ.first) {
+    ah.SetOccupancy(occ.second);
+  }
+  if (charge.first) {
+    ah.SetCharge(charge.second);
+  }
+  ah.SetHetAtom(record_type[0]=='H');
 }
 
 void PDBReader::ParseHelixEntry(const StringRef& line)
@@ -581,7 +600,7 @@ void PDBReader::ParseHelixEntry(const StringRef& line)
   std::pair<bool, int>  start_num=line.substr(21, 4).ltrim().to_int();
   std::pair<bool, int>  end_num=line.substr(33, 4).ltrim().to_int();
   if (!start_num.first || !end_num.first) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+    if (profile_.fault_tolerant) {
       return;
     }    
     throw IOException(str(format("invalid helix entry on line %d") % line_num_));
@@ -606,7 +625,7 @@ void PDBReader::ParseStrandEntry(const StringRef& line)
   std::pair<bool, int>  start_num=line.substr(22, 4).ltrim().to_int();
   std::pair<bool, int>  end_num=line.substr(33, 4).ltrim().to_int();
   if (!start_num.first || !end_num.first) {
-    if (PDB::Flags() & PDB::SKIP_FAULTY_RECORDS) {
+    if (profile_.fault_tolerant) {
       return;
     }
     throw IOException(str(format("invalid strand entry on line %d")%line_num_));
diff --git a/modules/io/src/mol/pdb_reader.hh b/modules/io/src/mol/pdb_reader.hh
index 2c2ca2c1a16eadd110ad79aca78dcf31e8afc06b..9e087c96200069c21587fd3f15e72f56656b91b0 100644
--- a/modules/io/src/mol/pdb_reader.hh
+++ b/modules/io/src/mol/pdb_reader.hh
@@ -28,8 +28,7 @@
 #include <ost/mol/mol.hh>
 #include <ost/mol/xcs_editor.hh>
 #include <ost/io/module_config.hh>
-#include <ost/io/mol/pdb_io.hh>
-
+#include <ost/io/mol/io_profile.hh>
 namespace ost { namespace io {
 
 class DLLEXPORT_OST_IO PDBReader {
@@ -38,11 +37,17 @@ class DLLEXPORT_OST_IO PDBReader {
     mol::ResNum end;
     String chain;
   };
+  struct HetEntry {
+    HetEntry(char c, mol::ResNum n): chain(c), num(n) {}
+    char        chain;
+    mol::ResNum num;
+  };
   typedef std::vector<HSEntry> HSList;
+  typedef std::vector<HetEntry>  HetList;
 public:
-  PDBReader(const String& filename);
-  PDBReader(const boost::filesystem::path& loc);
-  PDBReader(std::istream& instream);
+  PDBReader(const String& filename, const IOProfile& profile);
+  PDBReader(const boost::filesystem::path& loc, const IOProfile& profile);
+  PDBReader(std::istream& instream, const IOProfile& profile);
 
   bool HasNext();
 
@@ -77,16 +82,18 @@ private:
   String restrict_chains_;
   HSList helix_list_;
   HSList strand_list_;
-
   boost::filesystem::ifstream infile_;
   std::istream& instream_;
   boost::iostreams::filtering_stream<boost::iostreams::input>  in_;
   String curr_line_;
-  
+  HetList  hets_;
   // this needs to be set to true for reading pqr
   // file (i.e. pdb formatted file with charges in occupacy
   // column, and radii in b-factor column)
   bool is_pqr_;
+  IOProfile profile_;
+  bool charmm_style_;
+  bool warned_name_mismatch_;
 };
 
 }}
diff --git a/modules/io/src/mol/pdb_writer.cc b/modules/io/src/mol/pdb_writer.cc
index 8b16c2cce992fd7bf61675d315a00ca30178d581..bcdd204ba09c8ee1bff9d1abe46da1503bef25f0 100644
--- a/modules/io/src/mol/pdb_writer.cc
+++ b/modules/io/src/mol/pdb_writer.cc
@@ -126,7 +126,12 @@ void write_atom(std::ostream& ostr, FormattedLine& line,
       line(60, 6)=fmt::LPaddedFloat(atom.GetRadius(), 2);
     } else {
       line(54, 6)=fmt::LPaddedFloat(atom.GetOccupancy(), 2);
-      line(60, 6)=fmt::LPaddedFloat(atom.GetBFactor(), 2);
+      Real bfac=atom.GetBFactor();
+      if (bfac>999.99) {
+        line(60, 6)=fmt::LPaddedFloat(999.99, 2);
+      } else {
+        line(60, 6)=fmt::LPaddedFloat(bfac, 2);
+      }
     }
     if (charmm_style) {
       line(72, 4)=fmt::RPadded(chain_name);
@@ -136,7 +141,8 @@ void write_atom(std::ostream& ostr, FormattedLine& line,
   } else {
     for (std::vector<String>::const_iterator
          i=names.begin(), e=names.end(); i!=e; ++i) {
-      p=atom.GetAltPos(*i);
+      geom::Mat4 tf=atom.GetEntity().GetTransformationMatrix();
+      p=geom::Vec3(tf*geom::Vec4(atom.GetAltPos(*i)));
       line(30, 50).Clear();
 
       if (i->size()>1) {
@@ -154,7 +160,12 @@ void write_atom(std::ostream& ostr, FormattedLine& line,
        line(60, 6)=fmt::LPaddedFloat(atom.GetRadius(), 2);
       } else {
        line(54, 6)=fmt::LPaddedFloat(atom.GetOccupancy(), 2);
-       line(60, 6)=fmt::LPaddedFloat(atom.GetBFactor(), 2);
+       Real bfac=atom.GetBFactor();
+       if (bfac>999.99) {
+         line(60, 6)=fmt::LPaddedFloat(999.99, 2);
+       } else {
+         line(60, 6)=fmt::LPaddedFloat(bfac, 2);
+       }
       }
       if (charmm_style) {
         line(72, 4)=fmt::RPadded(chain_name);
@@ -197,7 +208,7 @@ public:
   virtual bool VisitAtom(const mol::AtomHandle& atom) {
     counter_++;
     write_atom(ostr_, line_, atom, counter_, is_pqr_, charmm_style_);
-    if (atom.GetAtomProps().is_hetatm) {
+    if (atom.IsHetAtom()) {
       atom_indices_[atom.GetHashCode()]=counter_;
     }
     return true;
@@ -236,7 +247,10 @@ public:
     line_(0, 6)=StringRef("TER   ", 6);
     line_( 6, 5)=fmt::LPaddedInt(counter_);
     line_(17, 3)=fmt::LPadded(res.GetKey());
-    line_[21]=res.GetChain().GetName()[0];
+    if (!res.GetChain().GetName().empty()) {
+      line_[21]=res.GetChain().GetName()[0];
+    }
+
     line_(22, 4)=fmt::LPaddedInt(res.GetNumber().GetNum());
     char ins_code=res.GetNumber().GetInsCode();
     if (ins_code!=0) {
@@ -268,7 +282,7 @@ public:
 private:
 public:
   virtual bool VisitAtom(const mol::AtomHandle& atom) {
-    if (atom.GetAtomProps().is_hetatm) {
+    if (atom.IsHetAtom()) {
       bool has_partner=false;
       int atom_index=atom_indices_[atom.GetHashCode()];
       mol::AtomHandleList partners=atom.GetBondPartners();
@@ -305,37 +319,41 @@ struct ForcePOSIX {
 
 }
 
-PDBWriter::PDBWriter(std::ostream& stream, bool charmm_style):
-  outfile_(), outstream_(stream), mol_count_(0), line_(80), 
-  charmm_style_(charmm_style)
+PDBWriter::PDBWriter(std::ostream& stream, const IOProfile& profile):
+  outfile_(), outstream_(stream), mol_count_(0), line_(80),
+  multi_model_(false), charmm_style_(profile.dialect=="CHARMM"), is_pqr_(false),
+  profile_(profile)
 {
   
 }
 
-PDBWriter::PDBWriter(const boost::filesystem::path& filename, bool charmm_style):
+PDBWriter::PDBWriter(const boost::filesystem::path& filename, 
+                     const IOProfile& profile):
   outfile_(filename.file_string().c_str()), outstream_(outfile_), 
-  mol_count_(0), line_(80), charmm_style_(charmm_style)
+  mol_count_(0), line_(80), multi_model_(false), 
+  charmm_style_(profile.dialect=="CHARMM"), is_pqr_(false),
+  profile_(profile)
 {}
 
-PDBWriter::PDBWriter(const String& filename, bool charmm_style):
-  outfile_(filename.c_str()), outstream_(outfile_), mol_count_(0), line_(80),
-  charmm_style_(charmm_style)
+PDBWriter::PDBWriter(const String& filename, const IOProfile& profile):
+  outfile_(filename.c_str()), outstream_(outfile_), mol_count_(0), line_(80), 
+  multi_model_(false), charmm_style_(profile.dialect=="CHARMM"), 
+  is_pqr_(false), profile_(profile)
 {}
 
 void PDBWriter::WriteModelLeader()
 {
   ++mol_count_;
-  if (PDB::Flags() & PDB::WRITE_MULTIPLE_MODELS) {
+  if (multi_model_) {
     outstream_ << "MODEL     " << mol_count_ << std::endl;
   } else if (mol_count_>1) {
-    throw IOException("Please enable the PDB::WRITE_MULTIPLE_MODELS flag to "
-                      "write multiple models");
+    throw IOException("Trying to write several models into one file with ");
   }
 }
 
 void PDBWriter::WriteModelTrailer()
 {
-  if (PDB::Flags() & PDB::WRITE_MULTIPLE_MODELS) {
+  if (multi_model_) {
     outstream_ << "ENDMDL" << std::endl;
   }
 }
@@ -343,12 +361,10 @@ void PDBWriter::WriteModelTrailer()
 template <typename H>
 void PDBWriter::WriteModel(H ent)
 {
-  ForcePOSIX posix = ForcePOSIX();
+  ForcePOSIX posix;
   this->WriteModelLeader();
   PDBWriterImpl writer(outstream_,line_, atom_indices_, charmm_style_);
-  if (PDB::Flags() & PDB::PQR_FORMAT) {
-    writer.SetIsPQR(true);
-  }
+  writer.SetIsPQR(is_pqr_);
   ent.Apply(writer);
   PDBConectWriterImpl con_writer(outstream_,atom_indices_);
   ent.Apply(con_writer);
@@ -373,8 +389,7 @@ void PDBWriter::Write(const mol::AtomHandleList& atoms)
   mol::ChainHandle last_chain;
   for (mol::AtomHandleList::const_iterator i=atoms.begin(),
        e=atoms.end(); i!=e; ++i, ++counter) {
-    write_atom(outstream_, line_, *i, counter, 
-               (PDB::Flags() & PDB::PQR_FORMAT) != 0, charmm_style_);
+    write_atom(outstream_, line_, *i, counter, is_pqr_, charmm_style_);
   }
   this->WriteModelTrailer();
 }
diff --git a/modules/io/src/mol/pdb_writer.hh b/modules/io/src/mol/pdb_writer.hh
index c8965721507173a49598e0a3f97e7e5639929a73..2ec823fcbd57ce76c9c83e9604f8c582063a18e2 100644
--- a/modules/io/src/mol/pdb_writer.hh
+++ b/modules/io/src/mol/pdb_writer.hh
@@ -32,18 +32,21 @@
 
 #include <ost/io/module_config.hh>
 #include <ost/io/formatted_line.hh>
-
-
-#include "pdb_io.hh"
+#include <ost/io/mol/io_profile.hh>
 
 namespace ost { namespace io {
 
 class DLLEXPORT_OST_IO PDBWriter {
 public:
-  PDBWriter(const String& filename, bool charmm_style=false);
-  PDBWriter(const boost::filesystem::path& filename, bool charmm_style=false);
-  PDBWriter(std::ostream& outstream, bool charmm_style=false);
-  
+  PDBWriter(const String& filename,
+            const IOProfile& profile);
+  PDBWriter(const boost::filesystem::path& filename,
+            const IOProfile& profile);
+  PDBWriter(std::ostream& outstream, const IOProfile& profile);
+  void SetWriteMultiModel(bool flag) { multi_model_=flag; }
+  bool GetWriteMultiModel() const { return multi_model_; }
+  void SetIsPQR(bool flag) { is_pqr_=flag; }
+  bool IsPQR() const { return is_pqr_; }
   void Write(const mol::EntityView& ent);
   void Write(const mol::EntityHandle& ent);
   
@@ -61,7 +64,10 @@ private:
   int                 mol_count_;
   std::map<long, int> atom_indices_;
   FormattedLine       line_;
+  bool                multi_model_;
   bool                charmm_style_;
+  bool                is_pqr_;
+  IOProfile           profile_;
 };
  
 }}
diff --git a/modules/io/src/mol/sdf_reader.cc b/modules/io/src/mol/sdf_reader.cc
index 4427850ea6678b6a9a6cb639e3e92e600c9a30a8..655ee8fa07b870fb02aa37d21e512ef88e0d621b 100644
--- a/modules/io/src/mol/sdf_reader.cc
+++ b/modules/io/src/mol/sdf_reader.cc
@@ -36,25 +36,28 @@ namespace ost { namespace io {
 using boost::format;
 
 SDFReader::SDFReader(const String& filename)
-  : infile_(filename), instream_(infile_) {
-  this->ClearState();
+  : infile_(filename), instream_(infile_)
+{
+  this->ClearState(boost::filesystem::path(filename));
 }
 
 SDFReader::SDFReader(const boost::filesystem::path& loc)
-  : infile_(loc), instream_(infile_) {
-  this->ClearState();
+  : infile_(loc), instream_(infile_)
+{
+  this->ClearState(loc);
 }
 
 SDFReader::SDFReader(std::istream& instream)
-  : infile_(), instream_(instream) {
-  this->ClearState();
+  : infile_(), instream_(instream)
+{
+  this->ClearState(boost::filesystem::path(""));
 }
 
 // import data from provided stream
 void SDFReader::Import(mol::EntityHandle& ent)
 {
   String line;
-  mol::XCSEditor editor=ent.RequestXCSEditor(mol::BUFFERED_EDIT);
+  mol::XCSEditor editor=ent.EditXCS(mol::BUFFERED_EDIT);
   while (std::getline(instream_,line)) {
     ++line_num;
 
@@ -82,7 +85,7 @@ void SDFReader::Import(mol::EntityHandle& ent)
       }
       curr_chain_.SetStringProp(data_header, data_value);
     } else if (boost::iequals(line, "$$$$")) {
-      LOG_INFO("MOLECULE " << curr_chain_.GetName() << " (" << chain_count_ << ") added.")
+      LOG_VERBOSE("MOLECULE " << curr_chain_.GetName() << " (" << chain_count_ << ") added.")
       NextMolecule();
     }
   }
@@ -91,8 +94,9 @@ void SDFReader::Import(mol::EntityHandle& ent)
                << " residues, " << atom_count_ << " atoms");
 }
 
-void SDFReader::ClearState()
+void SDFReader::ClearState(const boost::filesystem::path& loc)
 {
+  if(!infile_) throw IOException("could not open "+loc.string());
   curr_chain_=mol::ChainHandle();
   curr_residue_=mol::ResidueHandle();
   chain_count_=0;
@@ -196,17 +200,12 @@ void SDFReader::ParseAndAddAtom(const String& line, int line_num,
 
   String ele=boost::trim_copy(s_ele);
   String aname=boost::lexical_cast<String>(anum);
-
-  mol::AtomProp aprop;
-  aprop.element=ele;
-  aprop.radius=conop::Conopology::Instance().GetDefaultAtomRadius(ele);
-  aprop.mass=conop::Conopology::Instance().GetDefaultAtomMass(ele);
-  aprop.is_hetatm=hetatm;
-
+  
+  Real charge=0.0;  
   try {
-    aprop.charge=boost::lexical_cast<Real>(boost::trim_copy(s_charge));
-    if(aprop.charge != 0) {
-      aprop.charge=4-aprop.charge;
+    charge=boost::lexical_cast<Real>(boost::trim_copy(s_charge));
+    if (charge!=0) {
+      charge=4-charge;
     } //4-sdf_charge=real_charge if not 0
   } catch(boost::bad_lexical_cast&) {
     String msg="Bad atom line %d: Can't convert charge"
@@ -216,7 +215,9 @@ void SDFReader::ParseAndAddAtom(const String& line, int line_num,
 
   LOG_DEBUG("adding atom " << aname << " (" << s_ele << ") @" << apos);
 
-  editor.InsertAtom(curr_residue_, aname,apos,aprop);
+  mol::AtomHandle atom=editor.InsertAtom(curr_residue_, aname,apos, ele);  
+  atom.SetHetAtom(hetatm);
+  atom.SetCharge(charge);
 }
 
 
@@ -226,9 +227,9 @@ void SDFReader::ParseAndAddBond(const String& line, int line_num,
 
   LOG_TRACE( "line: [" << line << "]" );
 
-  if(line.length()<18 || line.length()>21) {
+  if(line.length()<9 || line.length()>21) {
     String msg="Bad bond line %d: Not correct number of characters on the"
-               " line: %i (should be between 18 and 21)";
+               " line: %i (should be between 9 and 21)";
     throw IOException(str(format(msg) % line_num % line.length()));
   }
 
@@ -257,10 +258,12 @@ void SDFReader::ParseAndAddBond(const String& line, int line_num,
 
   mol::AtomHandle first,second;
 
-  first = ent.FindAtom(curr_chain_.GetName(), mol::ResNum(residue_count_), first_name);
-  second = ent.FindAtom(curr_chain_.GetName(), mol::ResNum(residue_count_), second_name);
+  first = ent.FindAtom(curr_chain_.GetName(), mol::ResNum(residue_count_), 
+                       first_name);
+  second = ent.FindAtom(curr_chain_.GetName(), mol::ResNum(residue_count_), 
+                        second_name);
 
-  if(first.IsValid() && second.IsValid()) {
+  if (first.IsValid() && second.IsValid()) {
     bond = editor.Connect(first, second);
     bond.SetBondOrder(type);
   } else {
@@ -269,7 +272,8 @@ void SDFReader::ParseAndAddBond(const String& line, int line_num,
     throw IOException(str(format(msg) % line_num % first % second));
   }
 
-  LOG_DEBUG("adding bond " << s_first_name << " " << s_second_name << " (" << s_type << ") ");
+  LOG_DEBUG("adding bond " << s_first_name << " " << s_second_name << " (" 
+            << s_type << ") ");
 }
 
 }}
diff --git a/modules/io/src/mol/sdf_reader.hh b/modules/io/src/mol/sdf_reader.hh
index 0401e6ab746b3a0a86c738599071ecb5b50f6b79..3beacc0311bf602053c1d88beab5cc29237d1915 100644
--- a/modules/io/src/mol/sdf_reader.hh
+++ b/modules/io/src/mol/sdf_reader.hh
@@ -39,7 +39,7 @@ public:
   void Import(mol::EntityHandle& ent);
 
 private:
-  void ClearState();
+  void ClearState(const boost::filesystem::path& loc);
   void NextMolecule();
 
   void ParseAndAddHeader(const String& line, int line_num, mol::EntityHandle& ent,
diff --git a/modules/io/src/mol/sdf_writer.cc b/modules/io/src/mol/sdf_writer.cc
index b6243b4a698cb9959904f67c67256b9bdf14ceb1..c2db1ddb096925a67b02f542908c2a342010f2ef 100644
--- a/modules/io/src/mol/sdf_writer.cc
+++ b/modules/io/src/mol/sdf_writer.cc
@@ -21,6 +21,7 @@
  */
 
 #include "sdf_writer.hh"
+#include <boost/regex.hpp>
 
 namespace ost { namespace io {
 
@@ -28,7 +29,7 @@ using boost::format;
 
 namespace {
 
-  class SDFAtomWriter : public mol::EntityVisitor {
+  class SDFAtomWriter : public mol::EntityViewVisitor {
     public:
       SDFAtomWriter(std::ostream& ostream, std::map<long, int>& atom_indices)
       : ostr_(ostream), atom_indices_(atom_indices), counter_(0) {
@@ -36,7 +37,7 @@ namespace {
       }
     private:
     public:
-      virtual bool VisitAtom(const mol::AtomHandle& atom) {
+      virtual bool VisitAtom(const mol::AtomView& atom) {
         atom_indices_[atom.GetHashCode()] = ++counter_;
         ostr_ << format("%10.4f") % atom.GetPos()[0]
               << format("%10.4f") % atom.GetPos()[1]
@@ -52,22 +53,22 @@ namespace {
       int counter_;
   };
 
-  class SDFBondWriter : public mol::EntityVisitor {
+  class SDFBondWriter : public mol::EntityViewVisitor {
   public:
     SDFBondWriter(std::ostream& ostream, std::map<long, int>& atom_indices)
       : ostr_(ostream), atom_indices_(atom_indices), counter_(0) {
     }
   private:
   public:
-    virtual bool VisitAtom(const mol::AtomHandle& atom) {
+    virtual bool VisitAtom(const mol::AtomView& atom) {
       counter_++;
-      mol::AtomHandleList atoms = atom.GetBondPartners();
-      mol::AtomHandleList::iterator atom_iter = atoms.begin();
+      mol::AtomViewList atoms = atom.GetBondPartners();
+      mol::AtomViewList::iterator atom_iter = atoms.begin();
       for(; atom_iter != atoms.end(); ++atom_iter) {
         int atom_index = atom_indices_.find((*atom_iter).GetHashCode())->second;
         if(atom_index > counter_) {
           int type = 1;
-          mol::BondHandle bond = atom.FindBondToAtom(*atom_iter);
+          mol::BondHandle bond = atom.GetHandle().FindBondToAtom(atom_iter->GetHandle());
           if(bond.IsValid()) type = bond.GetBondOrder();
           ostr_ << format("%3i") % counter_
                 << format("%3i") % atom_index
@@ -104,11 +105,11 @@ void SDFWriter::Write(const mol::EntityView& ent) {
 }
 
 void SDFWriter::Write(const mol::EntityHandle& ent) {
-  mol::EntityHandle non_const_handle = ent;
-  non_const_handle.Apply(*this);
+  mol::EntityView non_const_view = ent.CreateFullView();
+  non_const_view.Apply(*this);
 }
 
-bool SDFWriter::VisitChain(const mol::ChainHandle& chain) {
+bool SDFWriter::VisitChain(const mol::ChainView& chain) {
   // print end of molecule line
   if(counter_ != 0) {
     ostr_ << "$$$$" << std::endl;
@@ -116,11 +117,19 @@ bool SDFWriter::VisitChain(const mol::ChainHandle& chain) {
     atom_indices_.clear();
   }
 
+  // remove chain number if added when reading from sdf file
+  String cname = chain.GetName();
+  if (cname.length()>6) {
+    boost::regex pattern = boost::regex("^[0-9]{5}_");
+    if (boost::regex_search(cname, pattern)) {
+      cname = cname.substr(6);
+    }
+  }
+
   // print header lines
-  ostr_ << chain.GetName().substr(6) << std::endl;
+  ostr_ << cname << std::endl;
   ostr_ << std::endl;
   ostr_ << std::endl;
-
   // print counts line
   ostr_ << format("%3d") % chain.GetAtomCount()
         << format("%3d") % chain.GetBondCount()
@@ -129,7 +138,7 @@ bool SDFWriter::VisitChain(const mol::ChainHandle& chain) {
 
   // write atom block
   SDFAtomWriter atom_writer(ostr_, atom_indices_);
-  mol::ChainHandle non_const_chain = chain;
+  mol::ChainView non_const_chain = chain;
   non_const_chain.Apply(atom_writer);
 
   // write bond block
diff --git a/modules/io/src/mol/sdf_writer.hh b/modules/io/src/mol/sdf_writer.hh
index 62a365d491f303f6e0a5a01add5ce3af1636deba..76538f808f611dd8edb1a5979b2f9ad9ced66359 100644
--- a/modules/io/src/mol/sdf_writer.hh
+++ b/modules/io/src/mol/sdf_writer.hh
@@ -38,7 +38,7 @@
 
 namespace ost { namespace io {
 
-class DLLEXPORT_OST_IO SDFWriter : public mol::EntityVisitor {
+class DLLEXPORT_OST_IO SDFWriter : public mol::EntityViewVisitor {
 public:
   SDFWriter(std::ostream& ostream);
   SDFWriter(const String& filename);
@@ -48,7 +48,7 @@ public:
   void Write(const mol::EntityHandle& ent);
 
 private:
-  virtual bool VisitChain(const mol::ChainHandle& chain);
+  virtual bool VisitChain(const mol::ChainView& chain);
 
   std::ofstream      outfile_;
   std::ostream&      ostr_;
diff --git a/modules/io/tests/test_io_pdb.cc b/modules/io/tests/test_io_pdb.cc
index df8ff5295dc686bbcf12c281b649a66a7218ff0c..78dab44682593cda43e79a9bb45ea6edce29b723 100644
--- a/modules/io/tests/test_io_pdb.cc
+++ b/modules/io/tests/test_io_pdb.cc
@@ -54,7 +54,7 @@ BOOST_AUTO_TEST_CASE(test_pdb_import_handler)
 BOOST_AUTO_TEST_CASE(atom_record)
 {
   String fname("testfiles/pdb/atom.pdb");
-  PDBReader reader(fname); 
+  PDBReader reader(fname, IOProfile()); 
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_REQUIRE_EQUAL(ent.GetChainCount(), 2);
@@ -67,10 +67,10 @@ BOOST_AUTO_TEST_CASE(atom_record)
   BOOST_CHECK_EQUAL(a1.GetResidue().GetChain().GetName(), "A");  
   
   BOOST_CHECK_EQUAL(a1.GetPos(), geom::Vec3(16.0, 64.0, 8.0));
-  BOOST_CHECK_EQUAL(a1.GetAtomProps().b_factor, 1.0);
-  BOOST_CHECK_EQUAL(a1.GetAtomProps().occupancy, 0.5);  
-  BOOST_CHECK_EQUAL(a1.GetAtomProps().element, "N");
-  BOOST_CHECK_EQUAL(a1.GetAtomProps().is_hetatm, false);
+  BOOST_CHECK_EQUAL(a1.GetBFactor(), 1.0);
+  BOOST_CHECK_EQUAL(a1.GetOccupancy(), 0.5);  
+  BOOST_CHECK_EQUAL(a1.GetElement(), "N");
+  BOOST_CHECK_EQUAL(a1.IsHetAtom(), false);
   mol::AtomHandle a2=ent.FindAtom(" ", mol::ResNum(1), "CA");
   BOOST_REQUIRE(a2.IsValid());  
   BOOST_CHECK_EQUAL(a2.GetName(), "CA");
@@ -78,16 +78,16 @@ BOOST_AUTO_TEST_CASE(atom_record)
   BOOST_CHECK_EQUAL(a2.GetResidue().GetChain().GetName(), " ");  
   
   BOOST_CHECK_EQUAL(a2.GetPos(), geom::Vec3(32.0, -128.0, -2.5));
-  BOOST_CHECK_EQUAL(a2.GetAtomProps().b_factor, 128.0);
-  BOOST_CHECK_EQUAL(a2.GetAtomProps().occupancy, 1.0);  
-  BOOST_CHECK_EQUAL(a2.GetAtomProps().element, "C");
-  BOOST_CHECK_EQUAL(a2.GetAtomProps().is_hetatm, true);
+  BOOST_CHECK_EQUAL(a2.GetBFactor(), 128.0);
+  BOOST_CHECK_EQUAL(a2.GetOccupancy(), 1.0);  
+  BOOST_CHECK_EQUAL(a2.GetElement(), "C");
+  BOOST_CHECK_EQUAL(a2.IsHetAtom(), true);
 }
 
 BOOST_AUTO_TEST_CASE(end_record)
 {
   String fname("testfiles/pdb/end.pdb");
-  PDBReader reader(fname); 
+  PDBReader reader(fname, IOProfile()); 
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_CHECK_EQUAL(ent.GetAtomCount(), 1);
@@ -96,12 +96,13 @@ BOOST_AUTO_TEST_CASE(end_record)
 BOOST_AUTO_TEST_CASE(join_spread_records_on)
 {
   String fname("testfiles/pdb/join-spread-records.pdb");
-  PDBReader reader(fname);
+  IOProfile profile;
+  profile.join_spread_atom_records=true;
+  PDBReader reader(fname, profile);
   
   mol::EntityHandle ent=mol::CreateEntity();
-  PDB::PushFlags(PDB::JOIN_SPREAD_ATOM_RECORDS);
+
   reader.Import(ent);
-  PDB::PopFlags();
   BOOST_CHECK_EQUAL(ent.GetResidueCount(), 2);
   mol::ResidueHandle res1=ent.FindResidue("A", mol::ResNum(1));
   BOOST_CHECK(res1.IsValid());
@@ -117,7 +118,7 @@ BOOST_AUTO_TEST_CASE(join_spread_records_on)
 BOOST_AUTO_TEST_CASE(join_spread_records_off)
 {
   String fname("testfiles/pdb/join-spread-records.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_CHECK_EQUAL(ent.GetResidueCount(), 3);
@@ -134,19 +135,28 @@ BOOST_AUTO_TEST_CASE(join_spread_records_off)
 BOOST_AUTO_TEST_CASE(calpha_only_import_on)
 {
   String fname("testfiles/pdb/calpha.pdb");
-  PDBReader reader(fname);
-  PDB::PushFlags(PDB::CALPHA_ONLY);
+  IOProfile profile;
+  profile.calpha_only=true;
+  PDBReader reader(fname, profile);
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
-  PDB::PopFlags();
-  BOOST_CHECK_EQUAL(ent.GetResidueCount(), 1);
-  BOOST_CHECK_EQUAL(ent.GetAtomCount(), 1);
+  BOOST_CHECK_EQUAL(ent.GetResidueCount(), 2);
+  BOOST_CHECK_EQUAL(ent.GetAtomCount(), 2);
+}
+
+BOOST_AUTO_TEST_CASE(het_import)
+{
+  String fname("testfiles/pdb/het.pdb");
+  PDBReader reader(fname, IOProfile());
+  mol::EntityHandle ent=mol::CreateEntity();
+  reader.Import(ent);
+  BOOST_CHECK_EQUAL(ent.Select("ligand=true").GetResidueCount(), 1);
 }
 
 BOOST_AUTO_TEST_CASE(calpha_only_import_off)
 {
   String fname("testfiles/pdb/calpha.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_CHECK_EQUAL(ent.GetResidueCount(), 2);
@@ -156,28 +166,28 @@ BOOST_AUTO_TEST_CASE(calpha_only_import_off)
 BOOST_AUTO_TEST_CASE(anisou_record)
 {
   String fname("testfiles/pdb/anisou.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_REQUIRE(ent.GetAtomCount()==1);
   mol::AtomHandle a1=ent.FindAtom("A", mol::ResNum(7), "N");
   BOOST_REQUIRE(a1.IsValid());
-  mol::AtomProp props=a1.GetAtomProps();
-  BOOST_CHECK_CLOSE(Real( 0.0100), props.anisou(0, 0), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0016), props.anisou(1, 0), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0026), props.anisou(2, 0), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0016), props.anisou(0, 1), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real( 0.0110), props.anisou(1, 1), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0054), props.anisou(2, 1), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0026), props.anisou(0, 2), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real(-0.0054), props.anisou(1, 2), Real(1e-4));
-  BOOST_CHECK_CLOSE(Real( 0.0120), props.anisou(2, 2), Real(1e-4));    
+  const geom::Mat3& anisou=a1.GetAnisou();
+  BOOST_CHECK_CLOSE(Real( 0.0100), anisou(0, 0), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0016), anisou(1, 0), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0026), anisou(2, 0), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0016), anisou(0, 1), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real( 0.0110), anisou(1, 1), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0054), anisou(2, 1), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0026), anisou(0, 2), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real(-0.0054), anisou(1, 2), Real(1e-4));
+  BOOST_CHECK_CLOSE(Real( 0.0120), anisou(2, 2), Real(1e-4));    
 }
 
 BOOST_AUTO_TEST_CASE(only_66_cols)
 {
   String fname("testfiles/pdb/short.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
 }
@@ -185,37 +195,50 @@ BOOST_AUTO_TEST_CASE(only_66_cols)
 BOOST_AUTO_TEST_CASE(no_endmdl_record)
 {
   String fname("testfiles/pdb/model.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   BOOST_CHECK_THROW(reader.Import(ent), IOException);
 }
 
+BOOST_AUTO_TEST_CASE(deuterium_import)
+{
+  String fname("testfiles/pdb/val-with-deuterium.pdb");
+  PDBReader reader(fname, IOProfile());
+  mol::EntityHandle ent=mol::CreateEntity();
+  reader.Import(ent);
+  // we use conopology to mark amino acids as peptide-linking. 
+  conop::Conopology& conop_inst=conop::Conopology::Instance();
+  conop_inst.ConnectAll(conop_inst.GetBuilder(), ent);
+  // this check makes sure that we correctly detect deal with the deuterium
+  // atoms in the residue.
+  BOOST_CHECK(ent.FindResidue("A", 297).IsPeptideLinking());
+}
+
 BOOST_AUTO_TEST_CASE(faulty_lines)
 {
   String fname("testfiles/pdb/faulty.pdb");
-  PDBReader reader(fname);
+  PDBReader reader(fname, IOProfile());
   mol::EntityHandle ent=mol::CreateEntity();
   BOOST_CHECK_THROW(reader.Import(ent), IOException);
-
-  PDB::PushFlags(PDB::SKIP_FAULTY_RECORDS);
-  reader.Import(ent);
+  IOProfile profile;
+  profile.fault_tolerant=true;
+  PDBReader reader2(fname, profile);
+  reader2.Import(ent);
 }
 
 BOOST_AUTO_TEST_CASE(write_atom)
 {
   std::stringstream out;
-  PDBWriter writer(out);
+  PDBWriter writer(out, IOProfile());
   
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor edi=ent.RequestXCSEditor();
+  mol::XCSEditor edi=ent.EditXCS();
   mol::ChainHandle ch=edi.InsertChain("A");
   mol::ResidueHandle r=edi.AppendResidue(ch, "GLY");
-  mol::AtomProp c_prop;
-  c_prop.element="C";
-  c_prop.occupancy=1.0;
-  c_prop.b_factor=128.0;
-  mol::AtomHandle a=edi.InsertAtom(r, "CA", geom::Vec3(32.0, -128.0, -2.5), 
-                                   c_prop);
+
+  mol::AtomHandle a=edi.InsertAtom(r, "CA", geom::Vec3(32.0, -128.0, -2.5), "C");
+  a.SetOccupancy(1.0);
+  a.SetBFactor(128.0);
   writer.Write(ent);
   String s=out.str();
   BOOST_CHECK_EQUAL(s.substr(0, 54), 
@@ -227,20 +250,18 @@ BOOST_AUTO_TEST_CASE(write_atom)
 BOOST_AUTO_TEST_CASE(write_hetatom)
 {
   std::stringstream out;
-  PDBWriter writer(out);
+  PDBWriter writer(out, IOProfile());
   
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor edi=ent.RequestXCSEditor();
+  mol::XCSEditor edi=ent.EditXCS();
   mol::ChainHandle ch=edi.InsertChain("A");
   mol::ResidueHandle r=edi.AppendResidue(ch, "CA");
-  mol::AtomProp c_prop;
-  c_prop.element="CA";
-  c_prop.is_hetatm=true;
-  c_prop.mass=40.01;
-  c_prop.occupancy=1.0;
-  c_prop.b_factor=40.75;
   mol::AtomHandle a=edi.InsertAtom(r, "CA", geom::Vec3(32.0, -128.0, -2.5), 
-                                   c_prop);
+                                   "CA");
+  a.SetHetAtom(true);
+  a.SetMass(40.01);
+  a.SetOccupancy(1.0);
+  a.SetBFactor(40.75);
   writer.Write(ent);
   String s=out.str();
   BOOST_CHECK_EQUAL(s.substr(0, 54), 
@@ -252,8 +273,9 @@ BOOST_AUTO_TEST_CASE(write_hetatom)
 BOOST_AUTO_TEST_CASE(no_endmdl_record_fault_tolerant)
 {
   String fname("testfiles/pdb/model.pdb");
-  PDBReader reader(fname);
-  PDB::PushFlags(PDB::SKIP_FAULTY_RECORDS);  
+  IOProfile profile;
+  profile.fault_tolerant=true;
+  PDBReader reader(fname, profile);
   mol::EntityHandle ent=mol::CreateEntity();
   reader.Import(ent);
   BOOST_CHECK_EQUAL(ent.GetChainCount(), 1);
@@ -264,7 +286,6 @@ BOOST_AUTO_TEST_CASE(no_endmdl_record_fault_tolerant)
   BOOST_CHECK_EQUAL(ent.GetChainCount(), 1);
   BOOST_CHECK_EQUAL(ent.GetResidueCount(), 1);  
   BOOST_CHECK_EQUAL(ent.GetAtomCount(), 2);  
-  PDB::PopFlags();
 }
 
 BOOST_AUTO_TEST_CASE(alt_loc_import_export)
@@ -273,8 +294,8 @@ BOOST_AUTO_TEST_CASE(alt_loc_import_export)
   // this scope is required to force the writer stream to be closed before 
   // opening the file again in compare_files. Avoids a race condition.
   {
-    PDBReader reader(fname);
-    PDBWriter writer(String("testfiles/pdb/alt-loc-out.pdb"));
+    PDBReader reader(fname, IOProfile());
+    PDBWriter writer(String("testfiles/pdb/alt-loc-out.pdb"), IOProfile());
     
     mol::EntityHandle ent=mol::CreateEntity();
     reader.Import(ent);
@@ -290,8 +311,8 @@ BOOST_AUTO_TEST_CASE(write_ter)
   // this scope is required to force the writer stream to be closed before 
   // opening the file again in compare_files. Avoids a race condition.
   {
-    PDBReader reader(fname);
-    PDBWriter writer(String("testfiles/pdb/ter-out.pdb"));
+    PDBReader reader(fname, IOProfile());
+    PDBWriter writer(String("testfiles/pdb/ter-out.pdb"), IOProfile());
     
     mol::EntityHandle ent=mol::CreateEntity();
     reader.Import(ent);
@@ -311,8 +332,8 @@ BOOST_AUTO_TEST_CASE(write_ter2)
   // this scope is required to force the writer stream to be closed before 
   // opening the file again in compare_files. Avoids a race condition.
   {
-    PDBReader reader(fname);
-    PDBWriter writer(String("testfiles/pdb/ter2-out.pdb"));
+    PDBReader reader(fname, IOProfile());
+    PDBWriter writer(String("testfiles/pdb/ter2-out.pdb"), IOProfile());
     
     mol::EntityHandle ent=mol::CreateEntity();
     reader.Import(ent);
@@ -332,8 +353,8 @@ BOOST_AUTO_TEST_CASE(write_ter3)
   // this scope is required to force the writer stream to be closed before 
   // opening the file again in compare_files. Avoids a race condition.
   {
-    PDBReader reader(fname);
-    PDBWriter writer(String("testfiles/pdb/ter3-out.pdb"));
+    PDBReader reader(fname, IOProfile());
+    PDBWriter writer(String("testfiles/pdb/ter3-out.pdb"), IOProfile());
     
     mol::EntityHandle ent=mol::CreateEntity();
     reader.Import(ent);
@@ -352,8 +373,8 @@ BOOST_AUTO_TEST_CASE(write_conect)
   // this scope is required to force the writer stream to be closed before
   // opening the file again in compare_files. Avoids a race condition.
   {
-    PDBReader reader(String("testfiles/pdb/conect.pdb"));
-    PDBWriter writer(String("testfiles/pdb/conect-out.pdb"));
+    PDBReader reader(String("testfiles/pdb/conect.pdb"), IOProfile());
+    PDBWriter writer(String("testfiles/pdb/conect-out.pdb"), IOProfile());
     mol::EntityHandle ent=mol::CreateEntity();
     reader.Import(ent);
     conop::Conopology& conop_inst=conop::Conopology::Instance();
@@ -364,26 +385,75 @@ BOOST_AUTO_TEST_CASE(write_conect)
                             "testfiles/pdb/conect-out.pdb"));
 }
 
+BOOST_AUTO_TEST_CASE(alt_loc_tf)
+{
+  String fname("testfiles/pdb/alt-loc.pdb");  
+  // this scope is required to force the writer stream to be closed before 
+  // opening the file again in compare_files. Avoids a race condition.
+  mol::EntityHandle ent=mol::CreateEntity();  
+  PDBReader reader(fname, IOProfile());
+  reader.Import(ent);
+  String out_name("testfiles/pdb/alt-loc-tf-out.pdb");
+  {
+    PDBWriter writer(out_name, IOProfile());
+    geom::Mat4 shift;
+    shift.PasteTranslation(geom::Vec3(10,20,30));
+    ent.EditXCS().ApplyTransform(shift);
+    writer.Write(ent);
+  }
+  PDBReader r2(out_name, IOProfile());
+  mol::EntityHandle ent2=mol::CreateEntity();
+  r2.Import(ent2);
+  mol::ResidueHandle res1=ent2.FindResidue("A", mol::ResNum(1));
+  mol::AtomHandle a1=res1.FindAtom("N");
+  BOOST_CHECK_EQUAL(res1.GetAltAtomPos(a1, "A"), geom::Vec3(26,84,30));
+  BOOST_CHECK_EQUAL(res1.GetAltAtomPos(a1, "B"), geom::Vec3(18,-108,30));  
+}
+
 BOOST_AUTO_TEST_CASE(res_name_too_long)
 {
   std::stringstream out;
-  PDBWriter writer(out);
+  PDBWriter writer(out, IOProfile());
   
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor edi=ent.RequestXCSEditor();
+  mol::XCSEditor edi=ent.EditXCS();
   mol::ChainHandle ch=edi.InsertChain("A");
   mol::ResidueHandle r=edi.AppendResidue(ch, "CALCIUM");
   mol::AtomHandle a=edi.InsertAtom(r, "CA", geom::Vec3(32.0, -128.0, -2.5));
   BOOST_CHECK_THROW(writer.Write(ent), IOException);
 }
 
+
+BOOST_AUTO_TEST_CASE(res_name_mismatch_tolerant)
+{
+  String fname("testfiles/pdb/arg-glu-gln.pdb");
+  IOProfile profile;
+  profile.fault_tolerant=true;
+  PDBReader reader(fname, profile);
+  mol::EntityHandle ent=mol::CreateEntity();
+  reader.Import(ent);
+  BOOST_CHECK_EQUAL(ent.GetChainCount(), 1);
+  BOOST_CHECK_EQUAL(ent.GetResidueCount(), 1);  
+  BOOST_CHECK_EQUAL(ent.GetAtomCount(), 11);
+}
+
+BOOST_AUTO_TEST_CASE(res_name_mismatch_pedantic)
+{
+  String fname("testfiles/pdb/arg-glu-gln.pdb");
+  IOProfile profile;
+  PDBReader reader(fname, profile);
+  mol::EntityHandle ent=mol::CreateEntity();
+  BOOST_CHECK_THROW(reader.Import(ent), IOException);
+}
+
+
 BOOST_AUTO_TEST_CASE(chain_name_too_long)
 {
   std::stringstream out;
-  PDBWriter writer(out);
+  PDBWriter writer(out, IOProfile());
   
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor edi=ent.RequestXCSEditor();
+  mol::XCSEditor edi=ent.EditXCS();
   mol::ChainHandle ch=edi.InsertChain("AB");
   mol::ResidueHandle r=edi.AppendResidue(ch, "CA");
   mol::AtomHandle a=edi.InsertAtom(r, "CA", geom::Vec3(32.0, -128.0, -2.5));
@@ -393,14 +463,16 @@ BOOST_AUTO_TEST_CASE(chain_name_too_long)
 BOOST_AUTO_TEST_CASE(atom_name_too_long)
 {
   std::stringstream out;
-  PDBWriter writer(out);
+  PDBWriter writer(out, IOProfile());
   
   mol::EntityHandle ent=mol::CreateEntity();
-  mol::XCSEditor edi=ent.RequestXCSEditor();
+  mol::XCSEditor edi=ent.EditXCS();
   mol::ChainHandle ch=edi.InsertChain("A");
   mol::ResidueHandle r=edi.AppendResidue(ch, "CA");
   mol::AtomHandle a=edi.InsertAtom(r, "CALCIUM", geom::Vec3(32.0, -128.0, -2.5));
   BOOST_CHECK_THROW(writer.Write(ent), IOException);
 }
 
+
+
 BOOST_AUTO_TEST_SUITE_END()
diff --git a/modules/io/tests/test_io_sdf.cc b/modules/io/tests/test_io_sdf.cc
index bbf858427da81a44a098a997b28682a1cb205073..f18f018bc48150ebb2776dea1f98d302db043ce5 100644
--- a/modules/io/tests/test_io_sdf.cc
+++ b/modules/io/tests/test_io_sdf.cc
@@ -60,7 +60,7 @@ BOOST_AUTO_TEST_CASE(simple_sdf)
   BOOST_CHECK_EQUAL(eh.GetChainCount(), 1);
   BOOST_CHECK_EQUAL(eh.GetAtomCount(),  6);
   BOOST_CHECK_EQUAL(eh.GetBondCount(),  6);
-  BOOST_CHECK_CLOSE(eh.GetMass(), Real(121.545502), Real(1e-4));
+  BOOST_CHECK_CLOSE(eh.GetMass(), Real(121.546997), Real(1e-4));
 
   // check atom/bond types
   mol::AtomHandle ah=eh.GetAtomList()[0];
@@ -70,7 +70,7 @@ BOOST_AUTO_TEST_CASE(simple_sdf)
   BOOST_CHECK_EQUAL(ah2.GetElement(), "Cl");
   BOOST_CHECK_CLOSE(ah.GetRadius(),  Real(1.55), Real(1e-2));
   BOOST_CHECK_CLOSE(ah2.GetRadius(), Real(1.75), Real(1e-2));
-  BOOST_CHECK_CLOSE(ah.GetMass(),  Real(14.0067), Real(1e-4));
+  BOOST_CHECK_CLOSE(ah.GetMass(),  Real(14.007), Real(1e-4));
   BOOST_CHECK_CLOSE(ah2.GetMass(), Real(35.453), Real(1e-3));
   BOOST_CHECK_EQUAL(ah.GetBondCount(),  3);
   BOOST_CHECK_EQUAL(ah2.GetBondCount(), 1);
@@ -151,6 +151,28 @@ BOOST_AUTO_TEST_CASE(write_sdf)
                             "testfiles/sdf/compound-out.sdf"));
 }
 
+BOOST_AUTO_TEST_CASE(write_sdf_view)
+{
+  // this scope is required to force the writer stream to be closed before
+  // opening the file again in compare_files. Avoids a race condition.
+  {
+    mol::EntityHandle eh = mol::CreateEntity();
+    EntityIOSDFHandler sdfh;
+    sdfh.Import(eh,"testfiles/sdf/compound.sdf");
+    mol::EntityView ev = eh.Select("(ele=C or ele=N) and aname!='1'");
+    SaveEntity(ev, "testfiles/sdf/compound-view-out.sdf");
+  }
+  BOOST_CHECK(compare_files("testfiles/sdf/compound-view.sdf",
+                            "testfiles/sdf/compound-view-out.sdf"));
+}
+
+BOOST_AUTO_TEST_CASE(nonexisting_file)
+{
+  mol::EntityHandle eh=mol::CreateEntity();
+  EntityIOSDFHandler sdfh;
+  BOOST_CHECK_THROW(sdfh.Import(eh,"non-existing-file.sdf"), IOException);
+}
+
 BOOST_AUTO_TEST_CASE(wrong_atomcount_error_sdf)
 {
   mol::EntityHandle eh=mol::CreateEntity();
diff --git a/modules/io/tests/testfiles/pdb/arg-glu-gln.pdb b/modules/io/tests/testfiles/pdb/arg-glu-gln.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..08051b8c3e40259f80ee5524061a86f58039ea85
--- /dev/null
+++ b/modules/io/tests/testfiles/pdb/arg-glu-gln.pdb
@@ -0,0 +1,29 @@
+ATOM    134  N  AARG A  15       8.286  13.769  40.774  0.50 60.53           N  
+ATOM    135  CA AARG A  15       8.903  14.440  41.922  0.50 64.64           C  
+ATOM    136  C  AARG A  15       7.867  15.000  42.911  0.50 65.25           C  
+ATOM    137  O  AARG A  15       8.174  15.244  44.080  0.50 60.65           O  
+ATOM    138  CB AARG A  15       9.857  15.549  41.457  0.50 65.83           C  
+ATOM    139  CG AARG A  15      10.863  15.121  40.391  0.50 64.71           C  
+ATOM    140  CD AARG A  15      11.814  16.270  40.051  0.50 69.97           C  
+ATOM    141  NE AARG A  15      12.505  16.084  38.775  0.50 69.52           N  
+ATOM    142  CZ AARG A  15      12.236  16.774  37.670  0.50 69.32           C  
+ATOM    143  NH1AARG A  15      11.291  17.706  37.674  0.50 55.65           N  
+ATOM    144  NH2AARG A  15      12.919  16.538  36.559  0.50 76.31           N  
+ATOM    145  N  CGLU A  15       8.306  13.754  40.761  0.17 60.57           N  
+ATOM    146  CA CGLU A  15       8.887  14.450  41.904  0.17 64.60           C  
+ATOM    147  C  CGLU A  15       7.813  14.816  42.928  0.17 64.89           C  
+ATOM    148  O  CGLU A  15       8.037  14.735  44.137  0.17 61.75           O  
+ATOM    149  CB CGLU A  15       9.635  15.707  41.448  0.17 65.94           C  
+ATOM    150  CG CGLU A  15      10.877  15.425  40.613  0.17 65.71           C  
+ATOM    151  CD CGLU A  15      11.545  16.692  40.105  0.17 68.96           C  
+ATOM    152  OE1CGLU A  15      10.877  17.748  40.063  0.17 67.85           O  
+ATOM    153  OE2CGLU A  15      12.740  16.631  39.744  0.17 68.13           O  
+ATOM    154  N  BGLN A  15       8.327  13.744  40.756  0.33 60.56           N  
+ATOM    155  CA BGLN A  15       8.877  14.452  41.907  0.33 64.61           C  
+ATOM    156  C  BGLN A  15       7.769  14.698  42.924  0.33 64.96           C  
+ATOM    157  O  BGLN A  15       7.924  14.416  44.116  0.33 61.27           O  
+ATOM    158  CB BGLN A  15       9.492  15.793  41.487  0.33 66.08           C  
+ATOM    159  CG BGLN A  15      10.726  15.695  40.597  0.33 65.69           C  
+ATOM    160  CD BGLN A  15      11.327  17.061  40.276  0.33 69.35           C  
+ATOM    161  OE1BGLN A  15      11.616  17.369  39.119  0.33 66.62           O  
+ATOM    162  NE2BGLN A  15      11.511  17.885  41.303  0.33 67.16           N
\ No newline at end of file
diff --git a/modules/io/tests/testfiles/pdb/het.pdb b/modules/io/tests/testfiles/pdb/het.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..f8fa944aa32acf2922dab16061d777d3a0ef42ce
--- /dev/null
+++ b/modules/io/tests/testfiles/pdb/het.pdb
@@ -0,0 +1,13 @@
+HET    AP5  A1215C     64                                                       
+ATOM     20  N   ILE A   3      26.039  48.836  36.139  1.00 21.59           N  
+ATOM     21  CA  ILE A   3      24.961  47.988  35.671  1.00 23.90           C  
+ATOM     22  C   ILE A   3      25.374  47.080  34.537  1.00 21.12           C  
+ATOM     23  O   ILE A   3      26.029  47.614  33.642  1.00 24.59           O  
+ATOM     24  CB  ILE A   3      23.802  48.880  35.202  1.00 23.84           C  
+ATOM     25  CG1 ILE A   3      23.317  49.724  36.378  1.00 26.14           C  
+ATOM     26  CG2 ILE A   3      22.660  48.010  34.642  1.00 19.29           C  
+ATOM     27  CD1 ILE A   3      22.436  50.890  35.992  1.00 24.97           C  
+HETATM 3320  PA  AP5 A1215C     18.089  46.955  20.531  1.00 17.77           P  
+HETATM 3321  O1A AP5 A1215C     17.885  47.954  21.576  1.00 16.47           O  
+HETATM 3322  O2A AP5 A1215C     18.847  47.325  19.359  1.00 15.16           O  
+END                                                                             
diff --git a/modules/io/tests/testfiles/pdb/val-with-deuterium.pdb b/modules/io/tests/testfiles/pdb/val-with-deuterium.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..6c623a1eff18d1d5d5685a541587e9255cf714fc
--- /dev/null
+++ b/modules/io/tests/testfiles/pdb/val-with-deuterium.pdb
@@ -0,0 +1,16 @@
+ATOM   4772  N   VAL A 297      26.034  -2.215  17.509  1.00 14.11           N  
+ATOM   4773  CA  VAL A 297      25.704  -3.589  17.846  1.00 15.41           C  
+ATOM   4774  C   VAL A 297      24.570  -4.026  16.905  1.00 15.48           C  
+ATOM   4775  O   VAL A 297      24.557  -5.141  16.370  1.00 16.17           O  
+ATOM   4776  CB  VAL A 297      25.107  -3.702  19.323  1.00 20.96           C  
+ATOM   4777  CG1 VAL A 297      24.248  -4.971  19.490  1.00 42.92           C  
+ATOM   4778  CG2 VAL A 297      26.208  -3.657  20.282  1.00 32.10           C  
+ATOM   4779  D   VAL A 297      25.787  -1.658  18.107  1.00 15.70           D  
+ATOM   4780  DA  VAL A 297      26.490  -4.176  17.775  1.00 13.23           D  
+ATOM   4781  DB  VAL A 297      24.531  -2.950  19.540  1.00 12.82           D  
+ATOM   4782 DG11 VAL A 297      23.948  -5.038  20.400  1.00 47.60           D  
+ATOM   4783 DG12 VAL A 297      23.489  -4.925  18.903  1.00 46.87           D  
+ATOM   4784 DG13 VAL A 297      24.779  -5.737  19.277  1.00 48.62           D  
+ATOM   4785 DG21 VAL A 297      25.850  -3.693  21.173  1.00 34.84           D  
+ATOM   4786 DG22 VAL A 297      26.791  -4.401  20.116  1.00 33.13           D  
+ATOM   4787 DG23 VAL A 297      26.704  -2.845  20.129  1.00 28.37           D   
\ No newline at end of file
diff --git a/modules/io/tests/testfiles/sdf/compound-view.sdf b/modules/io/tests/testfiles/sdf/compound-view.sdf
new file mode 100644
index 0000000000000000000000000000000000000000..0902b1232e979e69f500f1ff5c9c5a93fbf2994b
--- /dev/null
+++ b/modules/io/tests/testfiles/sdf/compound-view.sdf
@@ -0,0 +1,440 @@
+Test Ligand
+
+
+ 21 23  0  0  0  0            999 V2000
+   33.9561    6.2475   23.4088 C   0  0  0  0  0  0
+   32.6324    6.6232   23.1367 C   0  0  0  0  0  0
+   34.5295    6.5843   24.6557 C   0  0  0  0  0  0
+   31.8762    7.3329   24.0856 C   0  0  0  0  0  0
+   33.7671    7.2733   25.6188 C   0  0  0  0  0  0
+   32.4286    7.6460   25.3459 C   0  0  0  0  0  0
+   31.5951    8.3119   26.3710 C   0  0  0  0  0  0
+   31.3314    7.9140   27.6484 C   0  0  0  0  0  0
+   31.8735    6.7525   28.4344 C   0  0  0  0  0  0
+   30.4351    8.7885   28.2094 N   0  0  0  0  0  0
+   31.7811    6.9129   29.7679 N   0  0  0  0  0  0
+   30.1110    9.7809   27.3482 N   0  0  0  0  0  0
+   32.3829    6.0325   30.7674 C   0  0  0  0  0  0
+   30.7767    9.4820   26.2306 C   0  0  0  0  0  0
+   31.3859    4.9676   31.2295 C   0  0  0  0  0  0
+   30.7144   10.3135   25.0185 C   0  0  0  0  0  0
+   31.9150   10.8059   24.4681 C   0  0  0  0  0  0
+   31.8995   11.6150   23.3143 C   0  0  0  0  0  0
+   30.6694   11.9024   22.6787 C   0  0  0  0  0  0
+   29.4673   11.4261   23.2329 C   0  0  0  0  0  0
+   29.4821   10.6385   24.4075 C   0  0  0  0  0  0
+  1  2  1  0  0  0
+  1  3  2  0  0  0
+  2  4  2  0  0  0
+  3  5  1  0  0  0
+  4  6  1  0  0  0
+  5  6  2  0  0  0
+  6  7  1  0  0  0
+  7  8  2  0  0  0
+  7 14  1  0  0  0
+  8  9  1  0  0  0
+  8 10  1  0  0  0
+  9 11  1  0  0  0
+ 10 12  1  0  0  0
+ 11 13  1  0  0  0
+ 12 14  2  0  0  0
+ 13 15  1  0  0  0
+ 14 16  1  0  0  0
+ 16 17  1  0  0  0
+ 16 21  2  0  0  0
+ 17 18  2  0  0  0
+ 18 19  1  0  0  0
+ 19 20  2  0  0  0
+ 20 21  1  0  0  0
+M  END
+> <i_i_glide_confnum>
+2
+
+> <i_i_glide_lignum>
+1
+
+> <i_i_glide_posenum>
+352
+
+> <r_i_docking_score>
+-8.84426
+
+> <r_i_glide_ecoul>
+-16.1644
+
+> <r_i_glide_einternal>
+6.78671
+
+> <r_i_glide_emodel>
+-96.9661
+
+> <r_i_glide_energy>
+-62.2146
+
+> <r_i_glide_erotb>
+0.517993
+
+> <r_i_glide_esite>
+-0.0291388
+
+> <r_i_glide_evdw>
+-46.0502
+
+> <r_i_glide_gscore>
+-8.84426
+
+> <r_i_glide_hbond>
+-0.960751
+
+> <r_i_glide_ligand_efficiency>
+-0.327565
+
+> <r_i_glide_ligand_efficiency_ln>
+-2.0588
+
+> <r_i_glide_ligand_efficiency_sa>
+-0.982695
+
+> <r_i_glide_lipo>
+-2.84534
+
+> <r_i_glide_metal>
+-0
+
+> <r_i_glide_rewards>
+-0.799851
+
+> <r_i_glide_rmsd>
+0.6819
+
+$$$$
+Test Ligand
+
+
+ 21 23  0  0  0  0            999 V2000
+   34.1450    6.3862   23.4047 C   0  0  0  0  0  0
+   34.6745    6.7394   24.6654 C   0  0  0  0  0  0
+   32.7998    6.7274   23.0916 C   0  0  0  0  0  0
+   33.8742    7.4015   25.6120 C   0  0  0  0  0  0
+   32.0035    7.3913   24.0448 C   0  0  0  0  0  0
+   32.5275    7.7230   25.3191 C   0  0  0  0  0  0
+   31.6607    8.3431   26.3377 C   0  0  0  0  0  0
+   31.4133    7.9370   27.6169 C   0  0  0  0  0  0
+   31.9782    6.7689   28.3776 C   0  0  0  0  0  0
+   30.5206    8.8053   28.2099 N   0  0  0  0  0  0
+   32.0029    6.9625   29.7121 N   0  0  0  0  0  0
+   30.1677    9.8050   27.3570 N   0  0  0  0  0  0
+   32.5238    6.0208   30.6934 C   0  0  0  0  0  0
+   30.8244    9.5086   26.2225 C   0  0  0  0  0  0
+   31.3863    5.1079   31.1861 C   0  0  0  0  0  0
+   30.7465   10.3438   25.0101 C   0  0  0  0  0  0
+   31.9316   10.8558   24.4417 C   0  0  0  0  0  0
+   31.8920   11.6586   23.2829 C   0  0  0  0  0  0
+   30.6518   11.9231   22.6600 C   0  0  0  0  0  0
+   29.4612   11.4393   23.2345 C   0  0  0  0  0  0
+   29.4978   10.6576   24.4073 C   0  0  0  0  0  0
+  1  2  1  0  0  0
+  1  3  2  0  0  0
+  2  4  2  0  0  0
+  3  5  1  0  0  0
+  4  6  1  0  0  0
+  5  6  2  0  0  0
+  6  7  1  0  0  0
+  7  8  2  0  0  0
+  7 14  1  0  0  0
+  8  9  1  0  0  0
+  8 10  1  0  0  0
+  9 11  1  0  0  0
+ 10 12  1  0  0  0
+ 11 13  1  0  0  0
+ 12 14  2  0  0  0
+ 13 15  1  0  0  0
+ 14 16  1  0  0  0
+ 16 17  1  0  0  0
+ 16 21  2  0  0  0
+ 17 18  2  0  0  0
+ 18 19  1  0  0  0
+ 19 20  2  0  0  0
+ 20 21  1  0  0  0
+M  END
+> <i_i_glide_confnum>
+14
+
+> <i_i_glide_lignum>
+1
+
+> <i_i_glide_posenum>
+302
+
+> <r_i_docking_score>
+-8.79327
+
+> <r_i_glide_ecoul>
+-16.9687
+
+> <r_i_glide_einternal>
+5.76514
+
+> <r_i_glide_emodel>
+-98.4298
+
+> <r_i_glide_energy>
+-63.3874
+
+> <r_i_glide_erotb>
+0.517993
+
+> <r_i_glide_esite>
+-0.00975737
+
+> <r_i_glide_evdw>
+-46.4187
+
+> <r_i_glide_gscore>
+-8.79327
+
+> <r_i_glide_hbond>
+-0.966475
+
+> <r_i_glide_ligand_efficiency>
+-0.325677
+
+> <r_i_glide_ligand_efficiency_ln>
+-2.04693
+
+> <r_i_glide_ligand_efficiency_sa>
+-0.97703
+
+> <r_i_glide_lipo>
+-2.69167
+
+> <r_i_glide_metal>
+-0
+
+> <r_i_glide_rewards>
+-0.777126
+
+> <r_i_glide_rmsd>
+0.605551
+
+$$$$
+Test Ligand
+
+
+ 21 23  0  0  0  0            999 V2000
+   34.2768    6.4601   23.4276 C   0  0  0  0  0  0
+   34.7199    6.6807   24.7535 C   0  0  0  0  0  0
+   32.9608    6.8443   23.0740 C   0  0  0  0  0  0
+   33.8637    7.2655   25.7079 C   0  0  0  0  0  0
+   32.1001    7.4207   24.0338 C   0  0  0  0  0  0
+   32.5448    7.6388   25.3572 C   0  0  0  0  0  0
+   31.6578    8.2493   26.3632 C   0  0  0  0  0  0
+   31.3829    7.8493   27.6381 C   0  0  0  0  0  0
+   31.8957    6.6637   28.4136 C   0  0  0  0  0  0
+   30.4903    8.7246   28.2064 N   0  0  0  0  0  0
+   31.7656    6.7961   29.7467 N   0  0  0  0  0  0
+   30.1647    9.7304   27.3526 N   0  0  0  0  0  0
+   32.1947    5.8187   30.7363 C   0  0  0  0  0  0
+   30.8430    9.4334   26.2330 C   0  0  0  0  0  0
+   33.6957    5.9781   31.0077 C   0  0  0  0  0  0
+   30.7874   10.2877   25.0301 C   0  0  0  0  0  0
+   31.9854   10.7833   24.4695 C   0  0  0  0  0  0
+   31.9583   11.6080   23.3306 C   0  0  0  0  0  0
+   30.7247   11.9044   22.7018 C   0  0  0  0  0  0
+   29.5221   11.4297   23.2588 C   0  0  0  0  0  0
+   29.5448   10.6400   24.4309 C   0  0  0  0  0  0
+  1  2  1  0  0  0
+  1  3  2  0  0  0
+  2  4  2  0  0  0
+  3  5  1  0  0  0
+  4  6  1  0  0  0
+  5  6  2  0  0  0
+  6  7  1  0  0  0
+  7  8  2  0  0  0
+  7 14  1  0  0  0
+  8  9  1  0  0  0
+  8 10  1  0  0  0
+  9 11  1  0  0  0
+ 10 12  1  0  0  0
+ 11 13  1  0  0  0
+ 12 14  2  0  0  0
+ 13 15  1  0  0  0
+ 14 16  1  0  0  0
+ 16 17  1  0  0  0
+ 16 21  2  0  0  0
+ 17 18  2  0  0  0
+ 18 19  1  0  0  0
+ 19 20  2  0  0  0
+ 20 21  1  0  0  0
+M  END
+> <i_i_glide_confnum>
+1
+
+> <i_i_glide_lignum>
+1
+
+> <i_i_glide_posenum>
+177
+
+> <r_i_docking_score>
+-8.70173
+
+> <r_i_glide_ecoul>
+-15.8862
+
+> <r_i_glide_einternal>
+1.84397
+
+> <r_i_glide_emodel>
+-99.0481
+
+> <r_i_glide_energy>
+-62.44
+
+> <r_i_glide_erotb>
+0.517993
+
+> <r_i_glide_esite>
+-0.0274759
+
+> <r_i_glide_evdw>
+-46.5538
+
+> <r_i_glide_gscore>
+-8.70173
+
+> <r_i_glide_hbond>
+-0.97397
+
+> <r_i_glide_ligand_efficiency>
+-0.322286
+
+> <r_i_glide_ligand_efficiency_ln>
+-2.02562
+
+> <r_i_glide_ligand_efficiency_sa>
+-0.966858
+
+> <r_i_glide_lipo>
+-2.74283
+
+> <r_i_glide_metal>
+-0
+
+> <r_i_glide_rewards>
+-0.764823
+
+> <r_i_glide_rmsd>
+0.543804
+
+$$$$
+Test Ligand
+
+
+ 21 23  0  0  0  0            999 V2000
+   34.5144    6.6833   23.3611 C   0  0  0  0  0  0
+   33.1880    6.9515   22.9860 C   0  0  0  0  0  0
+   34.9381    7.0224   24.6610 C   0  0  0  0  0  0
+   32.2870    7.5460   23.8905 C   0  0  0  0  0  0
+   34.0422    7.6076   25.5720 C   0  0  0  0  0  0
+   32.7085    7.8735   25.1943 C   0  0  0  0  0  0
+   31.7655    8.4568   26.1623 C   0  0  0  0  0  0
+   31.4563    8.0176   27.4151 C   0  0  0  0  0  0
+   31.9612    6.8234   28.1735 C   0  0  0  0  0  0
+   30.4991    8.8399   27.9505 N   0  0  0  0  0  0
+   31.7656    6.8973   29.5011 N   0  0  0  0  0  0
+   30.1623    9.8254   27.0921 N   0  0  0  0  0  0
+   32.1790    5.9073   30.4826 C   0  0  0  0  0  0
+   30.8968    9.5864   26.0023 C   0  0  0  0  0  0
+   33.4739    6.3765   31.1528 C   0  0  0  0  0  0
+   30.8088   10.4312   24.8021 C   0  0  0  0  0  0
+   31.9800   11.0176   24.2785 C   0  0  0  0  0  0
+   31.9238   11.8291   23.1331 C   0  0  0  0  0  0
+   30.6968   12.0157   22.4634 C   0  0  0  0  0  0
+   29.5186   11.4761   23.0060 C   0  0  0  0  0  0
+   29.5649   10.7043   24.1795 C   0  0  0  0  0  0
+  1  2  1  0  0  0
+  1  3  2  0  0  0
+  2  4  2  0  0  0
+  3  5  1  0  0  0
+  4  6  1  0  0  0
+  5  6  2  0  0  0
+  6  7  1  0  0  0
+  7  8  2  0  0  0
+  7 14  1  0  0  0
+  8  9  1  0  0  0
+  8 10  1  0  0  0
+  9 11  1  0  0  0
+ 10 12  1  0  0  0
+ 11 13  1  0  0  0
+ 12 14  2  0  0  0
+ 13 15  1  0  0  0
+ 14 16  1  0  0  0
+ 16 17  1  0  0  0
+ 16 21  2  0  0  0
+ 17 18  2  0  0  0
+ 18 19  1  0  0  0
+ 19 20  2  0  0  0
+ 20 21  1  0  0  0
+M  END
+> <i_i_glide_confnum>
+9
+
+> <i_i_glide_lignum>
+1
+
+> <i_i_glide_posenum>
+294
+
+> <r_i_docking_score>
+-8.69162
+
+> <r_i_glide_ecoul>
+-14.7519
+
+> <r_i_glide_einternal>
+5.89466
+
+> <r_i_glide_emodel>
+-97.7232
+
+> <r_i_glide_energy>
+-63.1839
+
+> <r_i_glide_erotb>
+0.517993
+
+> <r_i_glide_esite>
+-0.0119369
+
+> <r_i_glide_evdw>
+-48.432
+
+> <r_i_glide_gscore>
+-8.69162
+
+> <r_i_glide_hbond>
+-0.870172
+
+> <r_i_glide_ligand_efficiency>
+-0.321912
+
+> <r_i_glide_ligand_efficiency_ln>
+-2.02327
+
+> <r_i_glide_ligand_efficiency_sa>
+-0.965735
+
+> <r_i_glide_lipo>
+-2.92829
+
+> <r_i_glide_metal>
+-0
+
+> <r_i_glide_rewards>
+-0.764823
+
+> <r_i_glide_rmsd>
+0.463026
+
+$$$$
diff --git a/modules/io/tests/testfiles/sdf/wrong_bondlinelength.sdf b/modules/io/tests/testfiles/sdf/wrong_bondlinelength.sdf
index 5be46a3936a635f503d5ec22bf7ccfb456b79922..ff012958c74b9ad11bc45b7f83c3f1d68a227357 100644
--- a/modules/io/tests/testfiles/sdf/wrong_bondlinelength.sdf
+++ b/modules/io/tests/testfiles/sdf/wrong_bondlinelength.sdf
@@ -9,9 +9,9 @@ Simple Ligand
     2.0000    2.0000    0.0000 C   0  0  0  0  0  0
    -1.0000   -1.0000    0.0000 Cl  0  0  0  0  0  0
   1  2  2  
-  1  3  1  0  0  0
-  1  6  1  0  0  0
-  2  4  1  0  0  0
+  1  3  
+  1  6  
+  2  4  
   3  4  1  0  0  0
   4  5  3  0  0  0
 M  END
diff --git a/modules/mol/alg/molalg.rst b/modules/mol/alg/molalg.rst
index 2daf3ca7597bca27d86b9d86d53e7c67a33b5bb6..7758f3ff290de4812b9635514cf0f7a2f51e2f0a 100644
--- a/modules/mol/alg/molalg.rst
+++ b/modules/mol/alg/molalg.rst
@@ -40,4 +40,30 @@
   :param ref: The index of the reference frame to use for superposition. If set 
      to -1, the each frame is superposed to the previous frame.
      
-  :returns: A newly created coord group containing the superposed frames.
\ No newline at end of file
+  :returns: A newly created coord group containing the superposed frames.
+  
+  
+Steric Clashes
+--------------------------------------------------------------------------------
+
+The following function detects steric clashes in atomic structures. Two atoms are clashing if their euclidian distance is smaller than a threshold value. The threshold values are calculated from high-resolution X-ray structures for each possible element pair. The value is chosen such that 99.99% of observed distances between 0 and 5 Angstroem are above the threshold.
+
+
+.. function:: FilterClashes(ent, tolerance=0.0)
+
+  This function filters out residues with clashing atoms. If the clashing atom 
+  is a backbone atom, the complete residue is removed, if the atom is part of 
+  the sidechain, only the sidechain atoms are removed.
+  
+  Hydrogen and deuterium atoms are ignored.
+  
+  :param ent: The input entity
+  :type ent: :class:`~ost.mol.EntityView` or :class:`~ost.mol.EntityHandle`
+  :param tolerance: The tolerance in (Angstroem) is substracted from the 
+     thresholds calculated from high resolution X-ray structures to make the 
+     function less pedantic. Negative values are also allowed and make the 
+     function more stringent.
+
+  :returns: The filtered :class:`~ost.mol.EntityView`
+
+
diff --git a/modules/mol/alg/pymod/wrap_mol_alg.cc b/modules/mol/alg/pymod/wrap_mol_alg.cc
index 67f4fbf9e13454d105b0f69844297b06a1508309..4f1f03d4ef8424beb299d419c577cce61eebb0a8 100644
--- a/modules/mol/alg/pymod/wrap_mol_alg.cc
+++ b/modules/mol/alg/pymod/wrap_mol_alg.cc
@@ -17,14 +17,13 @@
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
 
-/*
- * Author Juergen Haas
- */
 #include <boost/python.hpp>
 #include <ost/config.hh>
 #include <ost/mol/alg/local_dist_test.hh>
 #include <ost/mol/alg/superpose_frames.hh>
+#include <ost/mol/alg/filter_clashes.hh>
 using namespace boost::python;
+using namespace ost;
 
 void export_svdSuperPose();
 
@@ -32,6 +31,14 @@ void export_svdSuperPose();
 void export_entity_to_density();
 #endif
 
+namespace {
+  
+Real (*ldt_a)(const mol::EntityView&, const mol::EntityView& ref, Real, Real)=&mol::alg::LocalDistTest;
+Real (*ldt_b)(const seq::AlignmentHandle&,Real, Real, int, int)=&mol::alg::LocalDistTest;
+mol::EntityView (*fc_a)(const mol::EntityView&, Real,bool)=&mol::alg::FilterClashes;
+mol::EntityView (*fc_b)(const mol::EntityHandle&, Real, bool)=&mol::alg::FilterClashes;
+}
+
 BOOST_PYTHON_MODULE(_mol_alg)
 {
   export_svdSuperPose();
@@ -39,8 +46,11 @@ BOOST_PYTHON_MODULE(_mol_alg)
   export_entity_to_density();
   #endif
   
-  def("LocalDistTest", &ost::mol::alg::LocalDistTest);
+  def("LocalDistTest", ldt_a);
+  def("LocalDistTest", ldt_b, (arg("ref_index")=0, arg("mdl_index")=1));
+  def("FilterClashes", fc_a, (arg("ent"), arg("tolerance")=0.1, arg("always_remove_bb")=false));
+  def("FilterClashes", fc_b, (arg("ent"), arg("tolerance")=0.1, arg("always_remove_bb")=false));
   def("SuperposeFrames", &ost::mol::alg::SuperposeFrames, 
       (arg("source"), arg("sel")=ost::mol::EntityView(), arg("begin")=0, 
-       arg("end")=-1, arg("ref")=-1));  
+       arg("end")=-1, arg("ref")=-1));
 }
diff --git a/modules/mol/alg/src/CMakeLists.txt b/modules/mol/alg/src/CMakeLists.txt
index e613a9c735cff3588598ae612eec5ff0ce805202..d1c84aa186a4fb77a47bde198acf8adc1f472371 100644
--- a/modules/mol/alg/src/CMakeLists.txt
+++ b/modules/mol/alg/src/CMakeLists.txt
@@ -4,6 +4,7 @@ set(OST_MOL_ALG_HEADERS
   sec_structure_segments.hh
   local_dist_test.hh
   superpose_frames.hh
+  filter_clashes.hh
 )
 
 set(OST_MOL_ALG_SOURCES
@@ -11,9 +12,10 @@ set(OST_MOL_ALG_SOURCES
   sec_structure_segments.cc
   local_dist_test.cc
   superpose_frames.cc
+  filter_clashes.cc
 )
 
-set(MOL_ALG_DEPS mol)
+set(MOL_ALG_DEPS mol seq)
 
 if (ENABLE_IMG)
   set(OST_MOL_ALG_HEADERS
@@ -29,10 +31,14 @@ if (ENABLE_IMG)
   set(MOL_ALG_DEPS ${MOL_ALG_DEPS} img img_alg)
 endif()
 
+executable(NAME ldt SOURCES ldt.cc 
+           DEPENDS_ON io mol_alg STATIC)
+
 module(NAME mol_alg SOURCES ${OST_MOL_ALG_SOURCES}
        HEADERS ${OST_MOL_ALG_HEADERS}
        HEADER_OUTPUT_DIR ost/mol/alg
-       DEPENDS_ON ${MOL_ALG_DEPS})
+       DEPENDS_ON ${MOL_ALG_DEPS}
+       LINK ${BOOST_PROGRAM_OPTIONS})
 
 copy_if_different("." "${STAGE_DIR}/share/openstructure"
                   "atom_scattering_properties.txt" "ATOM_SCATTERING_PROPS"
diff --git a/modules/mol/alg/src/entity_to_density.cc b/modules/mol/alg/src/entity_to_density.cc
index 269f23add94f340c0b3f4eb40184b9feadc81bf7..6a15ac44fc68fd179f19b5f1d9405b259ecc3923 100644
--- a/modules/mol/alg/src/entity_to_density.cc
+++ b/modules/mol/alg/src/entity_to_density.cc
@@ -135,7 +135,7 @@ public:
       bool found = false;
       while (found != true && table_iter!=scatt_props_table_.end())
       {
-        if ( (*table_iter).element == (*iterator).GetAtomProps().element)
+        if ( (*table_iter).element == (*iterator).GetElement())
         {        
           geom::Vec3 coord = (*iterator).GetPos();
 
@@ -287,7 +287,7 @@ public:
                                              scatt_props_table_.begin();
       bool found = false;
       while (found != true && table_iter!=scatt_props_table_.end()) {
-        if ((*table_iter).element == (*iterator).GetAtomProps().element) {
+        if ((*table_iter).element == (*iterator).GetElement()) {
           found = true;
           Real a = (*table_iter).atomic_weight;
           geom::Vec3 coord = (*iterator).GetPos();
diff --git a/modules/mol/alg/src/filter_clashes.cc b/modules/mol/alg/src/filter_clashes.cc
new file mode 100644
index 0000000000000000000000000000000000000000..7a176cba2841155aa0311f3c5c00c505f62b22c8
--- /dev/null
+++ b/modules/mol/alg/src/filter_clashes.cc
@@ -0,0 +1,150 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#include <ost/log.hh>
+#include <ost/mol/mol.hh>
+#include "filter_clashes.hh"
+
+namespace ost { namespace mol { namespace alg {
+
+namespace {
+
+Real GetThreshold(const String& ele1, const String& ele2) {
+  if (ele1.length()!=1 || ele2.length()!=1) {
+    return 1.5;
+  }
+  switch (ele1[0]) {
+    case 'C' :
+      switch (ele2[0]) {
+        case 'C' : return 2.10;
+        case 'N' : return 2.10;
+        case 'S' : return 2.45;
+        case 'O' : return 2.25;
+        default: return 1.5;
+      }
+    case 'N':
+      switch (ele2[0]) {
+        case 'C' : return 2.10;
+        case 'N' : return 2.05;
+        case 'S' : return 2.55;
+        case 'O' : return 2.10;
+        default: return 1.5;
+      }
+    case 'O':
+      switch (ele2[0]) {
+        case 'C' : return 2.25;
+        case 'N' : return 2.10;
+        case 'S' : return 2.45;
+        case 'O' : return 2.05;
+        default: return 1.5;
+      }
+    case 'S':
+      switch (ele2[0]) {
+        case 'C' : return 2.45;
+        case 'N' : return 2.55;
+        case 'S' : return 1.80;
+        case 'O' : return 2.45;
+        default: return 1.5;
+      }
+    default:
+      return 1.5;
+  }
+}
+
+
+}
+
+EntityView FilterClashes(const EntityView& ent, Real tolerance, 
+                         bool always_remove_bb)
+{
+  EntityView filtered=ent.CreateEmptyView();
+  ResidueViewList residues=ent.GetResidueList();
+  for (ResidueViewList::iterator 
+       i=residues.begin(), e=residues.end(); i!=e; ++i) {
+    bool remove_sc=false, remove_bb=false;
+    ResidueView res=*i;
+    const AtomViewList& atoms=res.GetAtomList();
+    for (AtomViewList::const_iterator 
+         j=atoms.begin(), e2=atoms.end(); j!=e2; ++j) {
+      AtomView atom=*j;
+      String ele1=atom.GetElement();
+      if (ele1=="H" || ele1=="D") {
+        continue;
+      }
+      AtomViewList within=ent.FindWithin(atom.GetPos(), 2.5-tolerance);
+      for (AtomViewList::iterator 
+           k=within.begin(), e3=within.end(); k!=e3; ++k) {
+        AtomView atom2=*k;
+        if (atom2==atom) {
+          continue;
+        }
+        String ele2=atom2.GetElement();
+        if (ele2=="H" || ele2=="D") {
+          continue;
+        }
+        // In theory, this should also trigger for disulfide bonds, but 
+        // since we don't detect disulfides correctly, we can't count on that 
+        // and we instead allow S-S distances down to 1.8.
+        if (atom.GetHandle().FindBondToAtom(atom2.GetHandle()).IsValid()) {
+          continue;
+        }
+        Real d=geom::Length2(atom.GetPos()-atom2.GetPos());
+        Real threshold=GetThreshold(ele1, ele2)-tolerance;
+        if (d<threshold*threshold) {
+          remove_sc=true;
+          if (always_remove_bb==true) {
+            remove_bb=true;
+            continue;
+          }
+          String name=atom.GetName();
+          if (name=="CA" || name=="N" || name=="O" || name=="C") {
+            remove_bb=true;
+          }
+        }
+      }
+    }
+    if (remove_bb) {
+      LOG_VERBOSE("removing whole residue " << res);
+      continue;
+    }
+    if (remove_sc) {
+      LOG_VERBOSE("removing sidechain of residue " << res);
+      for (AtomViewList::const_iterator 
+           j=atoms.begin(), e2=atoms.end(); j!=e2; ++j) {
+       AtomView atom=*j;
+       String name=atom.GetName();
+       if (name=="CA" || name=="N" || name=="O" || name=="C") {
+         filtered.AddAtom(atom);
+       }
+      }
+    }
+    filtered.AddResidue(res, ViewAddFlag::INCLUDE_ATOMS);
+  }
+  return filtered;
+}
+
+
+EntityView FilterClashes(const EntityHandle& ent, Real tolerance, 
+                         bool always_remove_bb)
+{
+  return FilterClashes(ent.CreateFullView(), tolerance, always_remove_bb);
+}
+
+
+}}}
+
diff --git a/modules/img/base/src/version.hh b/modules/mol/alg/src/filter_clashes.hh
similarity index 62%
rename from modules/img/base/src/version.hh
rename to modules/mol/alg/src/filter_clashes.hh
index f893148f7ffa6f0ba61657238373a869178a6b56..043510d9817b5c2260748ad4b3bda3478e2adfab 100644
--- a/modules/img/base/src/version.hh
+++ b/modules/mol/alg/src/filter_clashes.hh
@@ -2,7 +2,6 @@
 // This file is part of the OpenStructure project <www.openstructure.org>
 //
 // Copyright (C) 2008-2010 by the OpenStructure authors
-// Copyright (C) 2003-2010 by the IPLT authors
 //
 // This library 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
@@ -17,23 +16,23 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+#ifndef OST_MOL_ALG_FILTER_CLASHES_HH
+#define OST_MOL_ALG_FILTER_CLASHES_HH
 
-/*
-  versioning info
+#include <ost/mol/entity_view.hh>
+#include <ost/mol/alg/module_config.hh>
 
-  Author: Ansgar Philippsen
-*/
+namespace ost { namespace mol { namespace alg {
 
-#ifndef IMG_VERSION_H
-#define IMG_VERSION_H
 
-#include <ost/img/module_config.hh>
+EntityView DLLEXPORT_OST_MOL_ALG FilterClashes(const EntityView& ent, 
+                                               Real tolerance=0.1,
+                                               bool always_remove_bb=false);
 
-namespace ost { namespace img {
-
-DLLEXPORT_OST_IMG_BASE String GetVersion();
-
-}} // namespace img
+EntityView DLLEXPORT_OST_MOL_ALG FilterClashes(const EntityHandle& ent, 
+                                               Real tolerance=0.1,
+                                               bool always_remove_bb=false);
+}}}
 
 
 #endif
diff --git a/modules/mol/alg/src/ldt.cc b/modules/mol/alg/src/ldt.cc
new file mode 100644
index 0000000000000000000000000000000000000000..10971167237080de0a6422096c59070be3d6abcf
--- /dev/null
+++ b/modules/mol/alg/src/ldt.cc
@@ -0,0 +1,128 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#if defined (_MSC_VER)
+#define BOOST_ALL_DYN_LINK 1
+#endif
+#include <boost/program_options.hpp>
+#include <ost/mol/alg/local_dist_test.hh>
+#include <ost/mol/alg/filter_clashes.hh>
+#include <ost/io/mol/pdb_reader.hh>
+#include <ost/io/io_exception.hh>
+#include <ost/conop/conop.hh>
+
+using namespace ost;
+using namespace ost::io;
+using namespace ost::mol;
+namespace po=boost::program_options;
+
+EntityHandle load(const String& file, const IOProfile& profile)
+{
+  try {
+    PDBReader reader(file, profile);
+    if (reader.HasNext()) {
+      EntityHandle ent=CreateEntity();
+      reader.Import(ent);
+      conop::Conopology& conop_inst=conop::Conopology::Instance();
+      conop_inst.ConnectAll(conop_inst.GetBuilder(), ent);
+      return ent;
+    }
+    std::cerr << "ERROR: '" << file << "' does not contain any ATOM records. " 
+              << "Are you sure this is a PDB file?" << std::endl;
+    return EntityHandle();
+  } catch (io::IOException& e) {
+    std::cerr << "ERROR: " << e.what() << std::endl;
+    return EntityHandle();
+  }
+}
+
+void usage()
+{
+  std::cerr << "usage: ldt [options] <mod1> [mod1 [mod2]] <ref>" << std::endl;
+  std::cerr << "   -s        selection performed on ref" << std::endl;
+  std::cerr << "   -c        use Calphas only" << std::endl;
+  std::cerr << "   -f        filter clashes (not implemented yet)" << std::endl;
+  std::cerr << "   -t        fault tolerant parsing" << std::endl;  
+}
+
+int main (int argc, char **argv)
+{
+  IOProfile profile;
+  // parse options
+  String sel;
+  bool filter_clashes=false;
+  po::options_description desc("Options");
+  desc.add_options()
+    ("calpha,c", "consider only calpha atoms")
+    ("sel,s", po::value<String>(&sel)->default_value(""), "selection for reference")
+    ("tolerant,t", "fault tolerant mode")
+    ("filter-clashes,f", "filter clashes")
+    ("files", po::value< std::vector<String> >(), "input file")
+  ;
+  po::positional_options_description p;
+  p.add("files", -1);
+  po::variables_map vm;
+  po::store(po::command_line_parser(argc, argv).
+                options(desc).positional(p).run(),
+            vm);
+  po::notify(vm);
+  if (vm.count("calpha")) {
+    profile.calpha_only=true;
+  }
+  if (vm.count("filter-clashes")) {
+    filter_clashes=true;
+  }
+  if (vm.count("tolerant")) {
+    profile.fault_tolerant=true;
+  }
+  std::vector<String> files;
+  if (vm.count("files")) {
+    files=vm["files"].as<std::vector<String> >();
+  } else {
+    usage();
+    exit(-1);
+  }
+  String ref_file=files.back();
+  EntityHandle ref=load(ref_file, profile);
+  if (!ref) {
+    return -1;
+  }
+  files.pop_back();
+  EntityView ref_view=ref.Select(sel);
+  for (size_t i=0; i<files.size(); ++i) {
+    EntityHandle model=load(files[i], profile);
+    if (!model) {
+      if (!profile.fault_tolerant) {
+        return -1;
+      }
+      continue;
+    }
+    EntityView v=model.CreateFullView();
+    if (filter_clashes) {
+      v=alg::FilterClashes(v);
+    }
+    float cutoffs[]={0.5,1,2,4};
+    float ldt=0.0;
+    for (int n=0; n<4; ++n) {
+      ldt+=alg::LocalDistTest(v, ref_view, cutoffs[n], 8.0);
+    }
+    ldt/=4.0;
+    std::cout << files[i] << " " << ldt << std::endl;
+  }
+  return 0;
+}
\ No newline at end of file
diff --git a/modules/mol/alg/src/local_dist_test.cc b/modules/mol/alg/src/local_dist_test.cc
index bd88902b0e181bb29f62da86ae41367137b23ded..de78df711c03dcfaf619de243c193b0bd70576f8 100644
--- a/modules/mol/alg/src/local_dist_test.cc
+++ b/modules/mol/alg/src/local_dist_test.cc
@@ -1,3 +1,4 @@
+#include <ost/log.hh>
 #include <ost/mol/mol.hh>
 #include "local_dist_test.hh"
 
@@ -48,11 +49,11 @@ bool swappable(const String& rname, const String& aname)
   return false;
 }
 
-std::pair<Real, Real> calc_overlap(ResidueView ref_res, 
-                                   EntityView ref,
-                                   ChainView mdl_chain, 
-                                   Real tol, Real max_dist, bool only_fixed, 
-                                   bool swap)
+std::pair<Real, Real> calc_overlap1(ResidueView ref_res, 
+                                    EntityView ref,
+                                    ChainView mdl_chain, 
+                                    Real tol, Real max_dist, bool only_fixed, 
+                                    bool swap)
 {
   std::pair<Real, Real> overlap(0.0, 0.0);
   AtomViewList ref_atoms=ref_res.GetAtomList();
@@ -81,7 +82,7 @@ std::pair<Real, Real> calc_overlap(ResidueView ref_res,
           continue;
         }
         AtomView av2=mdl_chain.FindAtom(aj->GetResidue().GetNumber(), 
-                                             aj->GetName());
+                                        aj->GetName());
         overlap.second+=1.0;
         if (!(av1 && av2)) {
           continue;
@@ -111,17 +112,106 @@ std::pair<Real, Real> calc_overlap(ResidueView ref_res,
   return overlap;
 }
 
+std::pair<Real, Real> calc_overlap2(const seq::ConstSequenceHandle& ref_seq,
+                                    const seq::ConstSequenceHandle& mdl_seq,
+                                    int pos, Real tol, Real max_dist, 
+                                    bool only_fixed, bool swap)
+{
+  std::pair<Real, Real> overlap(0.0, 0.0);
+  EntityView ref=ref_seq.GetAttachedView();
+  ResidueView ref_res=ref_seq.GetResidue(pos);
+  if (!ref_res.IsValid()) {
+    return std::pair<Real,Real>(0.0, 0.0);
+  }
+  AtomViewList ref_atoms=ref_res.GetAtomList();
+  ResidueView mdl_res=mdl_seq.GetResidue(pos);
+  AtomViewList within;
+  if (max_dist<0) {
+    within=ref.GetAtomList();
+  }  
+  for (AtomViewList::iterator ai=ref_atoms.begin(),
+       ae=ref_atoms.end(); ai!=ae; ++ai) {
+    if (ai->GetElement()=="H") { continue; }
+    String name=swap ? swapped_name(ai->GetName()) : ai->GetName();
+    AtomView av1=mdl_res ? mdl_res.FindAtom(name) : AtomView();
+    if (max_dist>=0){ 
+      within=ref.FindWithin(ai->GetPos(), max_dist);
+    }
+    for (AtomViewList::iterator aj=within.begin(),
+         ae2=within.end(); aj!=ae2; ++aj) {
+      if (aj->GetElement()=="H") { continue; }
+      if (only_fixed) {
+        if (aj->GetResidue().GetNumber()==ref_res.GetNumber()) {
+          continue;
+        }
+        if (swappable(aj->GetResidue().GetName(), aj->GetName())) {
+          continue;
+        }
+        overlap.second+=1.0;
+        // map from residue index to position in alignment
+        try {
+          int aln_pos=ref_seq.GetPos(aj->GetResidue().GetIndex());
+          ResidueView r2=mdl_seq.GetResidue(aln_pos);
+          if (!r2.IsValid()) {
+            continue;
+          }
+          AtomView av2=r2.FindAtom(aj->GetName());
+          if (!(av1 && av2)) {
+            continue;
+          }
+          Real mdl_dist=geom::Length(av1.GetPos()-av2.GetPos());
+          Real ref_dist=geom::Length(ai->GetPos()-aj->GetPos());
+          if (std::abs(mdl_dist-ref_dist)<tol) {
+            overlap.first+=1;
+          }
+        } catch(...) { }
+        continue;
+      } else {
+        if (aj->GetResidue().GetNumber()>ref_res.GetNumber()) {
+          overlap.second+=1.0;
+          try {
+           int aln_pos=ref_seq.GetPos(aj->GetResidue().GetIndex());
+            ResidueView r2=mdl_seq.GetResidue(aln_pos);
+            if (!r2.IsValid()) {
+              continue;
+            }
+            AtomView av2=r2.FindAtom(aj->GetName());
+            if (!(av1 && av2)) {
+              continue;
+            }
+            Real mdl_dist=geom::Length(av1.GetPos()-av2.GetPos());
+            Real ref_dist=geom::Length(ai->GetPos()-aj->GetPos());
+            if (std::abs(mdl_dist-ref_dist)<tol) {
+              overlap.first+=1;
+            }
+          } catch (...) { }
+        }  
+      }
+    }      
+  }
+  return overlap;
+}
+
 }
 
 Real LocalDistTest(const EntityView& mdl, const EntityView& ref,
                    Real cutoff, Real max_dist)
 {
-  ResidueViewList ref_residues=ref.GetResidueList();
+  if (!mdl.GetResidueCount()) {
+    LOG_WARNING("model structures doesn't contain any residues");
+    return 0.0;
+  }
+
+  if (!ref.GetResidueCount()) {
+    LOG_WARNING("reference structures doesn't contain any residues");
+    return 0.0;
+  }
+  ResidueViewList ref_residues=ref.GetResidueList();  
   ChainView mdl_chain=mdl.GetChainList()[0];  
   // Residues with symmetric side-chains require special treatment as there are 
   // two possible ways to name the atoms. We calculate the overlap with the 
   // fixed atoms and take the solution that gives bigger scores.
-  XCSEditor edi=ref.GetHandle().RequestXCSEditor(BUFFERED_EDIT);
+  XCSEditor edi=ref.GetHandle().EditXCS(BUFFERED_EDIT);
   for (ResidueViewList::iterator
        i=ref_residues.begin(), e=ref_residues.end(); i!=e; ++i) {
     const String rname=i->GetName();
@@ -134,10 +224,10 @@ Real LocalDistTest(const EntityView& mdl, const EntityView& ref,
       continue;
     }
 
-    std::pair<Real, Real> ov1=calc_overlap(*i, ref, mdl_chain, 
+    std::pair<Real, Real> ov1=calc_overlap1(*i, ref, mdl_chain, 
                                           cutoff, max_dist, true, 
                                           false);
-    std::pair<Real, Real> ov2=calc_overlap(*i, ref, mdl_chain, 
+    std::pair<Real, Real> ov2=calc_overlap1(*i, ref, mdl_chain, 
                                           cutoff, max_dist, true, 
                                           true); 
     if (ov1.first/ov1.second<ov2.first/ov2.second) {
@@ -148,18 +238,68 @@ Real LocalDistTest(const EntityView& mdl, const EntityView& ref,
          edi.RenameAtom(j->GetHandle(), swapped_name(j->GetName()));
        }
      }
-
     }
   }
   std::pair<Real, Real> total_ov(0.0, 0.0);
   for (ResidueViewList::iterator
        i=ref_residues.begin(), e=ref_residues.end(); i!=e; ++i) {
-     std::pair<Real, Real> ov1=calc_overlap(*i, ref, mdl_chain, cutoff, 
+     std::pair<Real, Real> ov1=calc_overlap1(*i, ref, mdl_chain, cutoff, 
                                             max_dist, false, false);
      total_ov.first+=ov1.first;
      total_ov.second+=ov1.second;
   }
-  return total_ov.first/total_ov.second;
+  return total_ov.first/(total_ov.second ? total_ov.second : 1);
+}
+
+Real LocalDistTest(const ost::seq::AlignmentHandle& aln,
+                   Real cutoff, Real max_dist, int ref_index, int mdl_index)
+{
+  seq::ConstSequenceHandle ref_seq=aln.GetSequence(ref_index);
+  seq::ConstSequenceHandle mdl_seq=aln.GetSequence(mdl_index);  
+  if (!ref_seq.HasAttachedView()) {
+    LOG_ERROR("reference sequence doesn't have a view attached.");
+    return 0.0;
+  }
+  if (!mdl_seq.HasAttachedView()) {
+    LOG_ERROR("model sequence doesn't have a view attached");
+    return 0.0;
+  }
+  XCSEditor edi=ref_seq.GetAttachedView().GetHandle().EditXCS(BUFFERED_EDIT);
+  for (int i=0; i<aln.GetLength(); ++i) {
+    ResidueView mdl_res=mdl_seq.GetResidue(i);
+    if (!mdl_res) {
+      continue;
+    }
+    String rname=mdl_res.GetName();
+    if (!(rname=="GLU" || rname=="ASP" || rname=="VAL" || rname=="TYR" || 
+         rname=="PHE" || rname=="LYS" || rname=="ARG")) {
+      continue;
+    }
+    std::pair<Real, Real> ov1=calc_overlap2(ref_seq, mdl_seq, i,
+                                            cutoff, max_dist, true, 
+                                            false);
+    std::pair<Real, Real> ov2=calc_overlap2(ref_seq, mdl_seq, i,
+                                            cutoff, max_dist, true, 
+                                            true);
+    if (ov1.first/ov1.second<ov2.first/ov2.second) {
+     AtomViewList atoms=mdl_res.GetAtomList();
+     for (AtomViewList::iterator j=atoms.begin(), 
+          e2=atoms.end(); j!=e2; ++j) {
+       if (swappable(rname, j->GetName())) {
+         edi.RenameAtom(j->GetHandle(), swapped_name(j->GetName()));
+       }
+     }
+    }
+  }
+  std::pair<Real, Real> total_ov(0.0, 0.0);
+  for (int i=0; i<aln.GetLength(); ++i) {
+     std::pair<Real, Real> ov1=calc_overlap2(ref_seq, mdl_seq, i, cutoff, 
+                                             max_dist, false, false);
+     total_ov.first+=ov1.first;
+     total_ov.second+=ov1.second;
+  }
+  return total_ov.first/(total_ov.second ? total_ov.second : 1);
+  return 0.0;
 }
 
 }}}
diff --git a/modules/mol/alg/src/local_dist_test.hh b/modules/mol/alg/src/local_dist_test.hh
index f0ba3ebea20a6138a0cf14f2a34d24839abe3ef4..a4e645acce1e5ae8d490e34a52860af0ac9705b7 100644
--- a/modules/mol/alg/src/local_dist_test.hh
+++ b/modules/mol/alg/src/local_dist_test.hh
@@ -1,14 +1,37 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
 #ifndef OST_MOL_ALG_LOCAL_DIST_TEST_HH
 #define OST_MOL_ALG_LOCAL_DIST_TEST_HH
 
 #include <ost/mol/entity_view.hh>
 #include <ost/mol/alg/module_config.hh>
+#include <ost/seq/alignment_handle.hh>
 
 namespace ost { namespace mol { namespace alg {
   
 Real DLLEXPORT_OST_MOL_ALG LocalDistTest(const EntityView& mdl,
                                          const EntityView& ref,
                                          Real cutoff, Real max_dist);
+
+Real DLLEXPORT_OST_MOL_ALG LocalDistTest(const ost::seq::AlignmentHandle& aln,
+                                         Real cutoff, Real max_dist, 
+                                         int ref_index=0, int mdl_index=1);
 }}}
 
 #endif
diff --git a/modules/mol/alg/src/svd_superpose.cc b/modules/mol/alg/src/svd_superpose.cc
index 191871a9c888eca76ef2672def7d08e71281523c..90b6a8c04a6adbddbcd63cc9859ea579ad95d374 100644
--- a/modules/mol/alg/src/svd_superpose.cc
+++ b/modules/mol/alg/src/svd_superpose.cc
@@ -354,7 +354,7 @@ SuperpositionResult SuperposeAtoms(const mol::AtomViewList& atoms1,
   res.ncycles=1;
   mol::AtomView jv=atoms1.front();
   if (apply_transform){
-    mol::XCSEditor ed=jv.GetResidue().GetChain().GetEntity().GetHandle().RequestXCSEditor();
+    mol::XCSEditor ed=jv.GetResidue().GetChain().GetEntity().GetHandle().EditXCS();
     ed.ApplyTransform(res.transformation);
   }
   return res;
@@ -381,7 +381,7 @@ SuperpositionResult SuperposeSVD(const mol::EntityView& ev1,
   //save rmsd info
   res.rmsd=CalculateRMSD(ev1, ev2, res.transformation);
   if (apply_transform){
-    mol::XCSEditor ed=ev1.GetHandle().RequestXCSEditor();
+    mol::XCSEditor ed=ev1.GetHandle().EditXCS();
     ed.ApplyTransform(res.transformation);
   }
   return res;
@@ -457,7 +457,7 @@ SuperpositionResult IterativeSuperposition(mol::EntityView& ev1,
   result.entity_view2=CreateViewFromAtomList(atoms_b);
 
   if (apply_transform){
-    mol::XCSEditor ed=ev1.GetHandle().RequestXCSEditor();
+    mol::XCSEditor ed=ev1.GetHandle().EditXCS();
     ed.ApplyTransform(result.transformation);
   }
   return result;
diff --git a/modules/mol/alg/tests/test_superposition.cc b/modules/mol/alg/tests/test_superposition.cc
index c410a768ac11b18155fca970f9f1fe23b1c0ec40..0d18b1aa8cb623655c332a7305de485307112d5a 100644
--- a/modules/mol/alg/tests/test_superposition.cc
+++ b/modules/mol/alg/tests/test_superposition.cc
@@ -33,21 +33,18 @@ using namespace ost::mol::alg;
 struct Fixture {
   Fixture() {
 
-    AtomProp prop;
-    prop.element="C";
-
     e=CreateEntity();
-    XCSEditor ed=e.RequestXCSEditor();
+    XCSEditor ed=e.EditXCS();
     c=ed.InsertChain("A");
     r=ed.AppendResidue(c, "XXX");
-    ab=ed.InsertAtom(r, "A", geom::Vec3(-5,-5,-5), prop);
-    ac=ed.InsertAtom(r, "B", geom::Vec3(-5, 5,-5), prop);
-    ad=ed.InsertAtom(r, "C", geom::Vec3(-5, 5, 5), prop);
-    ae=ed.InsertAtom(r, "D", geom::Vec3(-5,-5, 5), prop);
-    af=ed.InsertAtom(r, "E", geom::Vec3(5,-5, 5), prop);
-    ag=ed.InsertAtom(r, "F", geom::Vec3(5,-5,-5), prop);
-    ah=ed.InsertAtom(r, "G", geom::Vec3(5, 5,-5), prop);
-    ai=ed.InsertAtom(r, "H", geom::Vec3(5, 5, 5), prop);
+    ab=ed.InsertAtom(r, "A", geom::Vec3(-5,-5,-5), "C");
+    ac=ed.InsertAtom(r, "B", geom::Vec3(-5, 5,-5), "C");
+    ad=ed.InsertAtom(r, "C", geom::Vec3(-5, 5, 5), "C");
+    ae=ed.InsertAtom(r, "D", geom::Vec3(-5,-5, 5), "C");
+    af=ed.InsertAtom(r, "E", geom::Vec3(5,-5, 5), "C");
+    ag=ed.InsertAtom(r, "F", geom::Vec3(5,-5,-5), "C");
+    ah=ed.InsertAtom(r, "G", geom::Vec3(5, 5,-5), "C");
+    ai=ed.InsertAtom(r, "H", geom::Vec3(5, 5, 5), "C");
 
 
     BondHandle b1=ed.Connect(ab, ad);
@@ -87,7 +84,7 @@ BOOST_AUTO_TEST_CASE(superposition_svd)
 {
   Fixture f1, f2;
   EntityView ev1 = f1.e.CreateFullView();
-  XCSEditor ed=f1.e.RequestXCSEditor();
+  XCSEditor ed=f1.e.EditXCS();
   EntityView ev2 = f2.e.CreateFullView();
   ChainHandle ch1=f1.e.GetChainList()[0];
   ResidueHandleIter rit=ch1.ResiduesBegin();
diff --git a/modules/mol/base/doc/editors.rst b/modules/mol/base/doc/editors.rst
index f224b2e1fd2290db8be073dda9d18fc36bf052db..ca9856360f16c1261181695da9e2af5ddc51d7c1 100644
--- a/modules/mol/base/doc/editors.rst
+++ b/modules/mol/base/doc/editors.rst
@@ -28,9 +28,11 @@ zero, the dependent infomation is updated.
 
 In Python, one can not rely on the destructors being called. It is adviced to 
 always put a call to :meth:`XCSEditor.UpdateICS` or 
-:meth:`ICSEditor.UpdateXCS` when the editing is finished. Alternatively, starting from Python version 2.6, one can use the 
-`with <http://docs.python.org/reference/compound_stmts.html#with>`_  statement
-to make sure the destructor are called and the dependent information is updated.
+:meth:`ICSEditor.UpdateXCS` when the editing is finished. Alternatively, 
+starting from Python version 2.6, one can use the \
+`with <http://docs.python.org/reference/compound_stmts.html#with>`_  
+statement to make sure the destructor are called and the dependent information 
+is updated.
 
 
 Basic Editing Operations
@@ -64,10 +66,14 @@ The basic functionality of editors is implemented in the EditorBase class.
      :type  residue_name: string
      :returns:     :class:`ResidueHandle`
   
-  .. method:: InsertAtom(residue, atom_name, pos, [prop=mol.AtomProp()])
+  .. method:: InsertAtom(residue, atom_name, pos, element="", occupancy=1.0, b_factor=0.0, is_hetatm=False)
   
     Insert new atom and add it to residue. For atoms with alternative atom
-    locations use :meth:`InsertAltAtom`.
+    locations use :meth:`InsertAltAtom`. If the element parameter is a valid 
+    element, the atom properties mass, charge, and radius are set to default 
+    values for that element. If element is an empty string (or an invalid 
+    element), the properties are set to rather meaningless default values. You 
+    may later set any of the properties manually.
     
     :param residue:   is the parent residue and must be valid
     :type residue:    :class:`ResidueHandle`
@@ -79,10 +85,18 @@ The basic functionality of editors is implemented in the EditorBase class.
     :type atom_name:  string
     :param pos:       is the position of the atom in global coordinates
     :type pos:        :class:`geom.Vec3`
-    :param prop:      are the atom's properties such as element, van der Waals 
-                      radius charge and so on. The default set of atom
-                      properties is rather meaningless.
-    :type prop:       class:`AtomProp`
+    :param element:   is the atom's element. If set to a a valid element,
+                      atom properties such as mass, charge, radius are set 
+                      based on default values for that element. If the element 
+                      string is empty, or unknown, the properties are filled 
+                      with rather meaningless default values.
+    :type element:    class:`string`
+    :param occupancy: The occupancy of the atom. between 0 and 1
+    :type occupancy:  float
+    :param b_factor:  temperature factor.
+    :type  b_factor:  float
+    :param is_hetatm: whether the atom is an atom coming from a HETATM record.
+    :type is_hetatm:  bool
     :returns:         :class:`AtomHandle`
 
 Editor for the External Coordinate System
diff --git a/modules/mol/base/doc/entity.rst b/modules/mol/base/doc/entity.rst
index e6bebee7c94e7f83b8fba0c83685cc930e039002..79df5fcf21f9bf6e9daf647b9177204124dc73cc 100644
--- a/modules/mol/base/doc/entity.rst
+++ b/modules/mol/base/doc/entity.rst
@@ -143,7 +143,7 @@ The Handle Classes
     
     See :attr:`atoms`
     
-  .. method:: RequestXCSEditor([edit_mode=mol.EditMode.BUFFERED_EDIT])
+  .. method:: EditXCS([edit_mode=mol.EditMode.BUFFERED_EDIT])
     
     Request :class:`XCSEditor` for editing the external coordinate system. This
     call will fail when there are pending changes of the internal coordinate
@@ -156,7 +156,7 @@ The Handle Classes
     
     :returns: :class:`XCSEditor`
     
-  .. method:: RequestICSEditor([edit_mode=mol.EditMode.BUFFERED_EDIT])
+  .. method:: EditICS([edit_mode=mol.EditMode.BUFFERED_EDIT])
     
     Request :class:`ICSEditor` for editing the internal coordinate system, such
     as torsions, bond lengths and angle between two bonds. This call will fail
@@ -500,7 +500,14 @@ The Handle Classes
   .. attribute:: sec_structure
   
     The secondary structure of the residue.
-    
+  
+  .. attribute:: is_ligand
+  
+    Whether the residue is a ligand. When loading PDB structures, this property 
+    is set based on the HET records. This also means, that this property will 
+    most likely not be set properly for all except PDB files coming from 
+    pdb.org.
+
   .. method:: FindAtom(atom_name)
 
     Get atom by atom name. See also :attr:`atoms`
@@ -584,25 +591,32 @@ The Handle Classes
   .. attribute:: radius
   
     The van-der-Waals radius of the atom. Also available as :meth:`GetRadius`. 
-    Read-only.
+    Read/write.
     
     :type: float
   
   .. attribute:: occupancy
   
-    The atom's occupancy in the range 0 to 1. Also available as 
-    :meth:`GetOccupancy`. Read-only.
-    
+    The atom's occupancy in the range 0 to 1. Read/write. Also available as 
+    meth:`GetOccupancy`, :meth:`SetOccupancy`.
     :type: float
+    
+  .. attribute:: b_factor
+  
+    The atom's temperature factor. Read/write. Also available as 
+    :meth:`GetBFactor`, :meth:`SetBFactor`.
+    
+    :type: float    
+
   .. attribute:: charge
     
-    The atom's charge
+    The atom's charge. Also available as :meth:`GetCharge`, :meth:`SetCharge`.
     
     :type: float
 
   .. attribute:: residue
   
-    The residue this atom belongs to.
+    The residue this atom belongs to. Read-only.
     
     :type: :class:`ResidueHandle`
   
@@ -627,11 +641,7 @@ The Handle Classes
     :type  other_atom: :class:`AtomHandle`
     :rtype: :class:`BondHandle`
 
-  .. method:: GetAtomProps()
-    
-    Get atom properties such as mass, charge, element and occupancy.
-    
-    :rtype: :class:`AtomProp`
+
 
   .. method:: GetBondCount()
     
diff --git a/modules/mol/base/doc/query.rst b/modules/mol/base/doc/query.rst
index 156a91b065fa6ea08effb64767b0afdf970b4a9a..e47085dcb510579045ab6b25b8b9d6fee15419c3 100644
--- a/modules/mol/base/doc/query.rst
+++ b/modules/mol/base/doc/query.rst
@@ -18,7 +18,7 @@ selections in a convenient way. Selections are carried out mainly by calling the
 
   arginines=model.Select('rname=ARG')
 
-A simple selection query (called a predicate) consists in a property (here, 
+A simple selection query (called a predicate) consists of a property (here,
 `rname`), a comparison operator (here, `=`) and an argument (here, `ARG`).  The 
 return value of a call to the :meth:`EntityHandle.Select` method is always an 
 :class:`EntityView`. The :class:`EntityView` always contains a full hierarchy of 
@@ -197,6 +197,10 @@ index is the same for views and handles.
 
 **rbfac** (float): average B (temperature) factor of residue
 
+**ligand** (bool) Whether the residue is a ligand. For official PDB files, the ligand property is set based on HET records.
+
+**water** (bool) Whether the residue is water.
+
 Properties of Atoms
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
diff --git a/modules/mol/base/pymod/__init__.py b/modules/mol/base/pymod/__init__.py
index 6431ae0ce891d8e3b8fdbc2dd1ff42c60e90d046..a473f7ae467faff11c759f9f48627018cf665d8a 100644
--- a/modules/mol/base/pymod/__init__.py
+++ b/modules/mol/base/pymod/__init__.py
@@ -18,4 +18,18 @@
 #------------------------------------------------------------------------------
 from _mol import *
 import ost.geom as _geom
-from ost.mol import alg
\ No newline at end of file
+from ost.mol import alg
+
+
+def MergeCoordGroups(*coord_groups):
+  """
+  Merge several separate coord groups into one. The coord groups must have the 
+  same number of atoms. In case no coord group is supplied, None will be 
+  returned.
+  """
+  if len(coord_groups)==0:
+    return None
+  cg=CreateCoordGroup(coord_groups[0].atoms)
+  for coord_group in coord_groups:
+    cg.AddFrames(coord_group)
+  return cg
\ No newline at end of file
diff --git a/modules/mol/base/pymod/export_atom.cc b/modules/mol/base/pymod/export_atom.cc
index 13fc2ee554980d1941bb074db842f2364653bac4..67fc5a16348faba02eafaac26b272138e14da5ae 100644
--- a/modules/mol/base/pymod/export_atom.cc
+++ b/modules/mol/base/pymod/export_atom.cc
@@ -40,15 +40,8 @@ void export_Atom()
          return_value_policy<copy_const_reference>())
     .def("GetQualifiedName", &AtomBase::GetQualifiedName)
     .add_property("qualified_name", &AtomBase::GetQualifiedName)
-    .def("IsValid", &AtomBase::IsValid)
     .def(self_ns::str(self))
-    .def("GetAtomProps", &AtomBase::GetAtomProps,
-         return_value_policy<copy_const_reference>())
-    .def("SetAtomProps", &AtomBase::SetAtomProps, args("prop"))
     .def("GetIndex", &AtomBase::GetIndex)
-    .add_property("prop",
-                  make_function(&AtomBase::GetAtomProps,
-                                return_value_policy<copy_const_reference>()))
     .add_property("pos",
                   make_function(&AtomBase::GetPos,
                                 return_value_policy<copy_const_reference>()))
@@ -56,20 +49,33 @@ void export_Atom()
                   make_function(&AtomBase::GetName,
                                 return_value_policy<copy_const_reference>()),
                   &AtomBase::SetName)
-    .add_property("index",&AtomBase::GetIndex)
+    .add_property("index", &AtomBase::GetIndex)
     
     .def("GetRadius", &AtomBase::GetRadius)
     .def("GetElement", &AtomBase::GetElement, 
          return_value_policy<copy_const_reference>())
+    .def("SetElement", &AtomBase::SetElement)
     .def("GetCharge", &AtomBase::GetCharge)
+    .def("GetBFactor", &AtomBase::GetBFactor)
+    .def("SetBFactor", &AtomBase::SetBFactor)
+    .def("SetOccupancy", &AtomBase::SetOccupancy)
+    .def("GetOccupancy", &AtomBase::GetOccupancy)
     .def("GetMass", &AtomBase::GetMass)
-    .def("IsHetAtom", &AtomBase::IsHetAtom)    
-    .add_property("radius", &AtomBase::GetRadius)
+    .def("IsHetAtom", &AtomBase::IsHetAtom)
+    .def("SetMass", &AtomBase::SetMass)
+    .add_property("b_factor", &AtomBase::GetBFactor, &AtomBase::SetBFactor)
+    .add_property("occupancy", &AtomBase::GetOccupancy, 
+                  &AtomBase::SetOccupancy)
+    .def("SetCharge", &AtomBase::SetCharge)
+    .add_property("radius", &AtomBase::GetRadius, &AtomBase::SetRadius)
     .add_property("element", make_function(&AtomBase::GetElement, 
-                  return_value_policy<copy_const_reference>()))
-    .add_property("is_hetatom", &AtomBase::IsHetAtom)
-    .add_property("charge", &AtomBase::GetCharge)
-    .add_property("mass", &AtomBase::GetMass)
+                  return_value_policy<copy_const_reference>()),
+                  &AtomBase::SetElement)
+    .add_property("is_hetatom", &AtomBase::IsHetAtom, &AtomBase::SetHetAtom)
+    .add_property("charge", &AtomBase::GetCharge, &AtomBase::SetCharge)
+    .add_property("mass", &AtomBase::GetMass, &AtomBase::SetMass)
+    .add_property("valid", &AtomBase::IsValid)
+    .def("IsValid", &AtomBase::IsValid)
   ;
   generic_prop_def<AtomBase>(atom_base);
 
@@ -78,7 +84,6 @@ void export_Atom()
     .add_property("residue",&AtomHandle::GetResidue)
     .def("GetBondList", &AtomHandle::GetBondList)
     .def("GetBondCount", &AtomHandle::GetBondCount)
-    .add_property("valid", &AtomHandle::IsValid)    
     .def("GetEntity", &AtomHandle::GetEntity)
     .def("GetHandle", &AtomHandle::GetHandle)
     .add_property("handle", &AtomHandle::GetHandle)
@@ -96,15 +101,5 @@ void export_Atom()
     .def(vector_indexing_suite<AtomHandleList>())
     .def(ost::VectorAdditions<AtomHandleList>())
   ;
-  class_<AtomProp>("AtomProp", init<>())
-    .def_readwrite("element", &AtomProp::element)
-    .def_readwrite("radius", &AtomProp::radius)
-    .def_readwrite("charge", &AtomProp::charge)
-    .def_readwrite("mass", &AtomProp::mass)
-    .def_readwrite("occupancy", &AtomProp::occupancy)
-    .def_readwrite("b_factor", &AtomProp::b_factor)
-    .def_readwrite("is_hetatm", &AtomProp::is_hetatm)
-    .def_readwrite("anisou", &AtomProp::anisou)
-  ;
 }
 
diff --git a/modules/mol/base/pymod/export_atom_view.cc b/modules/mol/base/pymod/export_atom_view.cc
index d8bc4a0eeb9e4aaf72a7d083d2b03d3e375767f2..c33156370b0ce52fea3682d703d697c68341d2c0 100644
--- a/modules/mol/base/pymod/export_atom_view.cc
+++ b/modules/mol/base/pymod/export_atom_view.cc
@@ -41,6 +41,7 @@ void export_AtomView()
     .add_property("valid", &AtomView::IsValid)    
     .def("GetBondList", &AtomView::GetBondList)
     .def("GetHashCode", &AtomView::GetHashCode)
+    .def("IsValid", &AtomView::IsValid)
     .def("__hash__", &AtomView::GetHashCode)
     .add_property("hash_code", &AtomView::GetHashCode)
     .def("GetBondPartners", &AtomView::GetBondPartners)
diff --git a/modules/mol/base/pymod/export_chain.cc b/modules/mol/base/pymod/export_chain.cc
index ad473535b85d64e00e3a37bb32e08acaada3443c..b21d5eb97a0a077fb590e8b1c121676042ff7566 100644
--- a/modules/mol/base/pymod/export_chain.cc
+++ b/modules/mol/base/pymod/export_chain.cc
@@ -47,8 +47,9 @@ void export_Chain()
   chain_base
     .def("GetName", &ChainBase::GetName)
     .add_property("name", &ChainBase::GetName)
-    .def("IsValid", &ChainBase::IsValid)    
     .def(self_ns::str(self))
+    .add_property("valid", &ChainBase::IsValid)
+    .def("IsValid", &ChainBase::IsValid)
   ;
   generic_prop_def<ChainBase>(chain_base);
   class_<ChainHandle, bases<ChainBase> >("ChainHandle", init<>())
@@ -90,7 +91,6 @@ void export_Chain()
     .add_property("center_of_mass", &ChainHandle::GetCenterOfMass)
     .add_property("center_of_atoms", &ChainHandle::GetCenterOfAtoms)  
     .add_property("in_sequence", &ChainHandle::InSequence)  
-    .add_property("valid", &ChainHandle::IsValid)    
     .def("GetBounds", &ChainHandle::GetBounds)
     .add_property("bounds", &ChainHandle::GetBounds)
     .def("GetGeometricStart", geom_start<ChainHandle>)
diff --git a/modules/mol/base/pymod/export_chain_view.cc b/modules/mol/base/pymod/export_chain_view.cc
index 117e4ce837fba5e8111d1ff0ebf473559b1340f9..3835eed753bc498a319dbedf2408f5af7054d475 100644
--- a/modules/mol/base/pymod/export_chain_view.cc
+++ b/modules/mol/base/pymod/export_chain_view.cc
@@ -98,7 +98,8 @@ void export_ChainView()
     .add_property("mass", &ChainView::GetMass)
     .add_property("center_of_mass", &ChainView::GetCenterOfMass)
     .add_property("center_of_atoms", &ChainView::GetCenterOfAtoms)
-    .add_property("valid", &ChainView::IsValid)      
+    .add_property("valid", &ChainView::IsValid)   
+    .def("IsValid", &ChainView::IsValid)
     .add_property("in_sequence", &ChainView::InSequence)    
     .def("GetGeometricStart", geom_start<ChainView>)
     .def("GetGeometricEnd", geom_end<ChainView>)
diff --git a/modules/mol/base/pymod/export_coord_group.cc b/modules/mol/base/pymod/export_coord_group.cc
index 5589268afbb64498a74255cc797cda97f4d7bfdf..bed54377ec626890bae0de10ec69ae032ecf64e5 100644
--- a/modules/mol/base/pymod/export_coord_group.cc
+++ b/modules/mol/base/pymod/export_coord_group.cc
@@ -46,11 +46,13 @@ void export_CoordGroup()
     .def("IsValid",&CoordGroupHandle::IsValid)
     .def("GetEntity",&CoordGroupHandle::GetEntity)
     .def("GetAtomCount",&CoordGroupHandle::GetAtomCount)
+    .def("AddFrames", &CoordGroupHandle::AddFrames)
     .def("GetFrameCount",&CoordGroupHandle::GetFrameCount)
     .def("SetFramePositions",&CoordGroupHandle::SetFramePositions)
     .def("SetAtomPos",&CoordGroupHandle::SetAtomPos)
     .def("GetAtomPos",&CoordGroupHandle::GetAtomPos)
     .def("CopyFrame",&CoordGroupHandle::CopyFrame)
+    .add_property("atoms", &CoordGroupHandle::GetAtomList)
     .def("IsValid", &CoordGroupHandle::IsValid)
     .def("Capture", capture1)
     .def("Capture", capture2)
diff --git a/modules/mol/base/pymod/export_editors.cc b/modules/mol/base/pymod/export_editors.cc
index d7645c0bbdfa04087986e068d707a784f77a900a..4b8d4123e175070007ee6c49b2429deefcd3dd44 100644
--- a/modules/mol/base/pymod/export_editors.cc
+++ b/modules/mol/base/pymod/export_editors.cc
@@ -54,21 +54,15 @@ void (ICSEditor::*rotate_torsion_b)(const AtomHandle&, const AtomHandle&,
                                     const AtomHandle&, const AtomHandle&,
                                     Real)=&ICSEditor::RotateTorsionAngle;
                                  
-BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_insert_atom_overloads, 
-                                       EditorBase::InsertAtom, 3, 4)
 }
 
 void export_Editors()
-{
-  enum_<EditMode>("EditMode")
-    .value("BUFFERED_EDIT", BUFFERED_EDIT)
-    .value("UNBUFFERED_EDIT", UNBUFFERED_EDIT)
-  ;
-  
+{  
   class_<EditorBase>("EditorBase", no_init)
     .def("InsertChain", &EditorBase::InsertChain)
     .def("InsertAtom", &EditorBase::InsertAtom,
-         X_insert_atom_overloads())
+         (arg("residue"), arg("name"), arg("pos"), arg("element")="", 
+          arg("occupancy")=1.0, arg("b_factor")=0.0, arg("is_hetatm")=false))
     .def("InsertAltAtom", &EditorBase::InsertAltAtom)
     .def("DeleteResidue", &EditorBase::DeleteResidue)
     .def("DeleteChain", &EditorBase::DeleteChain)
@@ -83,6 +77,8 @@ void export_Editors()
     .def("Connect", connect_d)    
     .def("RenameChain", &EditorBase::RenameChain)
     .def("AddTorsion", &EditorBase::AddTorsion)
+    .def("ReorderResidues",&EditorBase::ReorderResidues)
+    .def("ReorderAllResidues",&EditorBase::ReorderAllResidues)
   ;
   
   class_<XCSEditor, bases<EditorBase> >("XCSEditor", no_init)
diff --git a/modules/mol/base/pymod/export_entity.cc b/modules/mol/base/pymod/export_entity.cc
index b0df16c0c9065f8084127b48a1055cd29090d849..3f3858ed0511b5e77c54c2293622e602ce593035 100644
--- a/modules/mol/base/pymod/export_entity.cc
+++ b/modules/mol/base/pymod/export_entity.cc
@@ -49,11 +49,20 @@ StringMethod select_string=&EntityHandle::Select;
 
 Real (EntityHandle::*get_angle1)(const AtomHandle&, const AtomHandle&, const AtomHandle&) const = &EntityHandle::GetAngle;
 Real (EntityHandle::*get_angle2)(const AtomView&, const AtomView&, const AtomView&) const = &EntityHandle::GetAngle;
+                                      
+XCSEditor depr_request_xcs_editor(EntityHandle e, EditMode m)
+{
+  WARN_DEPRECATED("EntityHandle::RequestXCSEditor is deprecated. Use "
+                  "EntityHandle::EditXCS instead");
+  return e.EditXCS(m);
+}
 
-BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_xcs_editor_overloads, 
-                                      EntityHandle::RequestXCSEditor, 0, 1)
-BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_ics_editor_overloads, 
-                                      EntityHandle::RequestICSEditor, 0, 1)                                      
+ICSEditor depr_request_ics_editor(EntityHandle e, EditMode m)
+{
+  WARN_DEPRECATED("EntityHandle::RequestICSEditor is deprecated. Use "
+                  "EntityHandle::EditICS instead");
+  return e.EditICS(m);
+}
 
 
 }
@@ -62,11 +71,12 @@ void export_Entity()
 {
   class_<EntityBase> ent_base("EntityBase", no_init);
   ent_base
-    .def("IsValid", &EntityBase::IsValid)
     .def(self_ns::str(self))
     .def("GetName", &EntityBase::GetName,
         return_value_policy<copy_const_reference>())
     .def("SetName", &EntityBase::SetName)
+    .def("IsValid", &EntityBase::IsValid)
+    .add_property("valid", &EntityBase::IsValid)
   ;
   generic_prop_def<EntityBase>(ent_base);
   
@@ -84,6 +94,7 @@ void export_Entity()
     .def("GetCenterOfAtoms", &EntityHandle::GetCenterOfAtoms)
     .def("GetGeometricCenter", geom_center<EntityHandle>)
     .add_property("geometric_center", geom_center<EntityHandle>)
+
     .add_property("geometric_end", geom_end<EntityHandle>)
     .add_property("geometric_start", geom_start<EntityHandle>)
     .def("GetGeometricStart", geom_start<EntityHandle>)
@@ -113,7 +124,6 @@ void export_Entity()
     .add_property("atoms", &EntityHandle::GetAtomList)
     .add_property("chains", &EntityHandle::GetChainList)
     .add_property("bonds", &EntityHandle::GetBondList)
-    .add_property("valid", &EntityHandle::IsValid)
     .def("GetBounds", &EntityHandle::GetBounds)
     .add_property("bounds", &EntityHandle::GetBounds)
     .def("GetTransformationMatrix", &EntityHandle::GetTransformationMatrix,
@@ -121,10 +131,11 @@ void export_Entity()
     .add_property("transform", 
                    make_function(&EntityHandle::GetTransformationMatrix, 
                                  return_value_policy<copy_const_reference>()))    
-    .def("RequestICSEditor", &EntityHandle::RequestICSEditor,
-         X_ics_editor_overloads(args("mode")))
-    .def("RequestXCSEditor", &EntityHandle::RequestXCSEditor,
-         X_xcs_editor_overloads(args("mode")))
+
+    .def("EditXCS", &EntityHandle::EditXCS, arg("mode")=UNBUFFERED_EDIT)
+    .def("EditICS", &EntityHandle::EditICS, arg("mode")=UNBUFFERED_EDIT)
+    .def("RequestXCSEditor", &depr_request_xcs_editor, arg("mode")=UNBUFFERED_EDIT)
+    .def("RequestICSEditor", &depr_request_ics_editor, arg("mode")=UNBUFFERED_EDIT)  
     .def("IsTransformationIdentity",&EntityHandle::IsTransformationIdentity)
     .def(self==self)
     .def(self!=self)
diff --git a/modules/mol/base/pymod/export_entity_view.cc b/modules/mol/base/pymod/export_entity_view.cc
index 4eadd54cdcb121c0507ffd2a4f0bdfb06f43f6d3..422eb77d146adf30561ec0ed51202f005203c1eb 100644
--- a/modules/mol/base/pymod/export_entity_view.cc
+++ b/modules/mol/base/pymod/export_entity_view.cc
@@ -111,6 +111,7 @@ void export_EntityView()
     .def("RemoveResidue", &EntityView::RemoveResidue)
     .def("RemoveAtom", &EntityView::RemoveAtom)
     .def("CreateEmptyView", &EntityView::CreateEmptyView)
+    .def("IsValid", &EntityView::IsValid)    
     .def("CreateFullView", &EntityView::CreateFullView)
     .def("AddAllInclusiveBonds", &EntityView::AddAllInclusiveBonds)
     .add_property("chain_count", &EntityView::GetChainCount)
diff --git a/modules/mol/base/pymod/export_residue.cc b/modules/mol/base/pymod/export_residue.cc
index ef844831cb222c399cf5a4405803be9224c2c48e..4679840eec1ffb033ffe20294abf19335a7cb986 100644
--- a/modules/mol/base/pymod/export_residue.cc
+++ b/modules/mol/base/pymod/export_residue.cc
@@ -101,7 +101,6 @@ void export_Residue()
     .def("GetPhiTorsion", &ResidueBase::GetPhiTorsion)
     .def("GetPsiTorsion", &ResidueBase::GetPsiTorsion)
     .def("GetOmegaTorsion", &ResidueBase::GetOmegaTorsion)
-    .def("IsValid", &ResidueBase::IsValid)
     .def(self_ns::str(self))
     .def("GetOneLetterCode", &ResidueBase::GetOneLetterCode)
     .def("SetOneLetterCode", &ResidueBase::SetOneLetterCode)
@@ -120,6 +119,9 @@ void export_Residue()
     .def("GetChemClass", &ResidueBase::GetChemClass)
     .def("SetChemClass", set_chemclass1)
     .def("SetChemClass", set_chemclass2)
+    .add_property("is_ligand", &ResidueBase::IsLigand, &ResidueBase::SetIsLigand)
+    .def("IsLigand", &ResidueBase::IsLigand)
+    .def("SetIsLigand", &ResidueBase::SetIsLigand)
     .add_property("number",
                    make_function(&ResidueBase::GetNumber,
                                  return_value_policy<copy_const_reference>()))
@@ -132,6 +134,8 @@ void export_Residue()
                    make_function(&ResidueBase::GetName,
                                  return_value_policy<copy_const_reference>()))
     .add_property("qualified_name", &ResidueBase::GetQualifiedName)
+    .def("IsValid", &ResidueBase::IsValid)
+    .add_property("valid", &ResidueBase::IsValid) 
   ;
   generic_prop_def<ResidueBase>(residue_base);
 
@@ -161,7 +165,7 @@ void export_Residue()
     .add_property("atom_count", &ResidueHandle::GetAtomCount)
     .add_property("index", &ResidueHandle::GetIndex)
     .def("Select", select_string, arg("flags")=0)
-    .def("Select", select_query, arg("flags")=0)
+    .def("Select", select_query, arg("flags")=0)    
     .def("GetMass", &ResidueHandle::GetMass)
     .def("GetCenterOfMass", &ResidueHandle::GetCenterOfMass)
     .def("GetCenterOfAtoms", &ResidueHandle::GetCenterOfAtoms)
@@ -173,7 +177,6 @@ void export_Residue()
     .add_property("phi_torsion", &ResidueHandle::GetPhiTorsion)
     .add_property("psi_torsion", &ResidueHandle::GetPsiTorsion)
     .add_property("omega_torsion", &ResidueHandle::GetOmegaTorsion)
-    .add_property("valid", &ResidueHandle::IsValid) 
     .def("GetGeometricStart", geom_start<ResidueHandle>)
     .def("GetGeometricEnd", geom_end<ResidueHandle>)
     .def(self==self)
diff --git a/modules/mol/base/pymod/export_residue_view.cc b/modules/mol/base/pymod/export_residue_view.cc
index f8dbd089628879641e24731629afe92a108e4403..81b66c1452871726670b039afb3d364bbe5bddfc 100644
--- a/modules/mol/base/pymod/export_residue_view.cc
+++ b/modules/mol/base/pymod/export_residue_view.cc
@@ -70,6 +70,7 @@ void export_ResidueView()
     .add_property("entity", &ResidueView::GetEntity)
     .add_property("index", &ResidueView::GetIndex)
     .def("RemoveAtoms", &ResidueView::RemoveAtom)
+    .def("IsValid", &ResidueView::IsValid)
     .add_property("handle", &ResidueView::GetHandle)
     .def("GetHandle", &ResidueView::GetHandle)
     .def("Select", select_string, arg("flags")=0)
diff --git a/modules/mol/base/pymod/export_surface.cc b/modules/mol/base/pymod/export_surface.cc
index 04d089dfc41442f1a529816655f016a553af33c9..07ff89d1b3641f145d9b584641c90d4dbadbecc8 100644
--- a/modules/mol/base/pymod/export_surface.cc
+++ b/modules/mol/base/pymod/export_surface.cc
@@ -20,12 +20,13 @@
 #include <boost/python/suite/indexing/vector_indexing_suite.hpp>
 using namespace boost::python;
 
-
 #include <ost/mol/surface_handle.hh>
 #include <ost/mol/surface_builder.hh>
 #include <ost/mol/entity_handle.hh>
 #include <ost/mol/impl/surface_impl.hh>
 
+#include <ost/export_helper/vector.hh>
+
 using namespace ost;
 using namespace ost::mol;
 
@@ -47,13 +48,13 @@ void export_Surface()
     .def_readwrite("Position", &SurfaceVertex::position)
     .def_readwrite("Normal", &SurfaceVertex::normal)
     .def_readwrite("Atom", &SurfaceVertex::atom)   
-  ;     
+  ;
   class_<SurfaceTriIDList>("SurfaceTriIDList", init<>())
     .def(vector_indexing_suite<SurfaceTriIDList>())
   ;
   class_<SurfaceVertexList>("SurfaceVertexList", init<>())
     .def(vector_indexing_suite<SurfaceVertexList>())
-  ;  
+  ;
   class_<SurfaceHandle>("SurfaceHandle", no_init)
     .def("Attach",attach1)
     .def("Attach",attach2)
@@ -65,6 +66,11 @@ void export_Surface()
     .def("IsValid",&SurfaceHandle::IsValid)
   ;
 
+  class_<SurfaceHandleList>("SurfaceHandleList", init<>())
+    .def(vector_indexing_suite<SurfaceHandleList>())
+    .def(ost::VectorAdditions<SurfaceHandleList>())
+  ;
+
   def("CreateSurface",create1);
 
   def("BuildSurface",BuildSurface);
diff --git a/modules/mol/base/pymod/wrap_mol.cc b/modules/mol/base/pymod/wrap_mol.cc
index ce55b9942f8f5fd378ce11c78b924b6b5691a44d..a388d478655cef5d68f6675e81cb4f5af12926b3 100644
--- a/modules/mol/base/pymod/wrap_mol.cc
+++ b/modules/mol/base/pymod/wrap_mol.cc
@@ -18,6 +18,7 @@
 //------------------------------------------------------------------------------
 #include <boost/python.hpp>
 #include <ost/mol/transform.hh>
+#include <ost/mol/editor_base.hh>
 #include <ost/info/info.hh>
 
 using namespace boost::python;
@@ -44,6 +45,11 @@ void export_QueryViewWrapper();
 void export_EntityPropertyMapper();
 BOOST_PYTHON_MODULE(_mol)
 {
+  enum_<EditMode>("EditMode")
+    .value("BUFFERED_EDIT", BUFFERED_EDIT)
+    .value("UNBUFFERED_EDIT", UNBUFFERED_EDIT)
+    .export_values()
+  ;
   export_Entity();
   export_Surface();
   export_Query();
@@ -64,14 +70,20 @@ BOOST_PYTHON_MODULE(_mol)
   export_QueryViewWrapper();
   export_EntityPropertyMapper();
   class_<Transform>("Transform", init<>())
+    .def(init<const Transform&>()) // shouldn't this be there automatically ?
     .def("GetMatrix",&Transform::GetMatrix)
+	.add_property("matrix",&Transform::GetMatrix)
     .def("GetTransposedMatrix",&Transform::GetTransposedMatrix)
+ 	.add_property("tmatrix",&Transform::GetTransposedMatrix)
     .def("SetTrans",&Transform::SetTrans)
     .def("GetTrans",&Transform::GetTrans)
+	.add_property("trans",&Transform::GetTrans,&Transform::SetTrans)
     .def("SetCenter",&Transform::SetCenter)
     .def("GetCenter",&Transform::GetCenter)
+	.add_property("center",&Transform::GetCenter,&Transform::SetCenter)
     .def("SetRot",&Transform::SetRot)
     .def("GetRot",&Transform::GetRot)
+	.add_property("rot",&Transform::GetRot,&Transform::SetRot)
     .def("ApplyXAxisRotation",&Transform::ApplyXAxisRotation)
     .def("ApplyYAxisRotation",&Transform::ApplyYAxisRotation)
     .def("ApplyZAxisRotation",&Transform::ApplyZAxisRotation)
diff --git a/modules/mol/base/src/CMakeLists.txt b/modules/mol/base/src/CMakeLists.txt
index 6b2967cc0f97c73fb93a405b7b6680a9b1717618..0a4314041d865a1611eb74c4532a141d15e50248 100644
--- a/modules/mol/base/src/CMakeLists.txt
+++ b/modules/mol/base/src/CMakeLists.txt
@@ -26,7 +26,6 @@ query_error.cc
 query_state.cc
 residue_base.cc
 residue_handle.cc
-residue_prop.cc
 residue_view.cc
 surface_builder.cc
 surface_handle.cc
@@ -42,7 +41,6 @@ xcs_editor.cc)
 set(OST_MOL_HEADERS
 atom_base.hh
 atom_handle.hh
-atom_prop.hh
 atom_view.hh
 bond_handle.hh
 bond_table.hh
diff --git a/modules/mol/base/src/atom_base.cc b/modules/mol/base/src/atom_base.cc
index 2818844b012bb0ac1d8ef0d2f088fb7435128434..ee41fbf1f743933bbe67f0b6d33a2b0acc2fc4dc 100644
--- a/modules/mol/base/src/atom_base.cc
+++ b/modules/mol/base/src/atom_base.cc
@@ -75,19 +75,6 @@ std::vector<String> AtomBase::GetAltGroupNames() const
   return impl_->GetResidue()->GetAltAtomGroupNames(Impl());
 }
 
-
-const AtomProp& AtomBase::GetAtomProps() const 
-{
-  this->CheckValidity();  
-  return impl_->GetAtomProps();
-}
-
-void AtomBase::SetAtomProps(const AtomProp& prop) 
-{
-  this->CheckValidity();  
-  impl_->GetAtomProps()=prop;
-}
-
 impl::AtomImplPtr& AtomBase::Impl() 
 {
   return impl_;
@@ -98,16 +85,6 @@ const impl::AtomImplPtr& AtomBase::Impl() const
   return impl_;
 }
 
-bool AtomBase::IsValid() const 
-{
-  return (impl_.get()!=0);
-}
-
-AtomBase::operator bool() const 
-{
-  return (impl_.get()!=0);
-}
-
 String AtomBase::GetQualifiedName() const 
 {
   this->CheckValidity();
@@ -122,7 +99,7 @@ void AtomBase::CheckValidity() const
 
 std::ostream& operator<<(std::ostream& os, const AtomBase& atom) 
 {
-  if (atom.IsValid()) {
+  if (atom.Impl()) {
     os << atom.GetQualifiedName();
   } else {
     os << "invalid atom";
@@ -134,47 +111,98 @@ std::ostream& operator<<(std::ostream& os, const AtomBase& atom)
 Real AtomBase::GetRadius() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().radius;
+  return Impl()->GetRadius();
 }
 
 
 const String& AtomBase::GetElement() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().element;
+  return Impl()->GetElement();
 }
 
 
 bool AtomBase::IsHetAtom() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().is_hetatm;
+  return Impl()->IsHetAtom();
 }
 
 Real AtomBase::GetBFactor() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().b_factor;
+  return Impl()->GetBFactor();
+}
+void AtomBase::SetElement(const String& element)
+{
+  this->CheckValidity();
+  Impl()->SetElement(element);
+}
+
+void AtomBase::SetBFactor(Real factor)
+{
+  this->CheckValidity();
+  Impl()->SetBFactor(factor);
+}
+
+void AtomBase::SetOccupancy(Real occ)
+{
+  this->CheckValidity();
+  Impl()->SetOccupancy(occ);
 }
 
 Real AtomBase::GetMass() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().mass;
+  return Impl()->GetMass();
 }
 
 Real AtomBase::GetCharge() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().charge;
+  return Impl()->GetCharge();
 }
 
 Real AtomBase::GetOccupancy() const
 {
   this->CheckValidity();
-  return Impl()->GetAtomProps().occupancy;
+  return Impl()->GetOccupancy();
+}
+
+void AtomBase::SetCharge(Real charge)
+{
+  this->CheckValidity();
+  Impl()->SetCharge(charge);
+}
+
+void AtomBase::SetRadius(Real radius)
+{
+  this->CheckValidity();
+  Impl()->SetRadius(radius);
+}
+
+const geom::Mat3& AtomBase::GetAnisou() const
+{
+  this->CheckValidity();
+  return Impl()->GetAnisou();
+}
+
+void AtomBase::SetAnisou(const geom::Mat3& anisou)
+{
+  this->CheckValidity();
+  Impl()->SetAnisou(anisou);
 }
 
+void AtomBase::SetMass(Real mass)
+{
+  this->CheckValidity();
+  Impl()->SetMass(mass);
+}
+void AtomBase::SetHetAtom(bool het)
+{
+  this->CheckValidity();
+  Impl()->SetHetAtom(het);
+}
 
 String AtomBase::GetStringProperty(Prop::ID prop_id) const
 {
diff --git a/modules/mol/base/src/atom_base.hh b/modules/mol/base/src/atom_base.hh
index 9777aea714732f090c4b2def487086e4031ad26f..a6ddaa7cdae5303b25845ce5fc082f31f75175ab 100644
--- a/modules/mol/base/src/atom_base.hh
+++ b/modules/mol/base/src/atom_base.hh
@@ -48,7 +48,20 @@ class DLLEXPORT_OST_MOL AtomBase: public GenericPropContainer<AtomBase> {
 public:
   AtomBase();
   AtomBase(const impl::AtomImplPtr& impl);
-public:  
+public:
+  /// \name Handle validity
+  //@{
+  /// \brief check validity of handle
+  /// 
+  /// check, whether the bond handle points to a valid atom.
+  /// \note It is an error to use any method other than #IsValid, Impl and 
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return Impl().get()!=0; }
+  //@}
   friend class ConstGenericPropContainer<AtomBase>;  
   ///\brief Get atom name. 
   ///
@@ -75,32 +88,9 @@ public:
   geom::Vec3 GetAltPos(const String& alt_group) const;
   
   std::vector<String> GetAltGroupNames() const;
-    /// \name Atom properties
-  //@{
-  /// \brief Get atom properties such as element name, radius crystallographic
-  ///     occupancy and temperature factors.
-  ///
-  /// \sa      #SetAtomProps
-  const AtomProp& GetAtomProps() const;
-    
-  /// \brief  Set atom properties.
-  void SetAtomProps(const AtomProp& prop);
+
   //@} 
-  
-  /// \name Handle validity
-  //@{
-  /// \brief check validity of handle
-  /// 
-  /// check, whether the bond handle points to a valid atom.
-  /// \note It is an error to use any method other than #IsValid, Impl and 
-  ///       #operator bool() when the handle is invalid. An InvalidHandle
-  ///       exception will be thrown.
-  operator bool() const;
-  /// \brief check validity of handle
-  /// \sa #operator bool()
-  bool IsValid() const;
-  //@}
-  
+    
   /// \brief Get qualified name for atom.
   /// 
   /// The qualified name consists of the atom name as well as a unique residue
@@ -134,6 +124,24 @@ public:
   /// The returned value may be zero for some structures
   Real GetBFactor() const;
   
+  
+  void SetBFactor(Real factor);
+  
+  void SetOccupancy(Real occ);
+  
+  
+  void SetCharge(Real charge);
+  
+  void SetMass(Real mass);
+  
+  void SetHetAtom(bool het);
+  
+  void SetRadius(Real radius);
+  
+  
+  const geom::Mat3& GetAnisou() const;
+  
+  void SetAnisou(const geom::Mat3& anisou);
   /// \brief get mass of atom
   /// 
   /// The returned value may be zero
@@ -153,6 +161,8 @@ public:
   /// \brief get atom implementation
   impl::AtomImplPtr& Impl();
 
+
+  void SetElement(const String& element);
 protected:
   
   GenericPropContainerImpl* GpImpl();
diff --git a/modules/mol/base/src/atom_handle.hh b/modules/mol/base/src/atom_handle.hh
index 6ea9094c0db51dab69bc7c46b8a5913c2402404b..83a1c904682d896f6c849faeeea815335a9eac3b 100644
--- a/modules/mol/base/src/atom_handle.hh
+++ b/modules/mol/base/src/atom_handle.hh
@@ -40,6 +40,7 @@ public:
   AtomHandle(const impl::AtomImplPtr& impl);
 
 public:  
+
   ResidueHandle GetResidue() const;
   
   EntityHandle GetEntity() const;  
diff --git a/modules/mol/base/src/atom_view.cc b/modules/mol/base/src/atom_view.cc
index 5811a2d5567ea3db1de2ebe8eede8fb4c9a7c631..20c14afbe42d93971aa84478f04db9c2199e065c 100644
--- a/modules/mol/base/src/atom_view.cc
+++ b/modules/mol/base/src/atom_view.cc
@@ -67,7 +67,10 @@ AtomView::AtomView(const ResidueView& residue_view,
 ResidueView AtomView::GetResidue() const 
 {
   this->CheckValidity();
-  return ResidueView(data_->residue.lock(), Impl()->GetResidue());
+  if (!data_->residue.expired()) {
+    return ResidueView(data_->residue.lock(), Impl()->GetResidue());    
+  }
+  throw InvalidHandle();
 }
 
 void AtomView::Apply(EntityVisitor& visitor) 
diff --git a/modules/mol/base/src/atom_view.hh b/modules/mol/base/src/atom_view.hh
index a9e2d9937986b83b3b10d6e547afe2b90c1c6e53..770f415501a2dce93d3e607141fa79ec2aab9722 100644
--- a/modules/mol/base/src/atom_view.hh
+++ b/modules/mol/base/src/atom_view.hh
@@ -35,6 +35,20 @@ class DLLEXPORT_OST_MOL AtomView : public AtomBase {
 
   friend class EntityView;
 public:
+  
+  /// \name View validity
+  //@{
+  /// \brief check validity of view
+  /// 
+  /// check, whether the atom view points to a valid atom.
+  /// \note It is an error to use any method other than #IsValid, Impl and 
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return data_.get()!=0; }
+  //@}
   // constructors  
   AtomView();
   AtomView(const ResidueView& residue_view,
diff --git a/modules/mol/base/src/chain_base.cc b/modules/mol/base/src/chain_base.cc
index aef8bc19a61c5aef1edbbbe0801bedfa138be472..3fd191bb98bb30e27fbf1cbeefe3ca007a9a3c19 100644
--- a/modules/mol/base/src/chain_base.cc
+++ b/modules/mol/base/src/chain_base.cc
@@ -44,14 +44,6 @@ String ChainBase::GetName() const {
   return impl_->GetName();
 }
 
-ChainBase::operator bool() const {
-  return impl_.get()!=0;
-}
-
-bool ChainBase::IsValid() const {
-  return impl_.get()!=0;
-}
-
 void ChainBase::CheckValidity() const {
   if (!impl_)
     throw InvalidHandle();
@@ -59,7 +51,7 @@ void ChainBase::CheckValidity() const {
 
 std::ostream& operator<<(std::ostream& os, const ChainBase& chain) 
 {
-  if (chain.IsValid()) {
+  if (chain.Impl()) {
     os << chain.GetName();
   } else {
     os << "invalid chain";
diff --git a/modules/mol/base/src/chain_base.hh b/modules/mol/base/src/chain_base.hh
index 68e0d4bf84bcaa96046a4bb11de5c4b2d72e97a4..faf7a5c983b7b4e4330cae9b341ee5e6dafadb28 100644
--- a/modules/mol/base/src/chain_base.hh
+++ b/modules/mol/base/src/chain_base.hh
@@ -42,8 +42,7 @@ public: // constructors
   ChainBase();
   ChainBase(const impl::ChainImplPtr& impl);
 public:
-  friend class ConstGenericPropContainer<ChainBase>;
-  String GetName() const;
+  
   /// \name Handle validity
   //@{
   /// \brief check validity of handle
@@ -52,11 +51,13 @@ public:
   /// \note It is an error to use any method other than #IsValid, #Impl() and 
   ///       #operator bool() when the handle is invalid. An InvalidHandle
   ///       exception will be thrown.
-  operator bool() const;
+  operator bool() const { return this->IsValid(); }
   /// \brief check validity of handle
   /// \sa #operator bool()
-  bool IsValid() const;
+  bool IsValid() const { return Impl().get()!=0; }
   //@}
+  friend class ConstGenericPropContainer<ChainBase>;
+  String GetName() const;
 
   const impl::ChainImplPtr& Impl() const {
     return impl_;
diff --git a/modules/mol/base/src/chain_handle.hh b/modules/mol/base/src/chain_handle.hh
index 6337818deeebc8356c1a08421173edc39da076ee..1d774dadd2c14d89acadaca430f98875ec7e66db 100644
--- a/modules/mol/base/src/chain_handle.hh
+++ b/modules/mol/base/src/chain_handle.hh
@@ -46,7 +46,7 @@ namespace ost { namespace mol {
 /// the residue numbers are in ascending order.
 ///
 /// New residues are inserted via one of the editors obtained from 
-/// EntityHandle::RequestXCSEditor() or EntityHandle::RequestICSEditor(). To
+/// EntityHandle::EditXCS() or EntityHandle::EditICS(). To
 /// append a residue to the C-terminal end, use EditorBase::AppendResidue, to
 /// insert after or before a specific residue, EditorBase::InsertResidueAfter
 /// and ditorBase::InsertResidueABefore will do the job, respectively.
@@ -57,6 +57,7 @@ public:
 
   ChainHandle(const impl::ChainImplPtr& impl);
   
+
   /// \brief Get parent entity.
   EntityHandle GetEntity() const;
 
@@ -104,11 +105,12 @@ public:
   // \c ResidueHandle::GetResidueCount().
   int GetAtomCount() const;
 
-  //! \brief   Get number of bonds of this chain. This method might NOT work as expected (see warning below).
+  /// \brief   Get number of all inclusive bonds of this chain.
+  ///
   /// \warning For a bond between two different chains, it is not clearly
-  ///          defined to which chain it belongs. Therefore, this method
-  ///          works only correctly if the chain has NO bonds to any other
-  ///          chains!
+  ///          defined to which chain it belongs. Therefore, this method will
+  ///          only return the number of bonds where both bonded atoms are
+  ///          within the same chain (all inclusive bonds).
   int GetBondCount() const;
   
   /// \brief   Get number of residues of this chain.
diff --git a/modules/mol/base/src/chain_view.cc b/modules/mol/base/src/chain_view.cc
index 1c5ba252e6c3d526ac711bb99f8031d860bda5e5..beac66cbedc73343e38cf81d9acb473523df6b3c 100644
--- a/modules/mol/base/src/chain_view.cc
+++ b/modules/mol/base/src/chain_view.cc
@@ -79,7 +79,11 @@ ChainView::ChainView() {
 }
 
 EntityView ChainView::GetEntity() const {
-  return EntityView(data_->entity.lock(), Impl()->GetEntity());
+  this->CheckValidity();
+  if (!data_->entity.expired()) {
+    return EntityView(data_->entity.lock(), Impl()->GetEntity());    
+  }
+  throw InvalidHandle();
 }
 
 ChainView::ChainView(const EntityView& entity,
@@ -134,6 +138,20 @@ int ChainView::GetAtomCount() const {
   return count;
 }
 
+int ChainView::GetBondCount() const {
+  this->CheckValidity();
+  int count=0;
+  EntityView ev = this->GetEntity();
+  const BondHandleList& bhl = ev.GetBondList();
+  for (BondHandleList::const_iterator i=bhl.begin(); i!=bhl.end(); ++i) {
+    if (i->GetFirst().GetResidue().GetChain().GetName()==this->GetName() &&
+        i->GetSecond().GetResidue().GetChain().GetName()==this->GetName()) {
+      count++;
+    }
+  }
+  return count;
+}
+
 ResidueView ChainView::FindResidue(const ResNum& number) const {
   this->CheckValidity();  
   const ResidueViewList& l=data_->residues;
@@ -381,7 +399,7 @@ geom::Vec3 ChainView::GetCenterOfMass() const
       ResidueView r=*i;
       for (AtomViewList::const_iterator j=r.GetAtomList().begin(),
           e2=r.GetAtomList().end(); j!=e2; ++j) {
-        center+=j->GetPos() * j->GetAtomProps().mass;
+        center+=j->GetPos() * j->GetMass();
       }
     }
     center/=mass;
diff --git a/modules/mol/base/src/chain_view.hh b/modules/mol/base/src/chain_view.hh
index 800d1fc82434898e2cd1bd436e8df4dfb1f5be8b..fbade451850c34be4d5c276b7416381e627ad950 100644
--- a/modules/mol/base/src/chain_view.hh
+++ b/modules/mol/base/src/chain_view.hh
@@ -44,6 +44,21 @@ public:
   ChainView(const EntityView& entity,
             const ChainHandle& chain);
 public:
+  
+  /// \name Handle validity
+  //@{
+  /// \brief check validity of handle
+  /// 
+  /// check, whether the chain handle points to a valid handle.
+  /// \note It is an error to use any method other than #IsValid, #Impl() and 
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return data_.get()!=0; }
+  //@}
+  
   /// \brief Get parent entity view
   EntityView GetEntity() const;
   
@@ -56,6 +71,14 @@ public:
   /// \brief Get number of atoms in this chain view
   int GetAtomCount() const;
   
+  /// \brief   Get number of all inclusive bonds of this chain.
+  ///
+  /// \warning For a bond between two different chains, it is not clearly
+  ///          defined to which chain it belongs. Therefore, this method will
+  ///          only return the number of bonds where both bonded atoms are
+  ///          within the same chain (all inclusive bonds).
+  int GetBondCount() const;
+
 public:
   /// \brief Add residue to view
   ///
diff --git a/modules/mol/base/src/chem_class.hh b/modules/mol/base/src/chem_class.hh
index f9c0f8279666df6fee4f2370b2ed40ba29432203..de74bcabca705b5b542bb0843f26216ffa17b8a8 100644
--- a/modules/mol/base/src/chem_class.hh
+++ b/modules/mol/base/src/chem_class.hh
@@ -18,16 +18,13 @@
 //------------------------------------------------------------------------------
 #ifndef OST_BASE_CHEM_CLASS_HI
 #define OST_BASE_CHEM_CLASS_HI
-#include <vector>
-
-#include <boost/shared_ptr.hpp>
 
 #include <ost/mol/module_config.hh>
 
 
 namespace ost { namespace mol {
 
-struct ChemClass {
+struct DLLEXPORT ChemClass {
   const static char PeptideLinking  ='P';
   const static char DPeptideLinking ='D';
   const static char LPeptideLinking ='L';
@@ -51,7 +48,7 @@ struct ChemClass {
   }
 
   bool operator!=(const ChemClass& cc) const {
-    return this->operator!=(cc);
+    return !this->operator==(cc);
   }
 
   bool IsPeptideLinking() const {
diff --git a/modules/mol/base/src/coord_group.cc b/modules/mol/base/src/coord_group.cc
index 4dcabf68bdc7ef09818a3f9a42fae7886c031dee..b4bea4c8e8267214f27c3794884ebb3978c9c62b 100644
--- a/modules/mol/base/src/coord_group.cc
+++ b/modules/mol/base/src/coord_group.cc
@@ -93,6 +93,21 @@ void CoordGroupHandle::AddFrame(const std::vector<geom::Vec3>& clist)
   }
 }
 
+void CoordGroupHandle::AddFrames(const CoordGroupHandle& cg)
+{
+  this->CheckValidity();
+  if (source_->IsMutable()) {
+    if (cg.GetAtomCount()!=this->GetAtomCount()) {
+      throw IntegrityError("Atom number don't match");
+    }
+    for (size_t i=0; i<cg.GetFrameCount(); ++i) {
+      source_->AddFrame(*cg.GetFrame(i));
+    }
+  } else {
+    throw IntegrityError("Can't add frame to immutable CoordGroup");
+  }
+}
+
 void CoordGroupHandle::CheckValidity() const
 {
   if (!source_) {
diff --git a/modules/mol/base/src/coord_group.hh b/modules/mol/base/src/coord_group.hh
index dfa3c85304e38e1e63da5cbac085220b7e063fed..8f7f78c9ec0196cb9619ec0dda0c85b77b7ebfb3 100644
--- a/modules/mol/base/src/coord_group.hh
+++ b/modules/mol/base/src/coord_group.hh
@@ -67,6 +67,7 @@ public:
   /// \brief add frame 
   void AddFrame(const std::vector<geom::Vec3>& clist);
 
+  void AddFrames(const CoordGroupHandle& cg);
   /// \brief set an indidivial atom position in the given frame
   void SetAtomPos(uint frame, AtomHandle atom, const geom::Vec3& pos);
 
diff --git a/modules/mol/base/src/coord_source.cc b/modules/mol/base/src/coord_source.cc
index 37d1fbd91cf9ce4dba16bb3614909cf77f064111..db02718fd5bec7c2721ddf11ec3eca4bc55e0932 100644
--- a/modules/mol/base/src/coord_source.cc
+++ b/modules/mol/base/src/coord_source.cc
@@ -63,7 +63,7 @@ void CoordSource::CopyFrame(uint frame_id)
     return;
   }
   assert(frame->size()==atoms_.size());
-  XCSEditor edi=atoms_.front().GetEntity().RequestXCSEditor(BUFFERED_EDIT);  
+  XCSEditor edi=atoms_.front().GetEntity().EditXCS(BUFFERED_EDIT);  
   CoordFrame::const_iterator c=frame->begin();
   for (AtomHandleList::iterator i=atoms_.begin(), 
        e=atoms_.end(); i!=e; ++i, ++c) {
diff --git a/modules/mol/base/src/editor_base.cc b/modules/mol/base/src/editor_base.cc
index 022109e062fa53e4be69a7c919e98c0350de6e5e..29b5d19116a9b260aa39c6be97e6051306c9ccea 100644
--- a/modules/mol/base/src/editor_base.cc
+++ b/modules/mol/base/src/editor_base.cc
@@ -78,29 +78,34 @@ void EditorBase::RenameChain(ChainHandle chain, const String& new_name)
 
 
 AtomHandle EditorBase::InsertAtom(ResidueHandle res, const String& name,
-                                  const geom::Vec3& pos,
-                                  const AtomProp& prop)
+                                  const geom::Vec3& pos, const String& ele,
+                                  Real occupancy, Real b_factor, 
+                                  bool is_hetatm)
 {
   CheckHandleValidity(res);
   ent_.Impl()->MarkTraceDirty();  
-  return AtomHandle(res.Impl()->InsertAtom(name, pos,prop));
+  AtomHandle atom(res.Impl()->InsertAtom(name, pos, ele));
+  atom.SetBFactor(b_factor);
+  atom.SetHetAtom(is_hetatm);
+  atom.SetOccupancy(occupancy);
+  return atom;
 }
 
 AtomHandle EditorBase::InsertAltAtom(ResidueHandle res, const String& name,
                                      const String& alt_group,
                                      const geom::Vec3& pos,
-                                     const AtomProp& prop) 
+                                     const String& ele) 
 {
   CheckHandleValidity(res);
   ent_.Impl()->MarkTraceDirty();
-  AtomHandle atom(res.Impl()->InsertAltAtom(name, alt_group, pos, prop));
+  AtomHandle atom(res.Impl()->InsertAltAtom(name, alt_group, pos, ele));
   this->UpdateTrace();
   return atom;
 }
 
 void EditorBase::AddAltAtomPos(const String& group,
-                                    const AtomHandle& atom,
-                                    const geom::Vec3& position) 
+                               const AtomHandle& atom,
+                               const geom::Vec3& position) 
 {
   CheckHandleValidity(atom);
   atom.GetResidue().Impl()->AddAltAtomPos(group, atom.Impl(), position);
@@ -114,7 +119,6 @@ void EditorBase::DeleteChain(const ChainHandle& chain)
 
 void EditorBase::DeleteAtom(const AtomHandle& atom_handle) 
 {
-  
   CheckHandleValidity(atom_handle);
   atom_handle.GetResidue().Impl()->DeleteAtom(atom_handle.Impl());
 }
@@ -125,6 +129,17 @@ void EditorBase::DeleteResidue(const ResidueHandle& residue_handle)
   residue_handle.GetChain().Impl()->DeleteResidue(residue_handle.Impl());
 }
 
+void EditorBase::ReorderResidues(const ChainHandle& chain)
+{
+  CheckHandleValidity(chain);
+  chain.Impl()->ReorderResidues();
+}
+
+void EditorBase::ReorderAllResidues()
+{
+  ent_.Impl()->ReorderAllResidues();
+}
+
 void EditorBase::RenameAtom(AtomHandle atom, const String& new_name)
 {
   CheckHandleValidity(atom);
diff --git a/modules/mol/base/src/editor_base.hh b/modules/mol/base/src/editor_base.hh
index 4a1ab915ab074fc03bd18c7056c11ac9a377e215..964f2fdba6ce7e94c3d498c36f07ba179ba5af09 100644
--- a/modules/mol/base/src/editor_base.hh
+++ b/modules/mol/base/src/editor_base.hh
@@ -28,7 +28,6 @@
 
 #include "entity_handle.hh"
 #include "residue_prop.hh"
-#include "atom_prop.hh"
 #include "editor_type_fw.hh"
 
 namespace ost { namespace mol {
@@ -40,8 +39,8 @@ namespace ost { namespace mol {
 /// Editors are usually used as one of the concrete subclasses of EditorBase:
 /// XCSEditor and ICSEditor. The former operates on the external carthesian
 /// coordinate system while the latter operates on the internal coordinate
-/// system. To create a new editor, use EntityHandle::RequestXCSEditor() and
-/// EntityHandle::RequestICSEditor(), respectively.
+/// system. To create a new editor, use EntityHandle::EditXCS() and
+/// EntityHandle::EditICS(), respectively.
 /// 
 /// For an introduction to the concept of editors go \ref editors "here"
 class DLLEXPORT_OST_MOL EditorBase {
@@ -116,17 +115,16 @@ public:
   ///     algorithms as well as most builders in the conop module rely on proper 
   ///     naming.
   /// \param pos is the position of the atom in global coordinates
-  /// \param prop are the atom's properties such as element, van der Waals 
-  ///     radius charge and so on. The default set of atom properties is  rather
-  ///     meaningless
   AtomHandle InsertAtom(ResidueHandle residue, const String& name, 
-                        const geom::Vec3& pos, const AtomProp& prop=AtomProp());
+                        const geom::Vec3& pos, const String& ele="",
+                        Real occupancy=1.0, Real b_factor=0.0, 
+                        bool is_hetatm=false);
 
   /// \brief Insert new atom with alternative position indicator
   /// \sa EditorBase::AddAltAtomPos(), ResidueHandle
   AtomHandle InsertAltAtom(ResidueHandle residue, const String& name, 
-                           const String& alt_group, const geom::Vec3& pos, 
-                           const AtomProp& prop=AtomProp());
+                           const String& alt_group, const geom::Vec3& pos,
+                           const String& ele="");
   /// \brief  Add alternative atom position
   /// \param group is the name of the alternative atom position group. If no 
   ///     group of that name exists, it will be created.
@@ -138,7 +136,7 @@ public:
   ///         is the alternative position
   /// \sa EditorBase::InsertAltAtom(), ResidueHandle
   void AddAltAtomPos(const String& group, const AtomHandle& atom, 
-                          const geom::Vec3& position);                           
+                     const geom::Vec3& position);
   //\}
   
   /// \brief connect two atoms with bond
@@ -184,6 +182,12 @@ public:
   ///
   /// \sa ChainHandle::DeleteResidue, DeleteAtom
   void DeleteResidue(const ResidueHandle& residue_handle);
+
+  /// \brief reorder residues of given chain based on their residue number
+  void ReorderResidues(const ChainHandle& chain);
+
+  /// \brief reorder residues of all chains based on their residue number
+  void ReorderAllResidues();
     
   /// \brief Get edit mode of editor
   EditMode GetMode() const;
diff --git a/modules/mol/base/src/entity_base.cc b/modules/mol/base/src/entity_base.cc
index 16ea851d9344aa560dd64fc8d65b2cd7366a77b1..5cd4f9fc7dabf1a6d1be1a1ba003ba1608277d8f 100644
--- a/modules/mol/base/src/entity_base.cc
+++ b/modules/mol/base/src/entity_base.cc
@@ -46,14 +46,6 @@ const GenericPropContainerImpl* EntityBase::GpImpl() const
   return Impl().get();
 }
 
-bool EntityBase::IsValid() const {
-  return impl_.get()!=0;
-}
-
-EntityBase::operator bool() const {
-  return impl_.get()!=0;
-}
-
 void EntityBase::CheckValidity() const {
   if (!impl_)
     throw InvalidHandle();
@@ -71,7 +63,7 @@ void EntityBase::SetName(const String& ent_name) {
 
 DLLEXPORT_OST_MOL std::ostream& operator<<(std::ostream& os,   
                                            const EntityBase& ent) {
-  if (ent.IsValid()) {
+  if (ent.Impl()) {
     os << "entity";
   } else {
     os << "invalid";
diff --git a/modules/mol/base/src/entity_base.hh b/modules/mol/base/src/entity_base.hh
index 9c4fe8922e0da646364a8c71053acfc5522ac904..7e5c7f2d78d1fd31a532c925775043a88674f0dd 100644
--- a/modules/mol/base/src/entity_base.hh
+++ b/modules/mol/base/src/entity_base.hh
@@ -34,20 +34,6 @@ public:
   EntityBase(const impl::EntityImplPtr& impl);
   EntityBase();
   
-  /// \name Handle validity
-  //@{
-  /// \brief check validity of handle
-  /// 
-  /// check, whether the entity handle points to a valid entity.
-  /// \note It is an error to use any method other than #IsValid, #Impl and 
-  ///       #operator bool() when the handle is invalid. An InvalidHandle
-  ///       exception will be thrown.
-  operator bool() const;
-  /// \brief check validity of handle
-  /// \sa #operator bool()
-  bool IsValid() const;
-  //@}
-  
   ///\brief Get entity name.
   ///
   /// \sa      EntityBase::SetName
@@ -61,6 +47,19 @@ public:
   void SetName(const String& ent_name);
 
 public:
+  
+  /// \name Handle validity
+  //@{
+  /// \brief check validity of handle
+  /// 
+  /// check, whether the entity handle points to a valid entity.
+  /// \note It is an error to use any method other than #IsValid, #Impl and 
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return Impl().get()!=0; }
   impl::EntityImplPtr& Impl();
   const impl::EntityImplPtr& Impl() const;
 protected:
diff --git a/modules/mol/base/src/entity_handle.cc b/modules/mol/base/src/entity_handle.cc
index 17c47cd81112c92ef308c598cf7c03202a1c6648..1de8bff483b9d256e0784fc68b054c31d30010e7 100644
--- a/modules/mol/base/src/entity_handle.cc
+++ b/modules/mol/base/src/entity_handle.cc
@@ -304,13 +304,13 @@ AtomHandleIter EntityHandle::AtomsEnd() const
                         impl::end(r.back()->GetAtomList()), ent, false);
 }
 
-XCSEditor EntityHandle::RequestXCSEditor(EditMode mode) const
+XCSEditor EntityHandle::EditXCS(EditMode mode) const
 {
   this->CheckValidity();
   return XCSEditor(*this, mode);
 }
 
-ICSEditor EntityHandle::RequestICSEditor(EditMode mode) const
+ICSEditor EntityHandle::EditICS(EditMode mode) const
 {
   this->CheckValidity();
   Impl()->EnableICS();
diff --git a/modules/mol/base/src/entity_handle.hh b/modules/mol/base/src/entity_handle.hh
index 540425c70219e49396c29ce19ef54850712edd70..a7d8f887eaf5f4573105c9b39f2ade0d9c240840 100644
--- a/modules/mol/base/src/entity_handle.hh
+++ b/modules/mol/base/src/entity_handle.hh
@@ -64,6 +64,8 @@ public:
   /// default ctor. creates invalid handle.
   EntityHandle();
   
+
+  //@}
   /// \brief copy entity, effectively duplicating the whole data structure
   /// 
   /// Alternative atom positions are not handled at all!
@@ -263,12 +265,12 @@ public:
   /// \brief Get editor for external coordinate system to manipulate atom 
   ///     positions
   /// \sa editors
-  XCSEditor RequestXCSEditor(EditMode mode=UNBUFFERED_EDIT) const;
+  XCSEditor EditXCS(EditMode mode=UNBUFFERED_EDIT) const;
   
   /// \brief Get editor for the internal coordinate system to manipulate 
   ///    torsions bond lengths and angles between bonds
   /// \sa editors
-  ICSEditor RequestICSEditor(EditMode mode=UNBUFFERED_EDIT) const;  
+  ICSEditor EditICS(EditMode mode=UNBUFFERED_EDIT) const;  
   
   /// \brief get this handle
   /// 
diff --git a/modules/mol/base/src/entity_view.cc b/modules/mol/base/src/entity_view.cc
index 945230d2f2779b172c02bc4ffc341fb2d3c96a73..8517e548b1b850fc90977d5ae22c2e471ca21cc1 100644
--- a/modules/mol/base/src/entity_view.cc
+++ b/modules/mol/base/src/entity_view.cc
@@ -265,6 +265,7 @@ ResidueView EntityView::FindResidue(const ResidueHandle& residue) const {
 
 AtomView EntityView::FindAtom(const AtomHandle& atom) const 
 {
+  this->CheckValidity();
   return data_->ViewForHandle(atom);
 }
 
diff --git a/modules/mol/base/src/entity_view.hh b/modules/mol/base/src/entity_view.hh
index e9566a1c2f3c756fbf003031ad4a0d6f01df05b2..b163966867d30ae50d6805bd0e99f39216e34454 100644
--- a/modules/mol/base/src/entity_view.hh
+++ b/modules/mol/base/src/entity_view.hh
@@ -93,9 +93,22 @@ public:
   ///
   /// \param entity The handle the view is created from.
   /// \param flags An ORed together list of ViewAddFlag
-  EntityView(const EntityHandle& entity,
-             ViewAddFlags flags=0);
-             
+  explicit EntityView(const EntityHandle& entity,
+                      ViewAddFlags flags=0);
+
+  /// \name View validity
+  //@{
+  /// \brief check validity of handle
+  /// 
+  /// check, whether the entity view points to a valid entity.
+  /// \note It is an error to use any method other than #IsValid, #Impl and 
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return data_.get()!=0; }
+  //@}
   /// \brief Get entity's mass
   Real GetMass() const;
              
diff --git a/modules/mol/base/src/impl/CMakeLists.txt b/modules/mol/base/src/impl/CMakeLists.txt
index 41ddeb0b5672a5081a97b63ec1a6a5c3cdc497d5..45a453ac1901307c628aeccb2f427a0293d480d3 100644
--- a/modules/mol/base/src/impl/CMakeLists.txt
+++ b/modules/mol/base/src/impl/CMakeLists.txt
@@ -10,12 +10,14 @@ query_impl.cc
 residue_impl.cc
 surface_impl.cc
 torsion_impl.cc
+atom_prop.cc
 PARENT_SCOPE
 )
 
 set(OST_MOL_IMPL_HEADERS
 pointer_iterator.hh
 atom_group.hh
+atom_prop.hh
 atom_impl.hh
 atom_impl_fw.hh
 chain_impl.hh
diff --git a/modules/mol/base/src/impl/atom_impl.cc b/modules/mol/base/src/impl/atom_impl.cc
index 698bc863f2083117655a67901aa8bb7d2fa5bfe0..71b714385d071805850c189783b8c511016a34d5 100644
--- a/modules/mol/base/src/impl/atom_impl.cc
+++ b/modules/mol/base/src/impl/atom_impl.cc
@@ -40,22 +40,28 @@ AtomImpl::AtomImpl(const EntityImplPtr& e,
                    const ResidueImplPtr& r,
                    const String& n,
                    const geom::Vec3& p,
-                   const AtomProp& prop,
+                   const String& ele,
                    unsigned long index):
   res_(r),
   name_(n),
   pos_(p),
-  prop_(prop),
+  occupancy_(0.0),
+  b_factor_(1.0),
+  prop_(NULL),  
+  is_hetatm_(false),  
+  element_(ele),
   prim_connector_(),
   connector_list_(),
   fragment_(),
   state_(0),
+
   index_(index)
 {
   EntityHandle ent = this->GetEntity();
   geom::Mat4 transf_matrix = ent.GetTransformationMatrix();
   geom::Vec3 transf_pos = geom::Vec3(transf_matrix*geom::Vec4(p));
   tf_pos_ = transf_pos;
+  prop_=AtomProp::GetDefaultProps(element_);
 }
 
 void AtomImpl::AddSecondaryConnector(const ConnectorImplP& bp)
@@ -204,6 +210,10 @@ void AtomImpl::UpdateFromXCS()
 }
 
 AtomImpl::~AtomImpl() {
+  if (prop_ && !prop_->is_default) {
+    delete prop_;
+    prop_=NULL;
+  }
 }
 
 EntityImplPtr AtomImpl::GetEntity() const
@@ -319,11 +329,11 @@ Real AtomImpl::GetFloatProperty(Prop::ID prop_id) const
     case Prop::AZ:
       return pos_[2];            
     case Prop::OCC:
-      return prop_.occupancy;
+      return occupancy_;
     case Prop::ABFAC:
-      return prop_.b_factor;
+      return b_factor_;
     case Prop::ACHARGE:
-      return prop_.charge;
+      return prop_->charge;
     default:
       throw PropertyError(prop_id);
   }
@@ -335,7 +345,7 @@ String AtomImpl::GetStringProperty(Prop::ID prop_id) const
     case Prop::ANAME:
       return name_;
     case Prop::ELE:
-      return prop_.element;
+      return element_;
     default:
       throw PropertyError(prop_id);
   }
diff --git a/modules/mol/base/src/impl/atom_impl.hh b/modules/mol/base/src/impl/atom_impl.hh
index 9fcbbf77636a50e0871bf6b01ea70bc28c8a157d..589432ca9041c600d0fba6ec850615d97e0d6cb6 100644
--- a/modules/mol/base/src/impl/atom_impl.hh
+++ b/modules/mol/base/src/impl/atom_impl.hh
@@ -24,7 +24,7 @@
 #include <ost/mol/module_config.hh>
 #include <ost/geom/geom.hh>
 #include <ost/mol/entity_visitor_fw.hh>
-#include <ost/mol/atom_prop.hh>
+#include <ost/mol/impl/atom_prop.hh>
 
 #include <ost/mol/impl/atom_impl_fw.hh>
 #include <ost/mol/impl/residue_impl_fw.hh>
@@ -50,7 +50,7 @@ class AtomImpl: public GenericPropContainerImpl,
                 public boost::enable_shared_from_this<AtomImpl> {
 public:
    AtomImpl(const EntityImplPtr& ent, const ResidueImplPtr& res,
-            const String& name, const geom::Vec3& pos, const AtomProp& prop,
+            const String& name, const geom::Vec3& pos, const String& ele,
             unsigned long index);
 
   ~AtomImpl();
@@ -70,11 +70,7 @@ public:
   void SetTransformedPos(const geom::Vec3& pos) { tf_pos_=pos; }
 
   void SetOriginalPos(const geom::Vec3& pos) { pos_=pos; }
-  
-  const AtomProp& GetAtomProps() const {return prop_;}
-  
-  AtomProp& GetAtomProps() {return prop_;}
-  
+      
   ResidueImplPtr GetResidue() const;
 
   void SetPrimaryConnector(const ConnectorImplP& bp) {
@@ -111,11 +107,93 @@ public:
   void SetTraced(bool f) {set_state_bit(1,f);}
   bool IsTraced() const {return get_state_bit(1);}
 
-  unsigned int GetState() const {
+
+  Real GetBFactor() const { return b_factor_; }
+  
+  const String& GetElement() const { return element_; }  
+  
+  void SetElement(const String& ele) 
+  { 
+    if (element_!=ele) {
+      element_=ele;
+      prop_=impl::AtomProp::GetDefaultProps(element_);
+    }
+  }
+  bool HasDefaultProps() const { return prop_->is_default; }
+  void SetAnisou(const geom::Mat3& anisou)
+  {
+    if (prop_->is_default && prop_->anisou!=anisou) {
+      prop_=new AtomProp(*prop_);
+      prop_->is_default=false;
+      prop_->has_anisou=true;
+    }
+
+    prop_->anisou=anisou;
+  }
+  
+  const geom::Mat3& GetAnisou() const
+  {
+    return prop_->anisou;
+  }
+  void SetBFactor(Real factor) 
+  { 
+    b_factor_=factor;
+  }  
+  
+  void SetOccupancy(Real occ)
+  {
+    occupancy_=occ;
+  }
+  
+  Real GetOccupancy() const 
+  { 
+    return occupancy_; 
+  }
+  
+  Real GetRadius() const { return prop_->radius; }
+  
+  Real GetMass() const { return prop_->mass; }
+  Real GetCharge() const { return prop_->charge; }
+  
+  bool IsHetAtom() { return is_hetatm_; }
+  
+  void SetHetAtom(bool het) { is_hetatm_=het; }
+  
+  void SetMass(Real mass)
+  {
+    if (prop_->is_default && prop_->mass!=mass) {
+      prop_=new AtomProp(*prop_);
+      prop_->is_default=false;
+    }
+    prop_->mass=mass;
+  }
+  
+  void SetRadius(Real radius)
+  {
+    if (prop_->is_default && prop_->radius!=radius) {
+      prop_=new AtomProp(*prop_);
+      prop_->is_default=false;
+    }
+    prop_->radius=radius;
+  }
+  
+  void SetCharge(Real charge)
+  {
+    if (prop_->is_default && prop_->charge!=charge) {
+      prop_=new AtomProp(*prop_);
+      prop_->is_default=false;
+    }
+    prop_->charge=charge;
+  }
+  
+  
+  unsigned int GetState() const 
+  {
     return state_;
   }
   
-  void SetState(int state) {
+  void SetState(int state) 
+  {
     state_=state;
   }
   
@@ -144,11 +222,14 @@ public:
                      
 private:
   ResidueImplW res_;
-  String name_;
-  geom::Vec3 pos_;
-  geom::Vec3 tf_pos_;
-  AtomProp prop_;
-
+  String       name_;
+  geom::Vec3   pos_;
+  geom::Vec3   tf_pos_;
+  Real         occupancy_;
+  Real         b_factor_;
+  AtomProp*    prop_;
+  bool         is_hetatm_;
+  String       element_;  
   ConnectorImplP prim_connector_;
   ConnectorImplList connector_list_;
   FragmentImplP fragment_;
diff --git a/modules/mol/base/src/impl/atom_prop.cc b/modules/mol/base/src/impl/atom_prop.cc
new file mode 100644
index 0000000000000000000000000000000000000000..aefb8d2196f8e64819d7e53ed2b151dd478e556c
--- /dev/null
+++ b/modules/mol/base/src/impl/atom_prop.cc
@@ -0,0 +1,159 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#include <algorithm>
+#include "atom_prop.hh"
+
+namespace ost { namespace mol { namespace impl {
+
+std::map<String, AtomProp> AtomProp::defaults_;
+
+void AtomProp::Init()
+{
+  defaults_["AC"]=AtomProp(2.0000, 227.0000);
+  defaults_["AG"]=AtomProp(1.7200, 107.8680);
+  defaults_["AL"]=AtomProp(2.0000, 26.9820);
+  defaults_["AM"]=AtomProp(2.0000, 243.0000);
+  defaults_["AR"]=AtomProp(1.8800, 39.9480);
+  defaults_["AS"]=AtomProp(1.8500, 74.9220);
+  defaults_["AT"]=AtomProp(2.0000, 210.0000);
+  defaults_["AU"]=AtomProp(1.6600, 196.9670);
+  defaults_["B"]=AtomProp(2.0000, 10.8110);
+  defaults_["BA"]=AtomProp(2.0000, 137.3270);
+  defaults_["BE"]=AtomProp(2.0000, 9.0120);
+  defaults_["BH"]=AtomProp(2.0000, 264.0000);
+  defaults_["BI"]=AtomProp(2.0000, 208.9800);
+  defaults_["BK"]=AtomProp(2.0000, 247.0000);
+  defaults_["BR"]=AtomProp(1.8500, 79.9040);
+  defaults_["C"]=AtomProp(1.7000, 12.0110);
+  defaults_["CA"]=AtomProp(2.0000, 40.0780);
+  defaults_["CD"]=AtomProp(1.5800, 112.4110);
+  defaults_["CE"]=AtomProp(2.0000, 140.1160);
+  defaults_["CF"]=AtomProp(2.0000, 251.0000);
+  defaults_["CL"]=AtomProp(1.7500, 35.4530);
+  defaults_["CM"]=AtomProp(2.0000, 247.0000);
+  defaults_["CO"]=AtomProp(2.0000, 58.9330);
+  defaults_["CR"]=AtomProp(2.0000, 51.9960);
+  defaults_["CS"]=AtomProp(2.0000, 132.9050);
+  defaults_["D"]=AtomProp(1.0900, 2.0141);
+  defaults_["CU"]=AtomProp(1.4000, 63.5460);
+  defaults_["DB"]=AtomProp(2.0000, 262.0000);
+  defaults_["DS"]=AtomProp(2.0000, 271.0000);
+  defaults_["DY"]=AtomProp(2.0000, 162.5000);
+  defaults_["ER"]=AtomProp(2.0000, 167.2600);
+  defaults_["ES"]=AtomProp(2.0000, 252.0000);
+  defaults_["EU"]=AtomProp(2.0000, 151.9640);
+  defaults_["F"]=AtomProp(1.4700, 18.9980);
+  defaults_["FE"]=AtomProp(2.0000, 55.8450);
+  defaults_["FM"]=AtomProp(2.0000, 257.0000);
+  defaults_["FR"]=AtomProp(2.0000, 223.0000);
+  defaults_["GA"]=AtomProp(1.8700, 69.7230);
+  defaults_["GD"]=AtomProp(2.0000, 157.2500);
+  defaults_["GE"]=AtomProp(2.0000, 72.6100);
+  defaults_["H"]=AtomProp(1.0900, 1.0080);
+  defaults_["HE"]=AtomProp(1.4000, 4.0030);
+  defaults_["HF"]=AtomProp(2.0000, 178.4900);
+  defaults_["HG"]=AtomProp(1.5500, 200.5900);
+  defaults_["HO"]=AtomProp(2.0000, 164.9300);
+  defaults_["HS"]=AtomProp(2.0000, 269.0000);
+  defaults_["I"]=AtomProp(1.9800, 126.9040);
+  defaults_["IN"]=AtomProp(1.9300, 114.8180);
+  defaults_["IR"]=AtomProp(2.0000, 192.2170);
+  defaults_["K"]=AtomProp(2.7500, 39.0980);
+  defaults_["KR"]=AtomProp(2.0200, 83.8000);
+  defaults_["LA"]=AtomProp(2.0000, 138.9060);
+  defaults_["LI"]=AtomProp(1.8200, 6.9410);
+  defaults_["LR"]=AtomProp(1.5000, 103.0000);
+  defaults_["LU"]=AtomProp(2.0000, 174.9670);
+  defaults_["MD"]=AtomProp(2.0000, 258.0000);
+  defaults_["MG"]=AtomProp(1.7300, 24.3050);
+  defaults_["MN"]=AtomProp(2.0000, 54.9380);
+  defaults_["MO"]=AtomProp(2.0000, 95.9400);
+  defaults_["MT"]=AtomProp(2.0000, 268.0000);
+  defaults_["N"]=AtomProp(1.5500, 14.0070);
+  defaults_["NA"]=AtomProp(2.2700, 22.9910);
+  defaults_["NB"]=AtomProp(2.0000, 92.9060);
+  defaults_["ND"]=AtomProp(2.0000, 144.2400);
+  defaults_["NE"]=AtomProp(1.5400, 20.1800);
+  defaults_["NI"]=AtomProp(1.6300, 58.6930);
+  defaults_["NO"]=AtomProp(2.0000, 259.0000);
+  defaults_["NP"]=AtomProp(2.0000, 237.0000);
+  defaults_["O"]=AtomProp(1.5200, 15.9990);
+  defaults_["OS"]=AtomProp(2.0000, 190.2300);
+  defaults_["P"]=AtomProp(1.8000, 30.9740);
+  defaults_["PA"]=AtomProp(2.0000, 231.0360);
+  defaults_["PB"]=AtomProp(2.0200, 207.2000);
+  defaults_["PD"]=AtomProp(1.6300, 106.4200);
+  defaults_["PM"]=AtomProp(2.0000, 145.0000);
+  defaults_["PO"]=AtomProp(2.0000, 210.0000);
+  defaults_["PR"]=AtomProp(2.0000, 140.9080);
+  defaults_["PT"]=AtomProp(1.7200, 195.0780);
+  defaults_["PU"]=AtomProp(2.0000, 244.0000);
+  defaults_["RA"]=AtomProp(2.0000, 226.0000);
+  defaults_["RB"]=AtomProp(2.0000, 85.4680);
+  defaults_["RE"]=AtomProp(2.0000, 186.2070);
+  defaults_["RF"]=AtomProp(2.0000, 261.0000);
+  defaults_["RH"]=AtomProp(2.0000, 102.9060);
+  defaults_["RN"]=AtomProp(2.0000, 222.0000);
+  defaults_["RU"]=AtomProp(2.0000, 101.0700);
+  defaults_["S"]=AtomProp(1.8000, 32.0660);
+  defaults_["SB"]=AtomProp(2.0000, 121.7600);
+  defaults_["SC"]=AtomProp(2.0000, 44.9560);
+  defaults_["SE"]=AtomProp(1.9000, 78.9600);
+  defaults_["SG"]=AtomProp(2.0000, 266.0000);
+  defaults_["SI"]=AtomProp(2.1000, 28.0860);
+  defaults_["SM"]=AtomProp(2.0000, 150.3600);
+  defaults_["SN"]=AtomProp(2.1700, 118.7100);
+  defaults_["SR"]=AtomProp(2.0000, 87.6200);
+  defaults_["TA"]=AtomProp(2.0000, 180.9480);
+  defaults_["TB"]=AtomProp(2.0000, 158.9250);
+  defaults_["TC"]=AtomProp(2.0000, 98.0000);
+  defaults_["TE"]=AtomProp(2.0600, 127.6000);
+  defaults_["TH"]=AtomProp(2.0000, 232.0380);
+  defaults_["TI"]=AtomProp(2.0000, 47.8670);
+  defaults_["TL"]=AtomProp(1.9600, 204.3830);
+  defaults_["TM"]=AtomProp(2.0000, 168.9340);
+  defaults_["U"]=AtomProp(1.8600, 238.0290);
+  defaults_["V"]=AtomProp(2.0000, 50.9420);
+  defaults_["W"]=AtomProp(2.0000, 183.8400);
+  defaults_["XE"]=AtomProp(2.1600, 131.2900);
+  defaults_["Y"]=AtomProp(2.0000, 88.9060);
+  defaults_["YB"]=AtomProp(2.0000, 173.0400);
+  defaults_["ZN"]=AtomProp(1.3900, 65.3900);
+  defaults_["ZR"]=AtomProp(2.0000, 91.2240);
+
+  defaults_[""]=AtomProp(0.0, 0.0);
+
+}
+
+AtomProp* AtomProp::GetDefaultProps(const String& ele)  
+{
+  if (defaults_.empty()) {
+    AtomProp::Init();
+  }
+  String upper_ele=ele;
+  std::transform(upper_ele.begin(),upper_ele.end(),upper_ele.begin(),toupper);  
+  std::map<String, AtomProp>::iterator i=defaults_.find(upper_ele);
+  if (i!=defaults_.end()) {
+    return &i->second;
+  }
+  return &defaults_[""];
+}
+
+
+}}}
diff --git a/modules/mol/base/src/atom_prop.hh b/modules/mol/base/src/impl/atom_prop.hh
similarity index 68%
rename from modules/mol/base/src/atom_prop.hh
rename to modules/mol/base/src/impl/atom_prop.hh
index badf20f00898a70a416826bcdf9602fc04d2b9d4..95e3068ea44ae429340c6d1785e1c48154d29f5b 100644
--- a/modules/mol/base/src/atom_prop.hh
+++ b/modules/mol/base/src/impl/atom_prop.hh
@@ -19,38 +19,42 @@
 #ifndef OST_ATOM_PROP_HH
 #define OST_ATOM_PROP_HH
 
+#include <map>
 #include <ost/mol/module_config.hh>
 #include <ost/geom/mat3.hh>
 
-namespace ost { namespace mol {
-
+namespace ost { namespace mol { namespace impl {
 
 
 class DLLEXPORT_OST_MOL AtomProp {
 public:
   AtomProp()
-    : element(""), radius(0.0), occupancy(1.0),
-      b_factor(0.0), charge(0.0), mass(0.0),
-      is_hetatm(false), has_anisou(false),
-      ordinal(0), anisou(geom::Mat3()) {
-
+    : radius(0.0), charge(0.0), mass(0.0), has_anisou(false), is_default(true),
+      anisou(geom::Mat3()) 
+  {
   }
-  String        element;
+  AtomProp(Real r, Real m, Real c=0.0): radius(r), charge(c), 
+     mass(m), has_anisou(false), is_default(true)
+  { }
+  AtomProp(const AtomProp& rhs): radius(rhs.radius), charge(rhs.charge),
+    mass(rhs.mass), has_anisou(rhs.has_anisou), is_default(rhs.is_default),
+    anisou(rhs.anisou)
+  { }
   Real          radius;
-  Real          occupancy;
-  Real          b_factor;
   Real          charge;
   Real          mass;
-  bool          is_hetatm;
   bool          has_anisou;
-  
-  int           ordinal;
+  bool          is_default;
   geom::Mat3    anisou;
+  
+  static AtomProp* GetDefaultProps(const String& ele);
+  
 private:
-  unsigned char flags;
+  static void Init();
+  static std::map<String, AtomProp> defaults_;
 };
 
-}} // ns
+}}} // ns
 
 #endif
 
diff --git a/modules/mol/base/src/impl/chain_impl.cc b/modules/mol/base/src/impl/chain_impl.cc
index c6b3192d3b5b3c55740e24a7d87ad0302cd6c9d4..4d5313a38fbafd97e9fb0fa658febeb71743b107 100644
--- a/modules/mol/base/src/impl/chain_impl.cc
+++ b/modules/mol/base/src/impl/chain_impl.cc
@@ -66,6 +66,8 @@ ResidueImplPtr ChainImpl::AppendResidue(const ResidueImplPtr& res)
   dst_res->SetOneLetterCode(res->GetOneLetterCode());
   dst_res->SetSecStructure(res->GetSecStructure());
   dst_res->SetChemClass(res->GetChemClass());  
+  dst_res->SetProtein(res->IsProtein());
+  dst_res->SetIsLigand(res->IsLigand());
   return dst_res;
 }
 
@@ -369,7 +371,7 @@ Real ChainImpl::GetMass() const
     ResidueImplPtr r=*i;
     for (AtomImplList::iterator j=r->GetAtomList().begin(); 
           j!=r->GetAtomList().end(); ++j) {
-      mass+=(*j)->GetAtomProps().mass;
+      mass+=(*j)->GetMass();
     }
   }
   return mass;
@@ -424,7 +426,7 @@ geom::Vec3 ChainImpl::GetCenterOfMass() const
       ResidueImplPtr r=*i;
       for (AtomImplList::iterator j=r->GetAtomList().begin(); 
            j!=r->GetAtomList().end(); ++j) {
-        center+=(*j)->GetPos() * (*j)->GetAtomProps().mass;
+        center+=(*j)->GetPos() * (*j)->GetMass();
       }
     }
     center/=mass;
@@ -437,4 +439,17 @@ void ChainImpl::SetName(const String& new_name)
   name_=new_name;
 }
 
+namespace {
+  bool rnum_cmp(const ResidueImplPtr& r1, const ResidueImplPtr& r2)
+  {
+    return r1->GetNumber()<r2->GetNumber();
+  }
+}
+
+void ChainImpl::ReorderResidues()
+{
+  std::sort(residue_list_.begin(),residue_list_.end(),rnum_cmp);
+  UpdateShifts();
+}
+
 }}} // ns
diff --git a/modules/mol/base/src/impl/chain_impl.hh b/modules/mol/base/src/impl/chain_impl.hh
index 1737ca4f587a76e52d99617809cd3e148f8598d5..23b12119b1569b487510df6cb13932906e86d3f5 100644
--- a/modules/mol/base/src/impl/chain_impl.hh
+++ b/modules/mol/base/src/impl/chain_impl.hh
@@ -111,6 +111,8 @@ public:
   void DeleteResidue(const ResidueImplPtr& residue);
   
   void DeleteAllResidues();
+
+  void ReorderResidues();
   
   int GetIndex(const ResNum& number) const;  
   
diff --git a/modules/mol/base/src/impl/dihedral.cc b/modules/mol/base/src/impl/dihedral.cc
index ff484d4e694d70256e60525d5000897dfd75dcba..dab6b84d8542d4c8a34330c8f52e3788cb125028 100644
--- a/modules/mol/base/src/impl/dihedral.cc
+++ b/modules/mol/base/src/impl/dihedral.cc
@@ -46,13 +46,8 @@ Dihedral::Dihedral(const AtomImplList& atoms)
 
 
 Real Dihedral::GetAngleXCS() const {
-  Vec3 r1=atoms_[1]->GetPos()-atoms_[0]->GetPos();
-  Vec3 r2=atoms_[2]->GetPos()-atoms_[1]->GetPos();
-  Vec3 r3=atoms_[3]->GetPos()-atoms_[2]->GetPos();
-  Vec3 r12cross = Cross(r1, r2);
-  Vec3 r23cross = Cross(r2, r3);
-  return atan2(Dot(r1*Length(r2), r23cross),
-               Dot(r12cross, r23cross));
+  return geom::DihedralAngle(atoms_[0]->GetPos(), atoms_[1]->GetPos(), 
+                             atoms_[2]->GetPos(), atoms_[3]->GetPos());
 }
 
 Real Dihedral::GetAngleICS() const {
diff --git a/modules/mol/base/src/impl/entity_impl.cc b/modules/mol/base/src/impl/entity_impl.cc
index 7a3144aaaf91a61ba7e8f640c9ba29e8a7cf2bc5..c7ceb61ce2b8a1b9d4a6e1466e2b47a8f3ca04ce 100644
--- a/modules/mol/base/src/impl/entity_impl.cc
+++ b/modules/mol/base/src/impl/entity_impl.cc
@@ -297,7 +297,7 @@ geom::Vec3 EntityImpl::GetCenterOfMass() const {
   Real mass = this->GetMass();
   if (this->GetAtomCount()>0 && mass>0) {
     for(AtomImplMap::const_iterator it = atom_map_.begin();it!=atom_map_.end();++it) {
-      center+=it->second->GetPos()*it->second->GetAtomProps().mass;
+      center+=it->second->GetPos()*it->second->GetMass();
     }
     center/=mass;
   }
@@ -308,7 +308,7 @@ Real EntityImpl::GetMass() const {
   Real mass=0.0;
   for (AtomImplMap::const_iterator it = atom_map_.begin();
       it!=atom_map_.end();++it) {
-    mass+=it->second->GetAtomProps().mass;
+    mass+=it->second->GetMass();
   }
   return mass;
 }
@@ -316,13 +316,13 @@ Real EntityImpl::GetMass() const {
 AtomImplPtr EntityImpl::CreateAtom(const ResidueImplPtr& rp,
                                    const String& name,
                                    const geom::Vec3& pos,
-                                   const AtomProp& prop)
+                                   const String& ele)
 {
 #if MAKE_SHARED_AVAILABLE
   AtomImplPtr ap=boost::make_shared<AtomImpl>(shared_from_this(), rp, name, 
-                                              pos, prop,next_index_++);
+                                              pos, ele,next_index_++);
 #else
-  AtomImplPtr ap(new AtomImpl(shared_from_this(), rp, name, pos, prop,next_index_++));
+  AtomImplPtr ap(new AtomImpl(shared_from_this(), rp, name, pos, ele, next_index_++));
 #endif
   if (identity_transf_ == false) {
     geom::Vec3 transformed_pos = geom::Vec3(transformation_matrix_*geom::Vec4(pos));
@@ -1198,4 +1198,11 @@ void EntityImpl::SetName(const String& ent_name){
   name_=ent_name;
 }
 
+void EntityImpl::ReorderAllResidues()
+{
+  for(ChainImplList::iterator cit=chain_list_.begin();cit!=chain_list_.end();++cit) {
+    (*cit)->ReorderResidues();
+  }
+}
+
 }}} // ns
diff --git a/modules/mol/base/src/impl/entity_impl.hh b/modules/mol/base/src/impl/entity_impl.hh
index 1dd0c21da30b21d60c6b413d112ab8d9b2bf68b6..3c6579452c32e2ccf5d03bd5bb0fb4c4c06f5751 100644
--- a/modules/mol/base/src/impl/entity_impl.hh
+++ b/modules/mol/base/src/impl/entity_impl.hh
@@ -101,7 +101,7 @@ public:
 
   // default copy ctor and assignment op should work for now
   AtomImplPtr CreateAtom(const ResidueImplPtr& rp, const String& name,
-                       const geom::Vec3& pos, const AtomProp& prop);
+                         const geom::Vec3& pos, const String& ele);
 
   ResidueImplPtr CreateResidue(const ChainImplPtr& cp,
                                const ResNum& n,
@@ -246,6 +246,8 @@ public:
   pointer_it<ChainImplPtr> GetChainIter(const String& name);
   void SetName(const String& ent_name);
 
+  void ReorderAllResidues();
+
 private:
   void DoCopy(EntityImplPtr dest);
   
diff --git a/modules/mol/base/src/impl/query_impl.cc b/modules/mol/base/src/impl/query_impl.cc
index 92b00434666358db3197e01463020751976de0c5..d801f68ab8c72782b813f38a7acd7b64c9ef346c 100644
--- a/modules/mol/base/src/impl/query_impl.cc
+++ b/modules/mol/base/src/impl/query_impl.cc
@@ -434,6 +434,7 @@ bool QueryImpl::ParseValue(const Prop& sel, const QueryToken& op,
       if (sel.type==Prop::INT) {
         // todo. Add check to test that the comparison operator is only one of
         // = and !=. The others don't make too much sense.
+
         if (value_string=="true" || value_string=="True" || 
             value_string=="TRUE") {
           value=ParamType(int(1));
@@ -444,11 +445,19 @@ bool QueryImpl::ParseValue(const Prop& sel, const QueryToken& op,
           break;
         }
       }
+      // yes, not having a break here is on purpose
     case tok::String:      
       if (sel.type!=Prop::STRING) {
-        error_desc_.msg="'"+sel.GetName()+"' takes "+sel.GetTypeName()+
-                       " argument, but String literal given";
-        error_desc_.range=v.GetValueRange();
+        if (sel.id>=Prop::CUSTOM) {
+          // BZDNG-204: issue specific warning when trying to use a string value 
+          //     for a generic property.
+          error_desc_.msg="only numeric generic properties can be used in queries";
+          error_desc_.range=v.GetValueRange();
+        } else {
+          error_desc_.msg="'"+sel.GetName()+"' takes "+sel.GetTypeName()+
+                         " argument, but string literal given";
+          error_desc_.range=v.GetValueRange();
+        }
         return false;
       } else {
         value=value_string;
@@ -662,7 +671,19 @@ Node* QueryImpl::ParsePropValueExpr(QueryLexer& lexer) {
     GenProp gen_prop(epm);
     if (op.GetType()==tok::Colon) {
       op=lexer.NextToken();
-      if (!this->ExpectNumeric(op)) {
+      if (!this->ExpectNotEnd(op, "value")) {
+        return NULL;
+      }
+      if (tok::FloatingValue!=op.GetType() && 
+          tok::IntegralValue!=op.GetType()) {
+        // BZDNG-204: issue specific warning when trying to use a string value 
+        //     for a generic property. 
+        if (op.GetType()==tok::String || op.GetType()==tok::Identifier) {
+          error_desc_.msg="only numeric generic properties are supported in queries";
+          error_desc_.range=op.GetValueRange();
+          return NULL;
+        }
+        this->ExpectNumeric(op);
         return NULL;
       }
       gen_prop.default_val=atof(query_string_.substr(op.GetValueRange().Loc,
@@ -957,9 +978,10 @@ bool QueryImpl::ExpectNumeric(const QueryToken& token)
                            token.GetRange().Length)+"' found";
     error_desc_.range=token.GetRange();    
   }
-  return false;  
+  return false;
 }
 
+
 Node* QueryImpl::Concatenate(Node* lhs, Node* rhs, LogicOP logical_op) {
   assert(lhs && "lhs is NULL");
   assert(rhs && "rhs is NULL");
diff --git a/modules/mol/base/src/impl/residue_impl.cc b/modules/mol/base/src/impl/residue_impl.cc
index b997ced3f5ee1e88fb833cec5236d7d0c0702e57..6d0856b111c071316e4604b7c6d9a18d1c953085 100644
--- a/modules/mol/base/src/impl/residue_impl.cc
+++ b/modules/mol/base/src/impl/residue_impl.cc
@@ -42,15 +42,18 @@ ResidueImpl::ResidueImpl(const EntityImplPtr& ent,
   key_(key),
   atom_list_(),
   sec_structure_(SecStructure::COIL),
-  olc_('?')
-{}
+  olc_('?'),
+  protein_(false), ligand_(false)
+{
+}
 
 
 AtomImplPtr ResidueImpl::InsertAtom(const String& name,
-                                  const geom::Vec3& pos,
-                                  const AtomProp& prop)
+                                    const geom::Vec3& pos,
+                                    const String& ele)
 {
-  AtomImplPtr ap=ent_.lock()->CreateAtom(shared_from_this(),name, pos, prop);
+  AtomImplPtr ap=ent_.lock()->CreateAtom(shared_from_this(),
+                                         name, pos, ele);
   atom_list_.push_back(ap);
   return ap;
 }
@@ -59,9 +62,20 @@ AtomImplPtr ResidueImpl::InsertAtom(const AtomImplPtr& atom)
 {
   AtomImplPtr dst_atom=this->InsertAtom(atom->GetName(), 
                                         atom->GetPos(),
-                                        atom->GetAtomProps());
+                                        atom->GetElement());
+
   dst_atom->Assign(*atom.get());
   dst_atom->SetState(atom->GetState());
+  dst_atom->SetBFactor(atom->GetBFactor());
+  dst_atom->SetOccupancy(atom->GetOccupancy());
+  dst_atom->SetHetAtom(atom->IsHetAtom());  
+
+  if (!atom->HasDefaultProps()) {
+    dst_atom->SetRadius(atom->GetRadius());
+    dst_atom->SetCharge(atom->GetCharge());
+    dst_atom->SetMass(atom->GetMass());
+    dst_atom->SetAnisou(atom->GetAnisou());
+  }
   return dst_atom;
 }
 
@@ -70,7 +84,7 @@ Real ResidueImpl::GetAverageBFactor() const
   Real sum=0;
   for (AtomImplList::const_iterator i=atom_list_.begin(), 
        e=atom_list_.end(); i!=e; ++i) {
-    sum+=(*i)->GetAtomProps().b_factor;
+    sum+=(*i)->GetBFactor();
   }
   return atom_list_.size()>0 ? sum/atom_list_.size() : 0.0;
 }
@@ -115,8 +129,8 @@ geom::Vec3 ResidueImpl::GetAltAtomPos(const AtomImplPtr& atom,
 AtomImplPtr ResidueImpl::InsertAltAtom(const String& name,
                                        const String& alt_group,
                                        const geom::Vec3& pos,
-                                       const AtomProp& prop) {
-  AtomImplPtr atom=this->InsertAtom(name, pos, prop);
+                                       const String& ele) {
+  AtomImplPtr atom=this->InsertAtom(name, pos, ele);
   this->AddAltAtom(alt_group, atom, pos);
   return atom;
 }
@@ -198,24 +212,28 @@ ChainImplPtr ResidueImpl::GetChain() const
 
 geom::Vec3 ResidueImpl::GetCentralNormal() const
 {
+  geom::Vec3 nrvo(1,0,0);
   if (chem_class_.IsPeptideLinking()) {
     AtomImplPtr a1 = FindAtom("C");
     AtomImplPtr a2 = FindAtom("O"); 
-    geom::Vec3 nrvo;
     if(a1 && a2) {
-      nrvo = geom::Normalize(a1->GetPos()-a2->GetPos());
+      nrvo = geom::Normalize(a2->GetPos()-a1->GetPos());
     } else {
-      geom::Vec3 v0=GetCentralAtom()->GetPos();
-      nrvo=geom::Cross(geom::Normalize(v0),
-                       geom::Normalize(geom::Vec3(-v0[2],v0[0],v0[1])));
-      LOG_VERBOSE("warning: could not find atoms for proper central normal calculation");
+      a1 = FindAtom("CB");
+      a2 = FindAtom("CA"); 
+      if(a1 && a2) {
+        nrvo = geom::Normalize(a2->GetPos()-a1->GetPos());
+      } else {
+        geom::Vec3 v0=GetCentralAtom()->GetPos();
+        nrvo=geom::Cross(geom::Normalize(v0),
+                         geom::Normalize(geom::Vec3(-v0[2],v0[0],v0[1])));
+        LOG_VERBOSE("warning: could not find atoms for proper central normal calculation");
+      }
     }
-    return nrvo;    
   } else if (chem_class_.IsNucleotideLinking()) {
     AtomImplPtr a1 = FindAtom("P");
     AtomImplPtr a2 = FindAtom("OP1");
     AtomImplPtr a3 = FindAtom("OP2");
-    geom::Vec3 nrvo;
     if(a1 && a2 && a3) {
       nrvo = geom::Normalize(a1->GetPos()-(a2->GetPos()+a3->GetPos())*.5);
     } else {
@@ -224,9 +242,8 @@ geom::Vec3 ResidueImpl::GetCentralNormal() const
                        geom::Normalize(geom::Vec3(-v0[2],v0[0],v0[1])));
       LOG_VERBOSE("warning: could not find atoms for proper central normal calculation");
     }
-    return nrvo;
   }
-  return geom::Vec3();
+  return nrvo;
 }
 
 
@@ -376,7 +393,7 @@ void ResidueImpl::DeleteAllAtoms() {
 
 String ResidueImpl::GetQualifiedName() const {
   String chain_name=this->GetChain()->GetName();
-  return (chain_name==" " ? "" :  chain_name+".")+
+  return ((chain_name==" " || chain_name=="") ? "" :  chain_name+".")+
          this->GetKey()+
          this->GetNumber().AsString();
 }
@@ -422,7 +439,7 @@ Real ResidueImpl::GetMass() const
   Real mass = 0;
   for (AtomImplList::const_iterator i=atom_list_.begin(); 
        i!=atom_list_.end(); ++i) {
-    mass+=(*i)->GetAtomProps().mass;
+    mass+=(*i)->GetMass();
   }
   return mass;
 }
@@ -466,7 +483,7 @@ geom::Vec3 ResidueImpl::GetCenterOfMass() const
   if (this->GetAtomCount() > 0 && mass > 0) {
     for (AtomImplList::const_iterator i=atom_list_.begin(); 
         i!=atom_list_.end(); ++i) {
-      center+=(*i)->GetPos()*(*i)->GetAtomProps().mass;
+      center+=(*i)->GetPos()*(*i)->GetMass();
     }
   }
   return center/mass;
diff --git a/modules/mol/base/src/impl/residue_impl.hh b/modules/mol/base/src/impl/residue_impl.hh
index 183a9ccefe8c5025f2790109b0ab3d26acfc17f8..925204982bcd1ecaabf08e7ef3e1f7479073fd41 100644
--- a/modules/mol/base/src/impl/residue_impl.hh
+++ b/modules/mol/base/src/impl/residue_impl.hh
@@ -51,13 +51,13 @@ public:
   ResidueImpl(const EntityImplPtr& ent, const ChainImplPtr& ch,
               const ResNum& num, const ResidueKey& key);
 
-  AtomImplPtr InsertAtom(const String& name, const geom::Vec3& pos,
-                         const AtomProp& prop);
+  AtomImplPtr InsertAtom(const String& name, const geom::Vec3& pos, 
+                         const String& ele);
   /// \brief insert new residue with exactly the same parameters as atom, but 
   ///     no bonds
   AtomImplPtr InsertAtom(const AtomImplPtr& atom);
   AtomImplPtr InsertAltAtom(const String& name, const String& alt_group,
-                           const geom::Vec3& pos, const AtomProp& prop);
+                           const geom::Vec3& pos, const String& ele);
   const ResNum& GetNumber() const {return num_;}
   void SetNumber(const ResNum& num) {num_=num;}
 
@@ -202,6 +202,9 @@ public:
   void SetProtein(bool protein) { protein_=protein; }
   
   bool IsProtein() const { return protein_; }
+  
+  bool IsLigand() const { return ligand_; }
+  void SetIsLigand(bool flag) { ligand_=flag; }
 private:
   void AddAltAtom(const String& group, const AtomImplPtr& atom,
                   const geom::Vec3& position);
@@ -219,6 +222,7 @@ private:
   char                       olc_;
   // whether the residue is part of the protein.
   bool                       protein_;
+  bool                       ligand_;
 };
 
 }}} // ns
diff --git a/modules/mol/base/src/property_id.cc b/modules/mol/base/src/property_id.cc
index a6408b83e97407a26060faac0824dc0659403493..0ce93195b8d8fcb0a8bf41752661381705b5be44 100644
--- a/modules/mol/base/src/property_id.cc
+++ b/modules/mol/base/src/property_id.cc
@@ -51,6 +51,7 @@ struct Properties : public boost::spirit::symbols<Prop> {
       ("peptide", Prop(Prop::PEPTIDE, Prop::INT, Prop::RESIDUE))
       ("rindex", Prop(Prop::RINDEX, Prop::INT, Prop::RESIDUE))
       ("protein", Prop(Prop::PROTEIN, Prop::INT, Prop::RESIDUE))
+      ("ligand", Prop(Prop::LIGAND, Prop::INT, Prop::RESIDUE))
       ("water", Prop(Prop::WATER, Prop::INT, Prop::RESIDUE))
       ("acharge", Prop(Prop::ACHARGE, Prop::FLOAT, Prop::ATOM));
   }
@@ -116,6 +117,8 @@ String Prop::GetName() const
       return "rindex";
     case PROTEIN:
       return "protein";
+    case LIGAND:
+      return "ligand";
     case WATER:
       return "water";
     default:
@@ -128,7 +131,7 @@ String Prop::GetTypeName() const
 
   switch(type) {
     case Prop::STRING:
-      return "String";
+      return "string";
     case Prop::FLOAT:
       return "floating point";
     case Prop::INT:
diff --git a/modules/mol/base/src/property_id.hh b/modules/mol/base/src/property_id.hh
index 4ea4be13fc66c96512edfca18169967602f747da..f8a541ce75798e1c2e143414dae09d6ac154db9c 100644
--- a/modules/mol/base/src/property_id.hh
+++ b/modules/mol/base/src/property_id.hh
@@ -40,7 +40,7 @@ public:
   /// respectively.
   typedef enum {
     RNAME, ANAME, CNAME, ELE, RNUM, ANUM, AX, AY, AZ, OCC, RTYPE, ISHETATM,
-    RBFAC, ABFAC, PEPTIDE, ACHARGE, RINDEX, PROTEIN, WATER, WITHIN, 
+    RBFAC, ABFAC, PEPTIDE, ACHARGE, RINDEX, PROTEIN, LIGAND, WATER, WITHIN, 
     UNDEF, CUSTOM
   } ID;
   
diff --git a/modules/mol/base/src/query_state.cc b/modules/mol/base/src/query_state.cc
index 95dc07e16ef138132fc9b8a43c93c23061e994ee..5df2d900b8b95c428e03d4a30b58e03ee2f68281 100644
--- a/modules/mol/base/src/query_state.cc
+++ b/modules/mol/base/src/query_state.cc
@@ -217,6 +217,10 @@ boost::logic::tribool QueryState::EvalResidue(const impl::ResidueImplPtr& r) {
         int_value=r->GetChemClass().IsWater();
         s_[*i]=cmp_num<int>(ss.comp_op,int_value,boost::get<int>(ss.param));
         break;
+      case Prop::LIGAND:
+        int_value=r->IsLigand();
+        s_[*i]=cmp_num<int>(ss.comp_op,int_value,boost::get<int>(ss.param));
+        break;        
       case Prop::RTYPE:
         p=boost::get<String>(ss.param);
         if (p.length()>1) {
@@ -334,17 +338,17 @@ boost::logic::tribool QueryState::EvalAtom(const impl::AtomImplPtr& a) {
                                boost::get<float>(ss.param));
         break;                
       case Prop::OCC:
-        float_value=a->GetAtomProps().occupancy;
+        float_value=a->GetOccupancy();
         s_[*i]=cmp_num<Real>(ss.comp_op, float_value, 
                                boost::get<float>(ss.param));
         break;                        
       case Prop::ELE:
-        str_value = a->GetAtomProps().element;
+        str_value = a->GetElement();
         s_[*i] = cmp_string(ss.comp_op,str_value,
           boost::get<String>(ss.param));                          
         break;
       case Prop::ABFAC:
-        float_value=a->GetAtomProps().b_factor;
+        float_value=a->GetBFactor();
         s_[*i]=cmp_num<Real>(ss.comp_op, float_value, 
                               boost::get<float>(ss.param));
         break;
@@ -354,11 +358,11 @@ boost::logic::tribool QueryState::EvalAtom(const impl::AtomImplPtr& a) {
                                 ss.comp_op);
         break;
       case Prop::ISHETATM:
-        int_value = a->GetAtomProps().is_hetatm;
+        int_value = a->IsHetAtom();
         s_[*i] = cmp_num<int>(ss.comp_op,int_value,boost::get<int>(ss.param));
         break;
       case Prop::ACHARGE:
-        float_value=a->GetAtomProps().charge;
+        float_value=a->GetCharge();
         s_[*i]=cmp_num<Real>(ss.comp_op, float_value, 
                               boost::get<float>(ss.param));
         break;
diff --git a/modules/mol/base/src/query_view_wrapper.cc b/modules/mol/base/src/query_view_wrapper.cc
index 5774b1cfb501b62f6870653805fcfe6975a0a718..65156645865c45bf2d497f3d66e6aa710f23169d 100644
--- a/modules/mol/base/src/query_view_wrapper.cc
+++ b/modules/mol/base/src/query_view_wrapper.cc
@@ -43,22 +43,13 @@ QueryViewWrapper::QueryViewWrapper(const EntityView& entity_view):
     query_(),
     flags_(0){}
 
-QueryViewWrapper::QueryViewWrapper(const Query& query, 
-                                   const EntityHandle& entity_handle):
+QueryViewWrapper::QueryViewWrapper(const Query& query, const EntityHandle& entity_handle):
     view_set_(false),
     entity_handle_(entity_handle),
     entity_view_(),
     query_(query),
     flags_(0){}
 
-QueryViewWrapper::QueryViewWrapper(const Query& query, 
-                                   const EntityView& view):
-    view_set_(true),
-    entity_handle_(),
-    entity_view_(view),
-    query_(query),
-    flags_(0){}
-
 QueryViewWrapper::QueryViewWrapper(const Query& query, QueryFlags flags,
                                    const EntityHandle& entity_handle):
     view_set_(false),
@@ -67,6 +58,13 @@ QueryViewWrapper::QueryViewWrapper(const Query& query, QueryFlags flags,
     query_(query),
     flags_(flags){}
 
+QueryViewWrapper::QueryViewWrapper(const Query& query, const EntityView& view):
+    view_set_(true),
+    entity_handle_(),
+    entity_view_(view),
+    query_(query),
+    flags_(0){}
+
 QueryViewWrapper::QueryViewWrapper(const Query& query, QueryFlags flags,
                                    const EntityView& view):
     view_set_(true),
@@ -87,11 +85,13 @@ EntityView QueryViewWrapper::GetEntityView() const
   }
 }
 
-const Query& QueryViewWrapper::GetQuery() const{
+const Query& QueryViewWrapper::GetQuery() const
+{
   return query_;
 }
 
-void QueryViewWrapper::SetQuery(const Query& query){
+void QueryViewWrapper::SetQuery(const Query& query)
+{
   query_ = query;
 }
 
@@ -114,4 +114,4 @@ bool QueryViewWrapper::DependsOnQuery() const
   return query_.MatchAll();
 }
 
-} } // ns
+}} // ns
diff --git a/modules/mol/base/src/residue_base.cc b/modules/mol/base/src/residue_base.cc
index 9ae05d783a17e7885f3f1b2f8896cdcb1a7894be..f2074c8d352a575cb0fa1142ac35acfd9d448e88 100644
--- a/modules/mol/base/src/residue_base.cc
+++ b/modules/mol/base/src/residue_base.cc
@@ -65,14 +65,6 @@ String ResidueBase::GetQualifiedName() const {
   return impl_->GetQualifiedName();
 }
 
-ResidueBase::operator bool() const {
-  return impl_.get()!=0;
-}
-
-bool ResidueBase::IsValid() const {
-  return impl_.get()!=0;
-}
-
 bool ResidueBase::IsPeptideLinking() const 
 {
   return this->GetChemClass().IsPeptideLinking();
@@ -142,7 +134,7 @@ void ResidueBase::CheckValidity() const
 }
 
 std::ostream& operator<<(std::ostream& os, const ResidueBase& residue) {
-  if (residue.IsValid()) {
+  if (residue.Impl()) {
     os << residue.GetQualifiedName();
   } else {
     os << "invalid residue"; 
@@ -193,5 +185,17 @@ void ResidueBase::SetIsProtein(bool protein)
   Impl()->SetProtein(protein);
 }
 
+void ResidueBase::SetIsLigand(bool ligand)
+{
+  this->CheckValidity();
+  return Impl()->SetIsLigand(ligand);
+}
+
+bool ResidueBase::IsLigand() const
+{
+  this->CheckValidity();
+  return Impl()->IsLigand();
+}
+
 }}
 
diff --git a/modules/mol/base/src/residue_base.hh b/modules/mol/base/src/residue_base.hh
index 1ad7438795fa240422afc912645ab5025c48d50d..92901bf9e56a4c10c14260a55fc01577f53d577f 100644
--- a/modules/mol/base/src/residue_base.hh
+++ b/modules/mol/base/src/residue_base.hh
@@ -63,6 +63,19 @@ public:
   ResidueBase(const impl::ResidueImplPtr& impl);
   ResidueBase(const ResidueBase& rhs);
 public:
+  
+  /// \name Handle validity
+  //@{
+  /// \brief check validity of handle
+  ///
+  /// check, whether the residue handle points to a valid residue.
+  /// \note It is an error to use any method other than #IsValid, #Impl and
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return Impl().get()!=0; }
   friend class ConstGenericPropContainer<ResidueBase>;
   /// \brief return residue number
   const ResNum& GetNumber() const;
@@ -77,20 +90,7 @@ public:
   ///         residue name and residue number
   String GetQualifiedName() const;
 
-  /// \name Handle validity
-  //@{
-  /// \brief check validity of handle
-  ///
-  /// check, whether the residue handle points to a valid residue.
-  /// \note It is an error to use any method other than #IsValid, #Impl and
-  ///       #operator bool() when the handle is invalid. An InvalidHandle
-  ///       exception will be thrown.
-  operator bool() const;
-  /// \brief check validity of handle
-  /// \sa #operator bool()
-  bool IsValid() const;
-  //@}
-  
+
   /// \brief whether the residue can form peptide bonds
   bool IsPeptideLinking() const;
 
@@ -144,6 +144,10 @@ public:
   bool IsProtein() const;
   
   void SetIsProtein(bool protein);
+  
+  void SetIsLigand(bool ligand);
+  
+  bool IsLigand() const;
 public:
   impl::ResidueImplPtr& Impl();
 
diff --git a/modules/mol/base/src/residue_handle.hh b/modules/mol/base/src/residue_handle.hh
index f1eb07850185a9b1ea404eeceaedb589e1feff9b..5705f3de8eb6385d8b7397979c4023c421a15c0f 100644
--- a/modules/mol/base/src/residue_handle.hh
+++ b/modules/mol/base/src/residue_handle.hh
@@ -25,7 +25,6 @@
 #include <ost/mol/query.hh>
 #include <ost/mol/module_config.hh>
 #include <ost/mol/residue_base.hh>
-#include <ost/mol/atom_prop.hh>
 #include <ost/mol/entity_visitor_fw.hh>
 #include <ost/mol/iterator_fw.hh>
 
@@ -50,13 +49,14 @@ namespace ost { namespace mol {
 /// EditorBase::InsertAtom() or EditorBase::InsertAltAtom()
 /// 
 /// \code
-/// XCSEditor edi=residue.GetEntity().RequestXCSEditor();
+/// XCSEditor edi=residue.GetEntity().EditXCS();
 /// edi.InsertAtom(residue, "CA", geom.Vec3(1.0, 0.0, 0.0));
 /// \endcode
 class DLLEXPORT_OST_MOL ResidueHandle : public ResidueBase {
 public:
   ResidueHandle();
 
+  //@}
   ResidueHandle(const impl::ResidueImplPtr& impl)
     : ResidueBase(impl) {}
   EntityHandle GetEntity() const;
diff --git a/modules/mol/base/src/residue_prop.cc b/modules/mol/base/src/residue_prop.cc
deleted file mode 100644
index 3712bfe0b901e55bf67b8492406e96d231b4ac87..0000000000000000000000000000000000000000
--- a/modules/mol/base/src/residue_prop.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-//------------------------------------------------------------------------------
-// This file is part of the OpenStructure project <www.openstructure.org>
-//
-// Copyright (C) 2008-2010 by the OpenStructure authors
-//
-// This library 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 3.0 of the License, or (at your option)
-// any later version.
-// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-//------------------------------------------------------------------------------
-#include "residue_prop.hh"
-#include <boost/format.hpp>
-
-namespace ost { namespace mol {
-
-ResNum::ResNum(int n):
-  num_(n), alt_('\0')
-{}
-
-ResNum::ResNum(int n, char a):
-  num_(n), alt_(a)
-{}
-
-bool ResNum::operator==(const ResNum& r) const
-{
-  return num_==r.num_ && alt_==r.alt_;
-}
-
-bool ResNum::operator<(const ResNum& r) const
-{
-  return num_==r.num_ ? alt_<r.alt_ : num_<r.num_;
-}
-
-int ResNum::operator+=(int i)
-{
-  num_+=i;
-  return num_;
-}
-
-int ResNum::operator-=(int i)
-{
-  num_-=i;
-  return num_;
-}
-
-int ResNum::operator+=(const ResNum& r)
-{
-  num_+=r.num_;
-  return num_;
-}
-
-int ResNum::operator-=(const ResNum& r)
-{
-  num_-=r.num_;
-  return num_;
-}
-
-ResNum& ResNum::operator++()
-{
-  ++num_;
-  return *this;
-}
-
-ResNum& ResNum::operator--()
-{
-  --num_;
-  return *this;
-}
-
-ResNum ResNum::NextInsertionCode() const
-{
-  char alt= alt_=='\0' ? 'a' : alt_+1;
-  ResNum nrvo(num_,alt);
-  return nrvo;
-}
-
-String ResNum::AsString() const {
-  return str(boost::format("%d%s") % num_ % (alt_==0 ? "" : String(1, alt_)));
-}
-
-std::ostream& operator<<(std::ostream& os, const ResNum& n)
-{
-  return os << n.AsString();
-}
-
-
-}} // ns
diff --git a/modules/mol/base/src/residue_prop.hh b/modules/mol/base/src/residue_prop.hh
index 2bb92b3da49032829c360f069d0ea9d76bf64296..001660fa02d7b27494ee3b70586d6fd640c46af8 100644
--- a/modules/mol/base/src/residue_prop.hh
+++ b/modules/mol/base/src/residue_prop.hh
@@ -25,48 +25,112 @@
 
 namespace ost { namespace mol {
 
-/*
-  
-*/
-class DLLEXPORT_OST_MOL ResNum: private
+
+class DLLEXPORT ResNum: private
     boost::additive<ResNum, int,
     boost::totally_ordered<ResNum, 
     boost::totally_ordered<ResNum, int,
     boost::unit_steppable<ResNum> > > >
 {
 public:
-  ResNum(int num); // no explicit on purpose
-  ResNum(int num, char alt);
-
-  bool operator==(const ResNum&) const;
-  bool operator<(const ResNum&) const;
-  int operator+=(int);
-  int operator-=(int);
-  int operator+=(const ResNum&);
-  int operator-=(const ResNum&);
-  ResNum& operator++();
-  ResNum& operator--();
-
-  ResNum NextInsertionCode() const;
-
-  int GetNum() const {return num_;}
-  char GetInsCode() const {return alt_;}
+  ResNum(int n):
+    num_(n), alt_('\0')
+  { }
+
+  ResNum(int n, char a):
+    num_(n), alt_(a)
+  {}
+
+  bool operator==(const ResNum& r) const
+  {
+    return num_==r.num_ && alt_==r.alt_;
+  }
+
+  bool operator<(const ResNum& r) const
+  {
+    return num_==r.num_ ? alt_<r.alt_ : num_<r.num_;
+  }
+
+  int operator+=(int i)
+  {
+    num_+=i;
+    return num_;
+  }
+
+  int operator-=(int i)
+  {
+    num_-=i;
+    return num_;
+  }
+
+  int operator+=(const ResNum& r)
+  {
+    num_+=r.num_;
+    return num_;
+  }
+
+  int operator-=(const ResNum& r)
+  {
+    num_-=r.num_;
+    return num_;
+  }
+
+  ResNum& operator++()
+  {
+    ++num_;
+    return *this;
+  }
+
+  ResNum& operator--()
+  {
+    --num_;
+    return *this;
+  }
+
+  ResNum NextInsertionCode() const
+  {
+    char alt= alt_=='\0' ? 'a' : alt_+1;
+    ResNum nrvo(num_,alt);
+    return nrvo;
+  }
   
   /// \brief get residue number as String
   ///
   /// The returned String consists of both the numeric residue sequence number
   /// and the insertion code. If the insertion code is not defined, i.e. is 
   /// equal to the null character, only the residue sequence number is returned.
-  String AsString() const;
+  inline String AsString() const;
+  
+  int GetNum() const { return num_; }
+  
+  void SetNum(int num) { num_=num; }
+  
+  void SetInsCode(char ins_code) { alt_=ins_code; }
+  
+  char GetInsCode() const { return alt_; }  
+  
 private:
-  int num_;
-  char alt_;
+  int num_ : 24;
+  int alt_ :  8;
 };
 
-DLLEXPORT_OST_MOL std::ostream& operator<<(std::ostream& os, const ResNum& n);
-
 typedef String ResidueKey;
 
+inline std::ostream& operator<<(std::ostream& os, const ResNum& n)
+{
+  return os << n.GetNum();
+  if (n.GetInsCode()!='\0')
+    os << n.GetInsCode();
+  return os;
+}
+
+inline String ResNum::AsString() const
+{
+  std::stringstream ss;
+  ss << *this;
+  return ss.str();    
+}
+
 }} // ns
 
 
diff --git a/modules/mol/base/src/residue_view.cc b/modules/mol/base/src/residue_view.cc
index 53e0a3eaa79126ebbd6095a3c69719196a8d6c09..2fef9c9432c1f172b997df6f92c56f24b21e3f4a 100644
--- a/modules/mol/base/src/residue_view.cc
+++ b/modules/mol/base/src/residue_view.cc
@@ -138,7 +138,10 @@ const AtomViewList& ResidueView::GetAtomList() const {
 
 ChainView ResidueView::GetChain() const {
   this->CheckValidity();
-  return ChainView(data_->chain.lock(), Impl()->GetChain());
+  if (!data_->chain.expired()) {
+    return ChainView(data_->chain.lock(), Impl()->GetChain());
+  }
+  throw InvalidHandle();
 }
 
 
@@ -200,7 +203,7 @@ double ResidueView::GetMass() const
   double mass = 0;
   AtomViewList::const_iterator i;
   for (i=data_->atoms.begin(); i!=data_->atoms.end(); ++i) {
-    mass+=(*i).GetAtomProps().mass;
+    mass+=(*i).GetMass();
   }
   return mass;
 }
@@ -226,7 +229,7 @@ geom::Vec3 ResidueView::GetCenterOfMass() const
   if (!data_->atoms.empty() && mass > 0) {
     AtomViewList::const_iterator i;
     for (i=data_->atoms.begin(); i!=data_->atoms.end(); ++i) {
-      center+=(*i).GetPos()*(*i).GetAtomProps().mass;
+      center+=(*i).GetPos()*(*i).GetMass();
     }
       center/=mass;
   }
diff --git a/modules/mol/base/src/residue_view.hh b/modules/mol/base/src/residue_view.hh
index d771a95ce09a0ba448eaca0be2a391e53020ecdd..2f56f015cf3daacde5e214f6bfa2c24168c16cc9 100644
--- a/modules/mol/base/src/residue_view.hh
+++ b/modules/mol/base/src/residue_view.hh
@@ -53,6 +53,21 @@ public:
               const ResidueHandle&  residue);
 
 public:
+  
+  /// \name Handle validity
+  //@{
+  /// \brief check validity of view
+  ///
+  /// check, whether the residue view points to a valid residue.
+  /// \note It is an error to use any method other than #IsValid, #Impl and
+  ///       #operator bool() when the handle is invalid. An InvalidHandle
+  ///       exception will be thrown.
+  operator bool() const { return this->IsValid(); }
+  /// \brief check validity of handle
+  /// \sa #operator bool()
+  bool IsValid() const { return data_.get()!=0; }
+  //@}
+  
   /// \name internal
   //@{
   /// \brief construct new view from view data and impl.
diff --git a/modules/mol/base/src/surface_builder.cc b/modules/mol/base/src/surface_builder.cc
index ecd26cab22423b1c19339ce33fe2cc17bcfbb4af..3be39406778bade182728da22802672862db3fcf 100644
--- a/modules/mol/base/src/surface_builder.cc
+++ b/modules/mol/base/src/surface_builder.cc
@@ -22,7 +22,6 @@
 
 #include "surface_handle.hh"
 #include "entity_view.hh"
-#include "iterator.hh"
 
 namespace ost { namespace mol {
 
diff --git a/modules/mol/base/src/surface_handle.cc b/modules/mol/base/src/surface_handle.cc
index 6d1e82e643e3ff36d5d2a4d78803bb3ed42eb29a..e1169a3268793c19e0e7da171acf995b59f1fcf9 100644
--- a/modules/mol/base/src/surface_handle.cc
+++ b/modules/mol/base/src/surface_handle.cc
@@ -88,4 +88,14 @@ void SurfaceHandle::Invert()
   impl_->Invert();
 }
 
+std::ostream& operator<<(std::ostream& os, const SurfaceHandle& surf)
+{
+  if (surf.IsValid()) {
+    os << "valid surface";
+  } else {
+    os << "invalid surface";
+  }
+  return os;
+}
+
 }} // ns
diff --git a/modules/mol/base/src/surface_handle.hh b/modules/mol/base/src/surface_handle.hh
index e57b0095a2e869cdf9d3b1eb27839d9df99b6bab..a5e3eed9013a2f69194d6d0a218c73b2d565d514 100644
--- a/modules/mol/base/src/surface_handle.hh
+++ b/modules/mol/base/src/surface_handle.hh
@@ -72,10 +72,20 @@ public:
 
   bool IsValid() const {return impl_;}
 
+  bool operator==(const SurfaceHandle& ref) const { return impl_==ref.impl_; }
+
+  bool operator!=(const SurfaceHandle& ref) const { return !this->operator==(ref); }
+
 private:
   impl::SurfaceImplP impl_;
+
 };
 
+DLLEXPORT_OST_MOL std::ostream& operator<<(std::ostream& os,
+                                           const SurfaceHandle& surf);
+
+typedef std::vector<SurfaceHandle> SurfaceHandleList;
+
 }} // ns
 
 #endif
diff --git a/modules/mol/base/src/torsion_handle.hh b/modules/mol/base/src/torsion_handle.hh
index ff0d8be70f360f9113efb4422e9f60c38066d30f..44da2a44ce5ae14027947d32f4695b66b48329de 100644
--- a/modules/mol/base/src/torsion_handle.hh
+++ b/modules/mol/base/src/torsion_handle.hh
@@ -102,6 +102,10 @@ public:
   impl::TorsionImplP& Impl() {
     return impl_;
   }
+  
+  const impl::TorsionImplP& Impl() const {
+    return impl_;
+  }
 protected:
     void CheckValidity() const; 
 private:
diff --git a/modules/mol/base/tests/CMakeLists.txt b/modules/mol/base/tests/CMakeLists.txt
index 7d57b01e3e128f793c5204620d65f8057d2e919c..b29f1128e67b23fae8b469437195fb80a40b7cbe 100644
--- a/modules/mol/base/tests/CMakeLists.txt
+++ b/modules/mol/base/tests/CMakeLists.txt
@@ -8,6 +8,7 @@ set(OST_MOL_BASE_UNIT_TESTS
   test_ics.cc
   test_iterators.cc
   test_query.cc
+  test_surface.cc
   test_residue.cc
   test_view.cc
   test_view_op.cc
diff --git a/modules/mol/base/tests/dummy_ent.hh b/modules/mol/base/tests/dummy_ent.hh
index c4689027302ae8c21ab863058134c6e7e6f376d9..8e00291764489e2afc301f82dc88c4767e5a0413 100644
--- a/modules/mol/base/tests/dummy_ent.hh
+++ b/modules/mol/base/tests/dummy_ent.hh
@@ -28,7 +28,7 @@ namespace ost { namespace test {
 struct DummyEnt {
   DummyEnt() {
     e=CreateEntity();
-    XCSEditor editor=e.RequestXCSEditor();
+    XCSEditor editor=e.EditXCS();
     c=editor.InsertChain("A");
     r=editor.AppendResidue(c, "XXX");
     aa=editor.InsertAtom(r, "A", geom::Vec3());
diff --git a/modules/mol/base/tests/test_atom_groups.cc b/modules/mol/base/tests/test_atom_groups.cc
index 72835fa76d4f441c8cb407fbb769e81488004c84..b1ed9118e4a1ef910ab800c6ddf9f1db369cd27e 100644
--- a/modules/mol/base/tests/test_atom_groups.cc
+++ b/modules/mol/base/tests/test_atom_groups.cc
@@ -37,10 +37,10 @@ BOOST_AUTO_TEST_CASE(switch_pos)
   geom::Vec3 y=geom::Vec3(0.0, 1.0, 0.0);
   geom::Vec3 z=geom::Vec3(0.0, 0.0, 1.0);  
   // Should throw, since aa has no alt-location set.
-  XCSEditor editor=ent.e.RequestXCSEditor();  
+  XCSEditor editor=ent.e.EditXCS();  
   BOOST_CHECK_THROW(editor.AddAltAtomPos("B", ent.aa, y),
                     Error);
-  AtomHandle xx=editor.InsertAltAtom(ent.r, "ZZ", "A", y, AtomProp()); 
+  AtomHandle xx=editor.InsertAltAtom(ent.r, "ZZ", "A", y); 
   BOOST_CHECK_NO_THROW(editor.AddAltAtomPos("B", xx, z));
   BOOST_CHECK_EQUAL(ent.r.GetCurrentAltGroupName(), "A");
   BOOST_CHECK(ent.r.SwitchAtomPos("B"));
@@ -55,11 +55,9 @@ BOOST_AUTO_TEST_CASE(switch_pos)
 BOOST_AUTO_TEST_CASE(delete_atom) 
 {
   test::DummyEnt ent;
-  XCSEditor editor=ent.e.RequestXCSEditor();       
-  AtomHandle xx=editor.InsertAltAtom(ent.r, "ZZ", "A", geom::Vec3(), 
-                                     AtomProp());
-  AtomHandle zz=editor.InsertAltAtom(ent.r, "XX", "A", geom::Vec3(), 
-                                     AtomProp());
+  XCSEditor editor=ent.e.EditXCS();       
+  AtomHandle xx=editor.InsertAltAtom(ent.r, "ZZ", "A", geom::Vec3());
+  AtomHandle zz=editor.InsertAltAtom(ent.r, "XX", "A", geom::Vec3());
   
   editor.AddAltAtomPos("B", xx, geom::Vec3());
   editor.AddAltAtomPos("B", zz, geom::Vec3());
@@ -77,9 +75,8 @@ BOOST_AUTO_TEST_CASE(atom_group_triv)
   BOOST_CHECK(ent.r.HasAltAtomGroup("")==false);
   std::vector<String> names=ent.r.GetAltAtomGroupNames();
   BOOST_CHECK(names.empty());
-  XCSEditor editor=ent.e.RequestXCSEditor();
-  AtomHandle xx=editor.InsertAltAtom(ent.r, "A", "ZZ", geom::Vec3(0.0,1.0,0.0), 
-                                     AtomProp());   
+  XCSEditor editor=ent.e.EditXCS();
+  AtomHandle xx=editor.InsertAltAtom(ent.r, "A", "ZZ", geom::Vec3(0.0,1.0,0.0));   
   editor.AddAltAtomPos("B", xx, geom::Vec3(1.0, 0.0, 0.0));
   BOOST_CHECK(ent.r.HasAltAtoms()==true);
   BOOST_CHECK(ent.r.HasAltAtomGroup("B")==true);
diff --git a/modules/mol/base/tests/test_chain.cc b/modules/mol/base/tests/test_chain.cc
index e03c588a5b0a83ed7b959d02e99e8b386b0381f4..f43b9f2fffde39226dcc75ab606d21958a609354 100644
--- a/modules/mol/base/tests/test_chain.cc
+++ b/modules/mol/base/tests/test_chain.cc
@@ -46,7 +46,7 @@ void no_find_res(ChainHandle chain, const ResNum& n) {
 
 void test_res_pos() {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle ch1=e.InsertChain("A");
   e.AppendResidue(ch1, "A");
   e.AppendResidue(ch1, "B");
@@ -76,7 +76,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(test_comparison) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle ch1=e.InsertChain("A");
   ChainHandle ch2=e.InsertChain("B");
   ChainHandle cc=ch1;
@@ -86,10 +86,33 @@ BOOST_AUTO_TEST_CASE(test_comparison)
 }
 
 
+BOOST_AUTO_TEST_CASE(throw_invalid_chain_handle)
+{
+  EntityHandle ent=CreateEntity();
+  ChainHandle chain=ent.FindChain("A");
+  BOOST_CHECK_THROW(CheckHandleValidity(chain), InvalidHandle);
+  XCSEditor edi=ent.EditXCS();
+  edi.InsertChain("A");
+  chain=ent.FindChain("A");
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(chain));
+}
+
+BOOST_AUTO_TEST_CASE(throw_invalid_chain_view)
+{
+  EntityHandle ent=CreateEntity();
+  ChainHandle chain=ent.FindChain("A");
+  ChainView chain_view;
+  BOOST_CHECK_THROW(CheckHandleValidity(chain_view), InvalidHandle);
+  XCSEditor edi=ent.EditXCS();
+  edi.InsertChain("A");
+  EntityView ent_view=ent.CreateFullView();  
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(ent_view.FindChain("A")));
+}
+
 BOOST_AUTO_TEST_CASE(res_pos) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle ch1=e.InsertChain("A");
   e.AppendResidue(ch1, "A");
   e.AppendResidue(ch1, "B");
@@ -118,7 +141,7 @@ BOOST_AUTO_TEST_CASE(res_pos)
 BOOST_AUTO_TEST_CASE(res_pos_with_insertion_code) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle ch1=e.InsertChain("A");
   e.AppendResidue(ch1, "A");
   e.AppendResidue(ch1, "B");
@@ -148,7 +171,7 @@ BOOST_AUTO_TEST_CASE(res_pos_with_insertion_code)
 BOOST_AUTO_TEST_CASE(prev_next) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle ch1=e.InsertChain("A");
   e.AppendResidue(ch1, "A");
   e.AppendResidue(ch1, "B");
diff --git a/modules/mol/base/tests/test_conn.cc b/modules/mol/base/tests/test_conn.cc
index b36e5f754e453cba393920adc8c0852b81059b84..0c81d6900611ee77b826af1faaa74d7808a3fa9a 100644
--- a/modules/mol/base/tests/test_conn.cc
+++ b/modules/mol/base/tests/test_conn.cc
@@ -31,7 +31,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(connect) 
 {
   EntityHandle e=CreateEntity();
-  XCSEditor editor=e.RequestXCSEditor();  
+  XCSEditor editor=e.EditXCS();  
   ChainHandle c=editor.InsertChain("A");
   ResidueHandle r=editor.AppendResidue(c, "GLY");
 
diff --git a/modules/mol/base/tests/test_coord_group.cc b/modules/mol/base/tests/test_coord_group.cc
index f2012b9983cd652d373cb68b813fea65cd460aa6..cce3eb4873336242739b2cae689e8d18073a742b 100644
--- a/modules/mol/base/tests/test_coord_group.cc
+++ b/modules/mol/base/tests/test_coord_group.cc
@@ -33,7 +33,7 @@ BOOST_AUTO_TEST_SUITE( io )
 BOOST_AUTO_TEST_CASE(coord_group) 
 {
   EntityHandle e=CreateEntity();
-  XCSEditor editor=e.RequestXCSEditor();  
+  XCSEditor editor=e.EditXCS();  
   ChainHandle c=editor.InsertChain("A");
   ResidueHandle r=editor.AppendResidue(c, "XXX");
   AtomHandle aa=editor.InsertAtom(r, "A", geom::Vec3(0,1,2));
diff --git a/modules/mol/base/tests/test_delete.cc b/modules/mol/base/tests/test_delete.cc
index c117f5d9ae50dfd0d26a41c665627b957d3dd751..56d78f0a016d1671292ad091a849ddd13403871b 100644
--- a/modules/mol/base/tests/test_delete.cc
+++ b/modules/mol/base/tests/test_delete.cc
@@ -42,7 +42,7 @@ public:
 struct Fixture {
   Fixture() {
     e=CreateEntity();
-    XCSEditor editor=e.RequestXCSEditor();    
+    XCSEditor editor=e.EditXCS();    
     c=editor.InsertChain("A");
     r=editor.AppendResidue(c, "XXX");
     aa=editor.InsertAtom(r, "A", geom::Vec3());
@@ -71,7 +71,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(atom_delete) 
 {
   Fixture f;
-  XCSEditor e=f.e.RequestXCSEditor();
+  XCSEditor e=f.e.EditXCS();
   e.DeleteAtom(f.ab);
   E ev;
   BOOST_CHECK_NO_THROW(f.e.Apply(ev));
diff --git a/modules/mol/base/tests/test_entity.cc b/modules/mol/base/tests/test_entity.cc
index 0504422946e34546f0c3dee532bb05de4fbd232a..f4fb9ca01e2dd478c056fe197b6955593692c773 100644
--- a/modules/mol/base/tests/test_entity.cc
+++ b/modules/mol/base/tests/test_entity.cc
@@ -19,6 +19,8 @@
 /*
  *  Authors: Marco Biasini, Juergen Haas
  */
+ 
+#include <ost/mol/chem_class.hh>
 #include <ost/mol/mol.hh>
 #include <cmath>
 #define BOOST_TEST_DYN_LINK
@@ -42,10 +44,12 @@
 
 using namespace ost;
 using namespace ost::mol;
+
+
 EntityHandle make_test_entity()
 {
   EntityHandle eh = CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle chain = e.InsertChain("A");
   ResidueHandle res1 = e.AppendResidue(chain, "MET");
 
@@ -71,19 +75,36 @@ EntityHandle make_test_entity()
   res2.SetChemClass(ChemClass(ChemClass::LPeptideLinking));  
   e.AddTorsion("PHI", res1.FindAtom("C"), res2.FindAtom("N"), 
                res2.FindAtom("CA"), res2.FindAtom("C"));
-               
   return eh;
 }
 
 BOOST_AUTO_TEST_SUITE( mol_base )
 
+
+BOOST_AUTO_TEST_CASE(throw_invalid_ent_handle)
+{
+  EntityHandle ent;
+  BOOST_CHECK_THROW(CheckHandleValidity(ent), InvalidHandle);  
+  ent=CreateEntity();
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(ent));
+}
+
+BOOST_AUTO_TEST_CASE(throw_invalid_ent_view)
+{
+  EntityView ent_view;
+  BOOST_CHECK_THROW(CheckHandleValidity(ent_view), InvalidHandle);  
+  EntityHandle ent=CreateEntity();
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(ent.CreateFullView()));
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(ent.CreateEmptyView()));
+}
+
 BOOST_AUTO_TEST_CASE(entity_creator) 
 {
   EntityHandle eh = CreateEntity();
   eh.SetName("TestEntity");
   BOOST_CHECK(eh.GetName()=="TestEntity");
 
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle chain = e.InsertChain("C");
   BOOST_CHECK(chain.GetName()=="C");
 
@@ -118,7 +139,7 @@ BOOST_AUTO_TEST_CASE(entity_creator)
 BOOST_AUTO_TEST_CASE(spatial_organizer) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();  
+  XCSEditor e=eh.EditXCS();  
   ChainHandle chain = e.InsertChain("A");
   ResidueHandle res = e.AppendResidue(chain, "X");
 
@@ -139,7 +160,7 @@ BOOST_AUTO_TEST_CASE(spatial_organizer)
 BOOST_AUTO_TEST_CASE(transformation) 
 {
   EntityHandle eh = CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle chain = e.InsertChain("A");
   ResidueHandle res = e.AppendResidue(chain, "X");
 
@@ -240,7 +261,7 @@ BOOST_AUTO_TEST_CASE(transformation)
 
   BOOST_CHECK(bond1.GetLength()==1.5);
   BOOST_CHECK(bond2.GetLength()==2.0);
-  ICSEditor i = eh.RequestICSEditor();
+  ICSEditor i = eh.EditICS();
   i.SetBondLength(bond1,1.0);
   i.SetBondLength(bond2,3.0);
 
@@ -325,4 +346,56 @@ BOOST_AUTO_TEST_CASE(copy)
   BOOST_CHECK(r2.GetPhiTorsion());
 }
 
+BOOST_AUTO_TEST_CASE(copy_residue_props)
+{
+  EntityHandle ent=mol::CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  ChainHandle ch=edi.InsertChain("A");
+  ResidueHandle res=edi.AppendResidue(ch, "DUMMY", mol::ResNum(666, '6'));
+  res.SetOneLetterCode('X');
+  res.SetIsProtein(true);
+  res.SetIsLigand(true);
+  ChemClass cl(ChemClass::LPeptideLinking);  
+  res.SetSecStructure(SecStructure(SecStructure::ALPHA_HELIX));
+  res.SetChemClass(cl);
+  EntityHandle copy=ent.Copy();
+  ResidueHandle res2=copy.GetResidueList()[0];
+  BOOST_CHECK_EQUAL(res2.GetName(), String("DUMMY"));
+  BOOST_CHECK_EQUAL(res2.GetOneLetterCode(), 'X');
+
+  BOOST_CHECK_EQUAL(res2.GetChemClass(), cl);
+  BOOST_CHECK_EQUAL(res.GetSecStructure(), SecStructure::ALPHA_HELIX);
+  BOOST_CHECK(res2.IsProtein()==true);
+  BOOST_CHECK(res2.IsLigand()==true);  
+  BOOST_CHECK_EQUAL(res2.GetNumber(), ResNum(666, '6'));
+}
+
+BOOST_AUTO_TEST_CASE(copy_atom_props)
+{
+  EntityHandle ent=mol::CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  ChainHandle ch=edi.InsertChain("A");
+  ResidueHandle res=edi.AppendResidue(ch, "DUMMY");
+  AtomHandle   atom=edi.InsertAtom(res, "X", geom::Vec3(1,2,3), "C");
+  atom.SetMass(100.0);
+  atom.SetBFactor(200.0);
+  atom.SetOccupancy(300.0);
+  atom.SetHetAtom(true);
+  atom.SetRadius(500);
+  atom.SetCharge(800);
+  atom.SetAnisou(geom::Mat3(100,200,300));
+  EntityHandle copy=ent.Copy();
+  AtomHandle atom2=copy.GetAtomList()[0];
+  BOOST_CHECK_EQUAL(atom2.GetPos(), geom::Vec3(1,2,3));
+  BOOST_CHECK_EQUAL(atom2.GetName(), String("X"));
+  BOOST_CHECK_EQUAL(atom2.GetElement(), String("C"));
+  BOOST_CHECK_EQUAL(atom2.GetMass(), Real(100.0));
+  BOOST_CHECK_EQUAL(atom2.GetCharge(), Real(800.0));  
+  BOOST_CHECK_EQUAL(atom2.GetBFactor(), Real(200.0)); 
+  BOOST_CHECK_EQUAL(atom2.IsHetAtom(), true);
+  BOOST_CHECK_EQUAL(atom2.GetAnisou(), geom::Mat3(100,200,300));
+  BOOST_CHECK_EQUAL(atom2.GetRadius(), Real(500.0));
+}
+
+
 BOOST_AUTO_TEST_SUITE_END()
diff --git a/modules/mol/base/tests/test_ics.cc b/modules/mol/base/tests/test_ics.cc
index 37955909398b208a556a3a9feaf4c7f1f8c48ba0..d577f8ca9dd60a720ea1f780b5f3922e311e4993 100644
--- a/modules/mol/base/tests/test_ics.cc
+++ b/modules/mol/base/tests/test_ics.cc
@@ -36,7 +36,7 @@ struct Structure {
   Structure()
   {
     e=CreateEntity();
-    ICSEditor editor=e.RequestICSEditor();
+    ICSEditor editor=e.EditICS();
     c=editor.InsertChain("A");
     r=editor.AppendResidue(c, "ANGELIN");
     a1=editor.InsertAtom(r, "CC", geom::Vec3(-1.0, 0.0,  0.0));
@@ -76,7 +76,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(ics_angle_trivia) 
 {
   Structure s;
-  ICSEditor e=s.e.RequestICSEditor();
+  ICSEditor e=s.e.EditICS();
   BOOST_CHECK(!e.SetAngle(s.a1, s.a3, s.a2, 0));
   BOOST_CHECK(!e.SetAngle(s.a2, s.a3, s.a1, 0));
   BOOST_CHECK(e.SetAngle(s.a1, s.a2, s.a3, 0));
@@ -94,7 +94,7 @@ BOOST_AUTO_TEST_CASE(ics_set_angle_sec)
 {
   Structure s;
   // test for set angle of two secondary connectors
-  ICSEditor e=s.e.RequestICSEditor();  
+  ICSEditor e=s.e.EditICS();  
   geom::Plane p(s.a3.GetPos(), s.a2.GetPos(), s.a4.GetPos());
   e.SetAngle(s.a3, s.a2, s.a4, M_PI/4);
   e.UpdateXCS();  
@@ -111,7 +111,7 @@ BOOST_AUTO_TEST_CASE(ics_set_angle_prim)
 {
   Structure s;
   // test for set angle of two secondary connectors
-  ICSEditor e=s.e.RequestICSEditor();    
+  ICSEditor e=s.e.EditICS();    
   e.SetAngle(s.a1, s.a2, s.a4, M_PI/4);
   e.UpdateXCS();
   geom::Plane p(s.a1.GetPos(), s.a2.GetPos(), s.a4.GetPos());
diff --git a/modules/mol/base/tests/test_iterators.cc b/modules/mol/base/tests/test_iterators.cc
index 8dfc0dca0f1215b730a6e637cd98f36b0b2b59d0..0c2900571e9e4482f03dce839eb4c19b593649fe 100644
--- a/modules/mol/base/tests/test_iterators.cc
+++ b/modules/mol/base/tests/test_iterators.cc
@@ -140,7 +140,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(chain_handle_iterator) 
 {
   EntityHandle ent=CreateEntity();
-  XCSEditor editor=ent.RequestXCSEditor();  
+  XCSEditor editor=ent.EditXCS();  
   ChainHandle ch1=editor.InsertChain("A");
   ChainHandle ch2=editor.InsertChain("B");
   ChainHandle ch3=editor.InsertChain("C");
@@ -161,7 +161,7 @@ BOOST_AUTO_TEST_CASE(chain_handle_iterator)
 BOOST_AUTO_TEST_CASE(test_res_handle_iterator) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor editor=eh.RequestXCSEditor();  
+  XCSEditor editor=eh.EditXCS();  
   ChainHandle ch1=editor.InsertChain("A");
   editor.AppendResidue(ch1, "A");
   editor.AppendResidue(ch1, "B");
@@ -197,7 +197,7 @@ BOOST_AUTO_TEST_CASE(test_empty_iterators)
   BOOST_CHECK(eh.ChainsBegin()==eh.ChainsEnd());
   BOOST_CHECK(eh.ResiduesBegin()==eh.ResiduesEnd());  
   BOOST_CHECK(eh.AtomsBegin()==eh.AtomsEnd());    
-  XCSEditor editor=eh.RequestXCSEditor();
+  XCSEditor editor=eh.EditXCS();
   ChainHandle ch1=editor.InsertChain("A");  
   BOOST_CHECK(ch1.ResiduesBegin()==ch1.ResiduesEnd());
   BOOST_CHECK(ch1.AtomsBegin()==ch1.AtomsEnd());  
@@ -205,7 +205,7 @@ BOOST_AUTO_TEST_CASE(test_empty_iterators)
   BOOST_CHECK(r1.AtomsBegin()==r1.AtomsEnd());    
   
   eh=CreateEntity();
-  editor=eh.RequestXCSEditor();  
+  editor=eh.EditXCS();  
   ch1=editor.InsertChain("A");
   r1=editor.AppendResidue(ch1, "A");
   ResidueHandle r2=editor.AppendResidue(ch1, "B");
@@ -229,7 +229,7 @@ BOOST_AUTO_TEST_CASE(test_empty_iterators)
 BOOST_AUTO_TEST_CASE(test_atom_handle_iterator) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor editor=eh.RequestXCSEditor();  
+  XCSEditor editor=eh.EditXCS();  
   ChainHandle ch1=editor.InsertChain("A");
   ResidueHandle r1=editor.AppendResidue(ch1, "A");
   ResidueHandle r2=editor.AppendResidue(ch1, "B");
diff --git a/modules/mol/base/tests/test_query.cc b/modules/mol/base/tests/test_query.cc
index d84a3156be0375fedf8db262a0970d29c8a0d952..6e603a16adf42d60671bf2b916d4cfc29f0dbee1 100644
--- a/modules/mol/base/tests/test_query.cc
+++ b/modules/mol/base/tests/test_query.cc
@@ -31,57 +31,43 @@ using namespace ost::mol;
 EntityHandle make_query_test_entity()
 {
   EntityHandle eh = CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle chain = e.InsertChain("A");
   chain.SetFloatProp("testprop_c", 1.0);
   ResidueHandle res = e.AppendResidue(chain, "MET");
   res.SetFloatProp("testpropr", 1.0);
-  AtomProp c_atom;
-  c_atom.element="C";
-  c_atom.radius=1.0;
-
-  AtomProp o_atom;
-  o_atom.element="O";
-  o_atom.radius=1.0;
-  AtomProp n_atom;
-  n_atom.element="N";
-  n_atom.radius=1.0;
-
-  AtomProp s_atom;
-  s_atom.element="S";
-  s_atom.radius=1.0;
-  AtomHandle ah=e.InsertAtom(res, "N",geom::Vec3(21.609,35.384,56.705), n_atom);
+  AtomHandle ah=e.InsertAtom(res, "N",geom::Vec3(21.609,35.384,56.705), "N");
   ah.SetFloatProp("testpropa", 1.0);
-  e.InsertAtom(res, "CA",geom::Vec3(20.601,35.494,57.793), c_atom);
-  e.InsertAtom(res, "C",geom::Vec3(19.654,34.300,57.789), c_atom);
-  e.InsertAtom(res, "O",geom::Vec3(18.447,34.456,57.595), o_atom);
-  e.InsertAtom(res, "CB",geom::Vec3(19.789,36.783,57.639), c_atom);
-  e.InsertAtom(res, "CG",geom::Vec3(20.629,38.055,57.606), c_atom);
-  e.InsertAtom(res, "SD",geom::Vec3(21.638,38.325,59.084), s_atom);
-  e.InsertAtom(res, "CE",geom::Vec3(23.233,37.697,58.529), c_atom);
+  e.InsertAtom(res, "CA",geom::Vec3(20.601,35.494,57.793), "C");
+  e.InsertAtom(res, "C",geom::Vec3(19.654,34.300,57.789), "C");
+  e.InsertAtom(res, "O",geom::Vec3(18.447,34.456,57.595), "O");
+  e.InsertAtom(res, "CB",geom::Vec3(19.789,36.783,57.639), "C");
+  e.InsertAtom(res, "CG",geom::Vec3(20.629,38.055,57.606), "C");
+  e.InsertAtom(res, "SD",geom::Vec3(21.638,38.325,59.084), "S");
+  e.InsertAtom(res, "CE",geom::Vec3(23.233,37.697,58.529), "C");
 
   res = e.AppendResidue(chain, "ARG");
-  e.InsertAtom(res, "N",geom::Vec3(20.202,33.112,58.011), n_atom);
-  e.InsertAtom(res, "CA",geom::Vec3(19.396,31.903,58.033), c_atom);
-  e.InsertAtom(res, "C",geom::Vec3(18.608,31.739,59.328), c_atom);
-  e.InsertAtom(res, "O",geom::Vec3(17.651,30.965,59.381), o_atom);
-  e.InsertAtom(res, "CB",geom::Vec3(20.284,30.681,57.801), c_atom);
-  e.InsertAtom(res, "CG",geom::Vec3(20.665,30.488,56.342), c_atom);
-  e.InsertAtom(res, "CD",geom::Vec3(21.557,29.281,56.154), c_atom);
-  e.InsertAtom(res, "NE",geom::Vec3(22.931,29.557,56.551), n_atom);
-  e.InsertAtom(res, "CZ",geom::Vec3(23.901,28.653,56.528), c_atom);
-  e.InsertAtom(res, "NH1",geom::Vec3(23.640,27.417,56.130), n_atom);
-  e.InsertAtom(res, "NH2",geom::Vec3(25.132,28.980,56.893), n_atom);
+  e.InsertAtom(res, "N",geom::Vec3(20.202,33.112,58.011), "N");
+  e.InsertAtom(res, "CA",geom::Vec3(19.396,31.903,58.033), "C");
+  e.InsertAtom(res, "C",geom::Vec3(18.608,31.739,59.328), "C");
+  e.InsertAtom(res, "O",geom::Vec3(17.651,30.965,59.381), "O");
+  e.InsertAtom(res, "CB",geom::Vec3(20.284,30.681,57.801), "C");
+  e.InsertAtom(res, "CG",geom::Vec3(20.665,30.488,56.342), "C");
+  e.InsertAtom(res, "CD",geom::Vec3(21.557,29.281,56.154), "C");
+  e.InsertAtom(res, "NE",geom::Vec3(22.931,29.557,56.551), "N");
+  e.InsertAtom(res, "CZ",geom::Vec3(23.901,28.653,56.528), "C");
+  e.InsertAtom(res, "NH1",geom::Vec3(23.640,27.417,56.130), "N");
+  e.InsertAtom(res, "NH2",geom::Vec3(25.132,28.980,56.893), "N");
 
   res = e.AppendResidue(chain, "LEU");
-  e.InsertAtom(res, "N",geom::Vec3(19.003,32.473,60.366), n_atom);
-  e.InsertAtom(res, "CA",geom::Vec3(18.330,32.402,61.664), c_atom);
-  e.InsertAtom(res, "C",geom::Vec3(17.884,33.787,62.117), c_atom);
-  e.InsertAtom(res, "O",geom::Vec3(17.853,34.091,63.308), o_atom);
-  e.InsertAtom(res, "CB",geom::Vec3(19.269,31.793,62.710), c_atom);
-  e.InsertAtom(res, "CG",geom::Vec3(19.695,30.340,62.501), c_atom);
-  e.InsertAtom(res, "CD1",geom::Vec3(20.585,29.897,63.648), c_atom);
-  e.InsertAtom(res, "CD2",geom::Vec3(18.461,29.459,62.420), c_atom);
+  e.InsertAtom(res, "N",geom::Vec3(19.003,32.473,60.366), "N");
+  e.InsertAtom(res, "CA",geom::Vec3(18.330,32.402,61.664), "C");
+  e.InsertAtom(res, "C",geom::Vec3(17.884,33.787,62.117), "C");
+  e.InsertAtom(res, "O",geom::Vec3(17.853,34.091,63.308), "O");
+  e.InsertAtom(res, "CB",geom::Vec3(19.269,31.793,62.710), "C");
+  e.InsertAtom(res, "CG",geom::Vec3(19.695,30.340,62.501), "C");
+  e.InsertAtom(res, "CD1",geom::Vec3(20.585,29.897,63.648), "C");
+  e.InsertAtom(res, "CD2",geom::Vec3(18.461,29.459,62.420), "C");
   return eh;
 }
 
diff --git a/modules/mol/base/tests/test_residue.cc b/modules/mol/base/tests/test_residue.cc
index 332d60edd6534837b9511314b4a3aecceadbffae..f622f72a56a069e911321842268fedafb19181b8 100644
--- a/modules/mol/base/tests/test_residue.cc
+++ b/modules/mol/base/tests/test_residue.cc
@@ -34,7 +34,7 @@ BOOST_AUTO_TEST_SUITE( mol_base )
 BOOST_AUTO_TEST_CASE(test_in_sequence) 
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle ch1=e.InsertChain("A");
   ResidueHandle rA = e.AppendResidue(ch1, "A");
   ResidueHandle rB = e.AppendResidue(ch1, "B");
@@ -45,10 +45,38 @@ BOOST_AUTO_TEST_CASE(test_in_sequence)
   BOOST_CHECK(!InSequence(rA,rC));
 }
 
+
+BOOST_AUTO_TEST_CASE(throw_invalid_res_handle)
+{
+  ChainHandle chain;
+  EntityHandle ent=CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  chain=edi.InsertChain("A");
+  ResidueHandle res=chain.FindResidue(ResNum(1));
+  BOOST_CHECK_THROW(CheckHandleValidity(res), InvalidHandle);
+  edi.AppendResidue(chain, "GLY");
+  res=chain.FindResidue(ResNum(1));
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(res));
+}
+
+BOOST_AUTO_TEST_CASE(throw_invalid_res_view)
+{
+  ChainHandle chain;
+  EntityHandle ent=CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  chain=edi.InsertChain("A");
+  ResidueView res;
+  BOOST_CHECK_THROW(CheckHandleValidity(res), InvalidHandle);
+  edi.AppendResidue(chain, "GLY");
+  EntityView ent_view=ent.CreateFullView();
+  res=ent_view.FindChain("A").FindResidue(1);
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(res));
+}
+
 BOOST_AUTO_TEST_CASE(test_res_index)
 {
   EntityHandle eh=CreateEntity();
-  XCSEditor e=eh.RequestXCSEditor();
+  XCSEditor e=eh.EditXCS();
   ChainHandle ch1=e.InsertChain("A");
   ResidueHandle rA = e.AppendResidue(ch1, "A");
   ResidueHandle rB = e.AppendResidue(ch1, "B");
diff --git a/modules/img/base/src/version.cc b/modules/mol/base/tests/test_surface.cc
similarity index 70%
rename from modules/img/base/src/version.cc
rename to modules/mol/base/tests/test_surface.cc
index 7bd94775b32dee1c47cedd763638311515f37c2f..6e30dcd07af14434fabaafdbd2e7e16c0fbf5ed0 100644
--- a/modules/img/base/src/version.cc
+++ b/modules/mol/base/tests/test_surface.cc
@@ -2,7 +2,6 @@
 // This file is part of the OpenStructure project <www.openstructure.org>
 //
 // Copyright (C) 2008-2010 by the OpenStructure authors
-// Copyright (C) 2003-2010 by the IPLT authors
 //
 // This library 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
@@ -17,24 +16,25 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+ 
+#include <ost/mol/surface_handle.hh>
+#include <cmath>
+#define BOOST_TEST_DYN_LINK
+#include <boost/test/unit_test.hpp>
 
-/*
-  versioning info
+using namespace ost;
+using namespace ost::mol;
 
-  Author: Ansgar Philippsen
-*/
+BOOST_AUTO_TEST_SUITE( mol_base )
 
-#include "version.hh"
 
-#include <sstream>
-
-namespace ost { namespace img {
-
-String GetVersion()
+BOOST_AUTO_TEST_CASE(test_throw_invalid_surface)
 {
-  std::ostringstream str;
-  str << VERSION ;
-  return str.str();
+  SurfaceHandle surf;
+  BOOST_CHECK_THROW(CheckHandleValidity(surf), InvalidHandle);
+  
+  surf=CreateSurface();
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(surf));
 }
 
-}} // ns
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/modules/mol/base/tests/test_view.cc b/modules/mol/base/tests/test_view.cc
index 26399e10e1c240182d87f59a453a605d69dd3902..3f60928d627552a50450a62a6b89cb0de31c7ae8 100644
--- a/modules/mol/base/tests/test_view.cc
+++ b/modules/mol/base/tests/test_view.cc
@@ -30,7 +30,7 @@ using namespace ost::mol;
 struct Fixture {
   Fixture() {
     e=CreateEntity();
-    XCSEditor editor=e.RequestXCSEditor();
+    XCSEditor editor=e.EditXCS();
     c=editor.InsertChain("A");
     r=editor.AppendResidue(c, "ANGELIN");
     aa=editor.InsertAtom(r, "X1", geom::Vec3( 0.0, 0.0,  0.0));
diff --git a/modules/mol/base/tests/test_view_op.cc b/modules/mol/base/tests/test_view_op.cc
index f589bf2107638956d21663a4db196044c020c610..fb9d8ffda7b0fd210268a4ae3e5a6f3eb7074875 100644
--- a/modules/mol/base/tests/test_view_op.cc
+++ b/modules/mol/base/tests/test_view_op.cc
@@ -31,7 +31,7 @@ EntityHandle mk_test_ent()
 {
   EntityHandle ent=CreateEntity();
   ent.SetName("TestEntity");
-  XCSEditor edi=ent.RequestXCSEditor();
+  XCSEditor edi=ent.EditXCS();
   ChainHandle chain_a=edi.InsertChain("A");
   ResidueHandle res_a=edi.AppendResidue(chain_a, "A");
   AtomHandle atom_a=edi.InsertAtom(res_a, "A", geom::Vec3());
@@ -334,7 +334,8 @@ BOOST_AUTO_TEST_CASE(test_intersection_b)
                          bonds));
 }
 
-BOOST_AUTO_TEST_CASE(entity_from_view) {
+BOOST_AUTO_TEST_CASE(entity_from_view) 
+{
   EntityHandle ent=mk_test_ent();
   EntityView v1=ent.Select("aname=B,C,F,G");
   EntityHandle ent_fv=mol::CreateEntityFromView(v1, false);
@@ -347,5 +348,54 @@ BOOST_AUTO_TEST_CASE(entity_from_view) {
 
 }
 
+BOOST_AUTO_TEST_CASE(ent_from_view_residue_props)
+{
+  EntityHandle ent=mol::CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  ChainHandle ch=edi.InsertChain("A");
+  ResidueHandle res=edi.AppendResidue(ch, "DUMMY", mol::ResNum(666, '6'));
+  res.SetOneLetterCode('X');
+  res.SetIsProtein(true);
+  ChemClass cl(ChemClass::LPeptideLinking);  
+  res.SetSecStructure(SecStructure(SecStructure::ALPHA_HELIX));
+  res.SetChemClass(cl);
+  EntityHandle copy=mol::CreateEntityFromView(ent.Select(""), false);
+  ResidueHandle res2=copy.GetResidueList()[0];
+  BOOST_CHECK_EQUAL(res2.GetName(), String("DUMMY"));
+  BOOST_CHECK_EQUAL(res2.GetOneLetterCode(), 'X');
+
+  BOOST_CHECK_EQUAL(res2.GetChemClass(), cl);
+  BOOST_CHECK_EQUAL(res.GetSecStructure(), SecStructure::ALPHA_HELIX);
+  BOOST_CHECK(res2.IsProtein()==true);
+  BOOST_CHECK_EQUAL(res2.GetNumber(), ResNum(666, '6'));
+}
+
+BOOST_AUTO_TEST_CASE(ent_from_view_atom_props)
+{
+  EntityHandle ent=mol::CreateEntity();
+  XCSEditor edi=ent.EditXCS();
+  ChainHandle ch=edi.InsertChain("A");
+  ResidueHandle res=edi.AppendResidue(ch, "DUMMY");
+  AtomHandle   atom=edi.InsertAtom(res, "X", geom::Vec3(1,2,3), "C");
+  atom.SetMass(100.0);
+  atom.SetBFactor(200.0);
+  atom.SetOccupancy(300.0);
+  atom.SetHetAtom(true);
+  atom.SetRadius(500);
+  atom.SetCharge(800);
+  atom.SetAnisou(geom::Mat3(100,200,300));
+  EntityHandle copy=mol::CreateEntityFromView(ent.Select(""), false);
+  AtomHandle atom2=copy.GetAtomList()[0];
+  BOOST_CHECK_EQUAL(atom2.GetPos(), geom::Vec3(1,2,3));
+  BOOST_CHECK_EQUAL(atom2.GetName(), String("X"));
+  BOOST_CHECK_EQUAL(atom2.GetElement(), String("C"));
+  BOOST_CHECK_EQUAL(atom2.GetMass(), Real(100.0));
+  BOOST_CHECK_EQUAL(atom2.GetCharge(), Real(800.0));  
+  BOOST_CHECK_EQUAL(atom2.GetBFactor(), Real(200.0)); 
+  BOOST_CHECK_EQUAL(atom2.IsHetAtom(), true);
+  BOOST_CHECK_EQUAL(atom2.GetAnisou(), geom::Mat3(100,200,300));
+  BOOST_CHECK_EQUAL(atom2.GetRadius(), Real(500.0));
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
diff --git a/modules/qa/pymod/CMakeLists.txt b/modules/qa/pymod/CMakeLists.txt
index c4fff8b16c9a6f8fc579717f9d2ccd988c59002c..a63e9c2d9bc05f8a671c8bb172aac63cf7c8ccd5 100644
--- a/modules/qa/pymod/CMakeLists.txt
+++ b/modules/qa/pymod/CMakeLists.txt
@@ -2,6 +2,7 @@ set(OST_QA_PYMOD_SOURCES
   export_interaction.cc
   export_torsion.cc
   export_packing.cc
+  export_reduced.cc
   wrap_qa.cc
   export_clash.cc
 )
diff --git a/modules/qa/pymod/export_interaction.cc b/modules/qa/pymod/export_interaction.cc
index 6e6e119f0a6b2a2d2a9fad3662b6815516b37935..fe61394c0b819f8d32e96dbdc1c025cc9f174ac2 100644
--- a/modules/qa/pymod/export_interaction.cc
+++ b/modules/qa/pymod/export_interaction.cc
@@ -236,11 +236,12 @@ void export_Interaction()
     .def("GetCount", f2, args("partner1", "partner2", "distance"))
     .def("SaveToFile", &InteractionStatistics::SaveToFile, args("file_name"))
     .def("LoadFromFile", &InteractionStatistics::LoadFromFile).staticmethod("LoadFromFile")
-    .def("RepairCbetaStatistics", &InteractionStatistics::RepairCbetaStatistics)
-    .def("isCbetaStaistics", &InteractionStatistics::isCbetaStaistics)
   ;  
   
   class_<AllAtomPotentialOpts>("AllAtomPotentialOpts", init<>())
+    .def(init<float,float,float,int,float>((arg("lower_cutoff"), 
+                                           arg("upper_cutoff"), arg("dist_bin_size"), 
+                                           arg("sequence_sep"), arg("sigma")=0.02)))
     .def_readwrite("LowerCutoff", &AllAtomPotentialOpts::lower_cutoff)
     .def_readwrite("UpperCutoff", &AllAtomPotentialOpts::upper_cutoff)
     .def_readwrite("DistanceBucketSize", 
@@ -257,6 +258,7 @@ void export_Interaction()
     .def("GetEnergyCounts", &AllAtomPotential::GetEnergyCounts)
     .def("GetEnergy", three_args, args("atom_type_1", "atom_type_1", "distance"))
     .def("SaveToFile", &AllAtomPotential::SaveToFile)
+    .add_property("options", make_function(&AllAtomPotential::GetOptions, return_value_policy<copy_const_reference>()))
     .def("SetSequenceSeparation", &AllAtomPotential::SetSequenceSeparation)
   ;
   register_ptr_to_python<AllAtomPotentialPtr>();  
diff --git a/modules/qa/pymod/export_reduced.cc b/modules/qa/pymod/export_reduced.cc
new file mode 100644
index 0000000000000000000000000000000000000000..3384c45290d7237f8a9908f2e4b5ae3586014464
--- /dev/null
+++ b/modules/qa/pymod/export_reduced.cc
@@ -0,0 +1,73 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+
+#include <boost/python.hpp>
+#include <ost/mol/mol.hh>
+#include <ost/qa/reduced_statistics.hh>
+#include <ost/qa/reduced_potential.hh>
+
+using namespace ost::qa;
+using namespace ost::mol;
+using namespace boost::python;
+  
+uint64_t (ReducedStatistics::*get_count)(AminoAcid,
+                                         AminoAcid,
+                                         int,int)=&ReducedStatistics::GetCount;
+void (ReducedStatistics::*ex_h)(EntityHandle)=&ReducedStatistics::Extract;
+void (ReducedStatistics::*ex_v)(EntityView)=&ReducedStatistics::Extract;
+
+Real (ReducedPotential::*get_h)(EntityHandle,bool)=&ReducedPotential::GetTotalEnergy;
+Real (ReducedPotential::*get_v)(EntityView,bool)=&ReducedPotential::GetTotalEnergy;
+void export_Reduced()
+{
+  class_<ReducedStatOptions>("ReducedStatOptions", init<>())
+    .def(init<Real,Real,uint,uint,uint>((arg("l_cutoff"), arg("d_cutoff"), 
+          arg("num_ang_bins"), arg("num_dist_bins"), arg("sequence_sep"))))
+    .def_readwrite("lower_cutoff", &ReducedStatOptions::lower_cutoff)
+    .def_readwrite("upper_cutoff", &ReducedStatOptions::upper_cutoff)
+    .def_readwrite("num_angular_bins", &ReducedStatOptions::num_angular_bins)
+    .def_readwrite("num_dist_bins", &ReducedStatOptions::num_dist_bins)
+    .def_readwrite("sequence_sep", &ReducedStatOptions::sequence_sep)
+  ;
+  
+  
+  class_<ReducedStatistics, ReducedStatisticsPtr>("ReducedStatistics", no_init)
+    .def(init<Real,Real,uint,uint,uint>((arg("l_cutoff"), arg("u_cutoff"), 
+          arg("num_ang_bins"), arg("num_dist_bins"), arg("sequence_sep"))))
+    .def("Extract", ex_h, arg("ent"))
+    .def("Extract", ex_v, arg("ent"))
+    .add_property("options", make_function(&ReducedStatistics::GetOptions, 
+                  return_value_policy<copy_const_reference>()))
+    .def("Save", &ReducedStatistics::Save)
+    .def("Load", &ReducedStatistics::Load).staticmethod("Load")
+    .def("GetCount", get_count)
+  ;
+  class_<ReducedPotential, ReducedPotentialPtr>("ReducedPotential", no_init)
+    .def("Load", &ReducedPotential::Load).staticmethod("Load")
+    .def("Create", &ReducedPotential::Create).staticmethod("Create")
+    .def("Save", &ReducedPotential::Save)
+    .def("GetEnergy", &ReducedPotential::GetEnergy)
+    .def("GetTotalEnergy", get_h, 
+         (arg("ent"), arg("normalize")=true))
+    .def("GetTotalEnergy", get_v, 
+         (arg("ent"), arg("normalize")=true))
+    .add_property("options", make_function(&ReducedPotential::GetOptions, 
+                  return_value_policy<copy_const_reference>()))
+  ;
+}
\ No newline at end of file
diff --git a/modules/qa/pymod/export_torsion.cc b/modules/qa/pymod/export_torsion.cc
index a02e46f6c67d00ba90d9e65e353426affd948ae9..ed430c871e4369042b7b77127afbd66ff7656df7 100644
--- a/modules/qa/pymod/export_torsion.cc
+++ b/modules/qa/pymod/export_torsion.cc
@@ -84,6 +84,7 @@ void export_Torsion()
     .value("His", His)
     .value("Phe", Phe)
     .value("Trp", Trp)
+    .export_values()
   ;
   
   class_<AminoAcidSet>("AminoAcidSet", init<>())
diff --git a/modules/qa/pymod/wrap_qa.cc b/modules/qa/pymod/wrap_qa.cc
index bb6519155ef12476d31c1e1fac7752069ca182d2..8020ed29e5c1714d65911f289a7bf31cb998e912 100644
--- a/modules/qa/pymod/wrap_qa.cc
+++ b/modules/qa/pymod/wrap_qa.cc
@@ -22,10 +22,12 @@ void export_Torsion();
 void export_Interaction();
 void export_Packing();
 void export_Clash();
+void export_Reduced();
 BOOST_PYTHON_MODULE(_qa)
 {
   export_Torsion();
   export_Interaction();
   export_Packing();
   export_Clash();
+  export_Reduced();
 }
diff --git a/modules/qa/src/CMakeLists.txt b/modules/qa/src/CMakeLists.txt
index cc75ea3b85e8c3a6de3f98aeb75732ccf14f0849..b4c7baf97796e995ac5d3aca326dea2ec45154b1 100644
--- a/modules/qa/src/CMakeLists.txt
+++ b/modules/qa/src/CMakeLists.txt
@@ -13,10 +13,14 @@ packing_statistics.hh
 atom_types.hh
 packing_potential.hh
 clash_score.hh
+reduced_statistics.hh
+reduced_potential.hh
 module_config.hh
 )
 
 set(OST_QA_SOURCES
+reduced_statistics.cc
+reduced_potential.cc
 torsion_statistics.cc
 torsion_potential.cc
 solis_torsion_statistics.cc
@@ -28,8 +32,10 @@ atom_types.cc
 all_atom_potential.cc
 packing_potential.cc
 clash_score.cc
+impl/reduced_impl.cc
 )
 
+
 module(NAME qa SOURCES ${OST_QA_SOURCES}
-       HEADERS ${OST_QA_HEADERS} DEPENDS_ON io)
+       HEADERS reduced_impl.hh IN_DIR impl ${OST_QA_HEADERS} DEPENDS_ON io)
 
diff --git a/modules/qa/src/all_atom_potential.cc b/modules/qa/src/all_atom_potential.cc
index 348880447a93c9f8530bc1a4b65a146f809e2d72..18a4ce5f01488a74a5d62d24553e5804f7938e10 100644
--- a/modules/qa/src/all_atom_potential.cc
+++ b/modules/qa/src/all_atom_potential.cc
@@ -36,7 +36,8 @@ namespace {
 class AllAtomPotentialCalculator : public mol::EntityVisitor {
 public:
   AllAtomPotentialCalculator(AllAtomPotential::AllAtomEnergies& energies,
-                             AllAtomPotentialOpts& opts, mol::EntityView target_view):
+                             AllAtomPotentialOpts& opts, 
+                             mol::EntityView target_view):
     energies_(energies),
     options_(opts),
     energy_(0.0),
@@ -53,12 +54,6 @@ public:
   
   virtual bool VisitAtom(const mol::AtomHandle& atom_handle)
   {
-    //TODO: The handle contains all atoms of the original loded PDB file.
-    //i.e. the selection on C-beta atoms for the residue-based potential
-    //is lost. Therefore a first view contains all atoms of which the energy
-    //should be alculated and an additional (target-)view is provided which
-    //specifies the set of atoms against which the potential is calculated
-
     atom::ChemType type_a=GetAtomTypeByName(curr_aa_, atom_handle.GetName());
     if (type_a!=atom::UNKNOWN) {
       mol::AtomViewList nearby_atoms=target_view_.FindWithin(atom_handle.GetPos(),
@@ -75,24 +70,24 @@ public:
           float d=geom::Distance(atom_handle.GetPos(),
                                   a.GetPos());
 
-         // avoid rounding problems: distances very close to the cut-off may
-         // be rounded up the to cut-off and lead to an overflow in container energies_
+          // avoid rounding problems: distances very close to the cut-off may
+          // be rounded up the to cut-off and lead to an overflow in container 
+          // energies_
           d=d-0.0001; //used to prevent overflow if distance == upper_cutoff
           if (d<0) d=0.0;
 
           if (d>options_.lower_cutoff) {
-            // GetHandle() necessary to retriev original index of the view (as compared to index in the view):
-            if (abs(atom_handle.GetResidue().GetIndex()-a.GetResidue().GetHandle().GetIndex())<options_.sequence_sep) {
+            // GetHandle() necessary to retriev original index of the view (as 
+            // compared to index in the view):
+            int abs_sep=abs(atom_handle.GetResidue().GetIndex()-
+                            a.GetResidue().GetHandle().GetIndex());
+            if (abs_sep<options_.sequence_sep) {
               continue;
             }
             energy_+=energies_.Get(type_a, type_b, d);
             interaction_counts_++;
-            //std::cout << type_a << "(" << atom_handle.GetQualifiedName() << ")" << " " << type_b << "(" << a.GetQualifiedName() << ")" << " : " << d << "     " << energies_.Get(type_a, type_b, d) << std::endl;
           }
         }
-// 	else {
-// 	  std::cout << "Unknown type: " << type_b << std::endl;
-// 	}
       }
     }
     return false;
@@ -143,8 +138,13 @@ void AllAtomPotential::SaveToFile(const String& filename)
 
 AllAtomPotentialPtr AllAtomPotential::LoadFromFile(const String& filename)
 {
-  if(!boost::filesystem::exists(filename))
-  throw io::IOException("Could not open interaction potential data file.\nFile does not exist at: "+filename);
+  if (!boost::filesystem::exists(filename)) {
+    std::stringstream ss;
+    ss << "Could not open interaction potential. File '" 
+       << filename << "' does not exist";
+    throw io::IOException(ss.str());
+  }
+    
 
   std::ifstream stream(filename.c_str(), std::ios_base::binary);
   io::BinaryDataSource ds(stream);  
@@ -153,36 +153,25 @@ AllAtomPotentialPtr AllAtomPotential::LoadFromFile(const String& filename)
   return all_atom_p;
 }
 
-
-float AllAtomPotential::GetTotalEnergy(mol::EntityView view, mol::EntityView target_view)
+float AllAtomPotential::GetTotalEnergy(mol::EntityView view,
+                                       mol::EntityView target_view)
 {
   AllAtomPotentialCalculator c(energies_, options_, target_view);
   mol::EntityHandle e=view.GetHandle();
   view.Apply(c);
-  interaction_counts_member_=c.GetEnergyCounts();
+  interaction_counts_=c.GetEnergyCounts();
   return c.GetEnergy();
 }
 
-float AllAtomPotential::GetEnergy(atom::ChemType type_a, atom::ChemType type_b, float distance)
-{
-  return energies_.Get(type_a, type_b, distance);
-}
-
 float AllAtomPotential::GetTotalEnergy(mol::EntityView view)
 {
   AllAtomPotentialCalculator c(energies_, options_, view);
   mol::EntityHandle e=view.GetHandle();
   view.Apply(c);
-  interaction_counts_member_=c.GetEnergyCounts();
+  interaction_counts_=c.GetEnergyCounts();
   return c.GetEnergy();
 }
 
-
-int AllAtomPotential::GetEnergyCounts() const {
-  return interaction_counts_member_;
-}
-
-
 void AllAtomPotential::SetSequenceSeparation(int seq_sep) {
   options_.sequence_sep=seq_sep;
 }
@@ -233,7 +222,6 @@ void AllAtomPotential::Fill(const InteractionStatisticsPtr& stats)
                                  options_.lower_cutoff+
                                  options_.distance_bucket_size*0.5);
   }
-//   std::cout << "total_counts: " << total_counts << std::endl; 
 
   for (int i=0; i<atom::UNKNOWN; ++i) {
     for (int j=0; j<atom::UNKNOWN; ++j) {
@@ -254,26 +242,6 @@ void AllAtomPotential::Fill(const InteractionStatisticsPtr& stats)
         // prop = (Nd_xy / Nxy) / (Nd / Ntot)
         float e=0.582*log(1+options_.sigma*t2)-0.582*log(1+options_.sigma*t2*d);
         energies_.Set(Index(i, j, k), e);
-
-        // potential is only calculated for Cbeta atoms:
-        // copy the potential for Calpha (Calphas are selected if 
-        // Cbetas are not present)
-        if (stats->isCbetaStaistics() == true) {
-          //check if Cbeta (has counts) and not Glycin-Calpha
-          if (t3 != 0) {
-             if (i==3) {
-              energies_.Set(Index(i, j-1, k), e);
-             }
-             else if (j==3) {
-              energies_.Set(Index(i-1, j, k), e);
-              }
-             else {
-              energies_.Set(Index(i-1, j, k), e);
-              energies_.Set(Index(i, j-1, k), e);
-              energies_.Set(Index(i-1, j-1, k), e);
-             }
-          }
-        }
       }
     }
   }
diff --git a/modules/qa/src/all_atom_potential.hh b/modules/qa/src/all_atom_potential.hh
index 81beef95d7a1bf50168aa309c8865789035a38bd..0a1a99b7aeec1fa296645b6f7aeba81fd7a42ab5 100644
--- a/modules/qa/src/all_atom_potential.hh
+++ b/modules/qa/src/all_atom_potential.hh
@@ -37,7 +37,9 @@ struct DLLEXPORT_OST_QA AllAtomPotentialOpts {
 
   AllAtomPotentialOpts();
 
-  AllAtomPotentialOpts(float lower_cutoff, float upper_cutoff, float distance_bucket_size, int sequence_sep, float sigma=0.02);
+  AllAtomPotentialOpts(float lower_cutoff, float upper_cutoff, 
+                       float distance_bucket_size, int sequence_sep, 
+                       float sigma=0.02);
 
  public: 
   /// \brief weight factor 
@@ -76,8 +78,11 @@ public:
 
   /// \brief extract energy of a specific interaction
   /// (for plotting pseudo Lennard-Jones potential).
-  float GetEnergy(atom::ChemType type_a, atom::ChemType type_b, float distance);
-
+  float GetEnergy(atom::ChemType type_a, atom::ChemType type_b, 
+                  float distance)
+  {
+    return energies_.Get(type_a, type_b, distance);
+  }
   /// \brief calculate all-atom interaction between two entities.
   /// Two entities need to be provided:
   /// the atoms for which the energy should be derived and
@@ -85,12 +90,12 @@ public:
   float GetTotalEnergy(mol::EntityView view, mol::EntityView target_view);
 
   /// \brief retrieve total number of interactions (for normalisation)
-  int GetEnergyCounts() const;
+  int GetEnergyCounts() const { return interaction_counts_; }
 
   /// \brief set different seqeunce separation than used for training
   void SetSequenceSeparation(int seq_sep);
 
-  
+  const AllAtomPotentialOpts& GetOptions() const { return options_; }
   template <typename DS>
   void Serialize(DS& ds);
 public:
@@ -102,7 +107,7 @@ private:
   AllAtomPotentialOpts   options_;  
   AllAtomEnergies        energies_;
   mol::EntityView        target_view_;
-  int                    interaction_counts_member_;
+  int                    interaction_counts_;
 }; 
 
 }}
diff --git a/modules/qa/src/amino_acids.cc b/modules/qa/src/amino_acids.cc
index 8e98cbcf24e6292fe9880aec7312159a17dc31e2..a0f31e8dd206cf64d39c5f516a9721ccf258f818 100644
--- a/modules/qa/src/amino_acids.cc
+++ b/modules/qa/src/amino_acids.cc
@@ -125,6 +125,104 @@ String AminoAcidToResidueName(AminoAcid aa)
   }
 }
 
+String OneLetterCodeToResidueName(char olc)
+{
+  char upper_olc=toupper(olc);
+  switch(upper_olc) {
+    case 'A':
+      return "ALA";
+    case 'R':
+      return "ARG";
+    case 'N':
+      return "ASN";
+    case 'D':
+      return "ASP";
+    case 'Q':
+      return "GLN";
+    case 'E':
+      return "GLU";
+    case 'K':
+      return "LYS";
+    case 'S':
+      return "SER";
+    case 'C':
+      return "CYS";
+    case 'Y':  
+      return "TYR";
+    case 'W':
+      return "TRP";
+    case 'T':
+      return "THR";
+    case 'V':
+      return "VAL";
+    case 'I':
+      return "ILE";
+    case 'M':
+      return "MET";
+    case 'L':  
+      return "LEU";
+    case 'G':  
+      return "GLY";
+    case 'P':  
+      return "PRO";
+    case 'H':  
+      return "HIS";
+    case 'F':
+      return "PHE";
+    default:
+      return "UNK";
+  }
+}
+
+AminoAcid OneLetterCodeToAminoAcid(char olc)
+{
+  char upper_olc=toupper(olc);
+  switch(upper_olc) {
+    case 'A':
+      return Ala;
+    case 'R':   
+      return Arg;
+    case 'N':   
+      return Asn;
+    case 'D':   
+      return Asp;
+    case 'Q':   
+      return Gln;
+    case 'E':   
+      return Glu;
+    case 'K':   
+      return Lys;
+    case 'S':   
+      return Ser;
+    case 'C':   
+      return Cys;
+    case 'Y':   
+      return Tyr;
+    case 'W':   
+      return Trp;
+    case 'T':   
+      return Thr;
+    case 'V':   
+      return Val;
+    case 'I':   
+      return Ile;
+    case 'M':   
+      return Met;
+    case 'L':   
+      return Leu;
+    case 'G':   
+      return Gly;
+    case 'P':   
+      return Pro;
+    case 'H':   
+      return His;
+    case 'F':   
+      return Phe;
+    default:
+      return Xxx;
+  }
+}
+
 AminoAcidSet AminoAcidSet::CreatePolarSet()
 {
   AminoAcidSet polar;
diff --git a/modules/qa/src/amino_acids.hh b/modules/qa/src/amino_acids.hh
index d2337068c8743f8f80a2827112862b60259d88ca..92e80607acd58dae3f71d03bc8ceebb8d4bb491d 100644
--- a/modules/qa/src/amino_acids.hh
+++ b/modules/qa/src/amino_acids.hh
@@ -50,6 +50,10 @@ DLLEXPORT_OST_QA AminoAcid ResidueToAminoAcid(const mol::ResidueHandle& r);
 // \brief from amino acid to residue name
 DLLEXPORT_OST_QA String AminoAcidToResidueName(AminoAcid aa);
 
+DLLEXPORT_OST_QA String OneLetterCodeToResidueName(char olc);
+
+DLLEXPORT_OST_QA AminoAcid OneLetterCodeToAminoAcid(char olc);
+
 class AminoAcidSetIterator : public std::iterator<std::forward_iterator_tag,
                                                   AminoAcid> {
 public:
diff --git a/modules/qa/src/clash_score.cc b/modules/qa/src/clash_score.cc
index 66b95c09635eefd8fbf2fdbde5db2e78cf5bf501..8522606606fbc9600bdc6a52742d54751d5afd83 100644
--- a/modules/qa/src/clash_score.cc
+++ b/modules/qa/src/clash_score.cc
@@ -24,23 +24,6 @@ namespace ost { namespace qa {
 
 namespace {
   
-Real StericEnergy(const geom::Vec3& pos1, Real r1, 
-                  const geom::Vec3& pos2, Real r2)
-{
-  geom::Vec3 d=pos1-pos2;
-  // delay calculation of square root as long as possible. It is only needed
-  // in the rare case when 0.8254*rr <= d <= rr
-  Real distance_sqr=geom::Length2(d); 
-  Real rr=r1+r2;
-  if (distance_sqr>rr*rr) {
-    return 0.0;
-  }
-  if (distance_sqr<0.8254*0.8254*rr*rr) {
-    return 10.0;
-  }
-  return 57.273*(1.0-sqrt(distance_sqr)/rr);
-}
-
 template <typename T, typename I>
 Real do_clash_score(const T& ent_a, const mol::EntityView& ent_b)
 {
@@ -48,12 +31,12 @@ Real do_clash_score(const T& ent_a, const mol::EntityView& ent_b)
   for (I i=ent_a.AtomsBegin(), e=ent_a.AtomsEnd(); i!=e; ++i) {
     
     mol::AtomViewList clashees=ent_b.FindWithin((*i).GetPos(), 
-                                                (*i).GetAtomProps().radius+1.7);
+                                                (*i).GetRadius()+1.7);
 
     for (mol::AtomViewList::iterator j=clashees.begin(), 
          e2=clashees.end(); j!=e2; ++j) {
-         energy+=StericEnergy((*j).GetPos(), (*j).GetAtomProps().radius-0.25,
-                              (*i).GetPos(), (*i).GetAtomProps().radius-0.25);           
+         energy+=StericEnergy((*j).GetPos(), (*j).GetRadius()-0.25,
+                              (*i).GetPos(), (*i).GetRadius()-0.25);           
     }
   }
   return energy;  
@@ -61,6 +44,23 @@ Real do_clash_score(const T& ent_a, const mol::EntityView& ent_b)
 
 }
 
+Real StericEnergy(const geom::Vec3& pos1, Real r1,
+                  const geom::Vec3& pos2, Real r2)
+{
+  geom::Vec3 d=pos1-pos2;
+  // delay calculation of square root as long as possible. It is only needed
+  // in the rare case when 0.8254*rr <= d <= rr
+  Real distance_sqr=geom::Length2(d); 
+  Real rr=r1+r2;
+  if (distance_sqr>rr*rr) {
+    return 0.0;
+  }
+  if (distance_sqr<0.8254*0.8254*rr*rr) {
+    return 10.0;
+  }
+  return 57.273*(1.0-sqrt(distance_sqr)/rr);
+}
+
 Real ClashScore(const mol::EntityView& ent_a, const mol::EntityView& ent_b)
 {
   return do_clash_score<mol::EntityView, mol::AtomViewIter>(ent_a, ent_b);
@@ -75,11 +75,11 @@ Real ClashScore(const mol::AtomHandle& atom, const mol::EntityView& ent_b)
 {
   Real energy=0.0;
   mol::AtomViewList clashees=ent_b.FindWithin(atom.GetPos(), 
-                                              atom.GetAtomProps().radius+2.0);
+                                              atom.GetRadius()+2.0);
   for (mol::AtomViewList::iterator j=clashees.begin(), 
        e2=clashees.end(); j!=e2; ++j) {
-       energy+=StericEnergy((*j).GetPos(), (*j).GetAtomProps().radius,
-                            atom.GetPos(), atom.GetAtomProps().radius);           
+       energy+=StericEnergy((*j).GetPos(), (*j).GetRadius(),
+                            atom.GetPos(), atom.GetRadius());           
   }
   return energy;                                 
 }
diff --git a/modules/qa/src/clash_score.hh b/modules/qa/src/clash_score.hh
index 15b0994cecded3304a5079f99341428d87ef6b2d..bbf73a10ac4d86e26fde6e9e158aba41f72921ce 100644
--- a/modules/qa/src/clash_score.hh
+++ b/modules/qa/src/clash_score.hh
@@ -52,7 +52,10 @@ Real DLLEXPORT_OST_QA ClashScore(const mol::EntityHandle& ent_a,
 /// \sa \ref the_hammer.py "The Hammer Example"
 Real DLLEXPORT_OST_QA ClashScore(const mol::AtomHandle& atom, 
                                  const mol::EntityView& ent_b);
-                                 
+
+/// \brief calculate steric energy of two atoms
+Real DLLEXPORT_OST_QA StericEnergy(const geom::Vec3& pos1, Real r1,
+                                   const geom::Vec3& pos2, Real r2);
 //@}
 
 /// \example the_hammer.py
diff --git a/modules/qa/src/impl/reduced_impl.cc b/modules/qa/src/impl/reduced_impl.cc
new file mode 100644
index 0000000000000000000000000000000000000000..a3778cb39f4f2377e65bbed8795c3f61aa0d59ae
--- /dev/null
+++ b/modules/qa/src/impl/reduced_impl.cc
@@ -0,0 +1,118 @@
+#include <ost/log.hh>
+
+#include "reduced_impl.hh"
+
+
+namespace ost { namespace qa { namespace impl {
+
+bool ReducedPotentialImpl::VisitResidue(const mol::ResidueHandle& res)
+{
+  if (!res.IsPeptideLinking()) {
+    return false;
+  }
+  AminoAcid aa_one=OneLetterCodeToAminoAcid(res.GetOneLetterCode());
+  if (aa_one==Xxx) {
+    return false;
+  }
+  geom::Vec3 ca_pos_one;
+  geom::Vec3 cb_pos_one;
+  uint index=res.GetIndex();
+  if (!this->GetCAlphaCBetaPos(res, ca_pos_one, cb_pos_one)) {
+    return false;
+  }
+  
+  if (ent_) {
+    // we got a full entity handle.
+    mol::AtomHandleList within=ent_.FindWithin(ca_pos_one, 
+                                               opts_.upper_cutoff-0.00001);
+    for (mol::AtomHandleList::const_iterator 
+         i=within.begin(), e=within.end(); i!=e; ++i) {
+      if (i->GetName()=="CA") {
+        this->HandleResidue(aa_one, ca_pos_one, cb_pos_one, index, *i);
+      }
+
+    }
+    return false;
+  }
+  mol::AtomViewList within=view_.FindWithin(ca_pos_one, 
+                                             opts_.upper_cutoff-0.00001);
+  for (mol::AtomViewList::const_iterator 
+       i=within.begin(), e=within.end(); i!=e; ++i) {
+    if (i->GetName()=="CA") {
+      this->HandleResidue(aa_one, ca_pos_one, cb_pos_one, index, i->GetHandle());
+    }
+
+  }
+  return false;
+}
+
+void ReducedPotentialImpl::HandleResidue(AminoAcid aa_one, 
+                                         const geom::Vec3& ca_pos_one, 
+                                         const geom::Vec3& cb_pos_one, 
+                                         uint index_one, 
+                                         const mol::AtomHandle& ca_two)
+{
+  
+  mol::ResidueHandle res_two=ca_two.GetResidue();
+  if (res_two.GetIndex()-index_one<opts_.sequence_sep) {
+    return;
+  }
+  if (!res_two.IsPeptideLinking()) {
+    return;
+  }
+
+
+  AminoAcid aa_two=OneLetterCodeToAminoAcid(res_two.GetOneLetterCode());
+  if (aa_two==Xxx) {
+    return;
+  }
+  geom::Vec3 ca_pos_two;
+  geom::Vec3 cb_pos_two;
+  if (!this->GetCAlphaCBetaPos(res_two, ca_pos_two, cb_pos_two)) {
+    return;
+  }
+
+  Real dist=geom::Length(ca_pos_one-ca_pos_two);
+  if (dist<opts_.lower_cutoff) {
+    return;
+  }
+  Real angle=geom::Angle(cb_pos_one-ca_pos_one, cb_pos_two-ca_pos_two);
+
+  this->OnInteraction(aa_one, aa_two, dist, angle);
+}
+  
+bool ReducedPotentialImpl::GetCAlphaCBetaPos(const mol::ResidueHandle& res, 
+                                             geom::Vec3& ca_pos, 
+                                             geom::Vec3& cb_pos)
+{
+  const static Real bond_length=1.5;
+  mol::AtomHandle ca=res.FindAtom("CA");
+  if (!ca.IsValid()) {
+    return false;
+  }
+  ca_pos=ca.GetPos();
+  mol::AtomHandle cb=res.FindAtom("CB");
+  if (cb.IsValid()) {
+    cb_pos=cb.GetPos();
+    return true;
+  }
+  mol::AtomHandle n=res.FindAtom("N");
+  mol::AtomHandle c=res.FindAtom("C");
+  if (!(ca.IsValid() && c.IsValid() && n.IsValid())) {
+    LOG_WARNING("residue " << res.GetQualifiedName() 
+                << " doesn't have enough atoms to reconstruct Cbeta position");
+    return false;
+  }
+  geom::Vec3 v1=geom::Normalize(ca.GetPos()-n.GetPos());
+  geom::Vec3 v2=geom::Normalize(ca.GetPos()-c.GetPos());
+  geom::Vec3 in_plane_v=geom::Normalize(v1+v2);
+  geom::Plane p(ca.GetPos() ,n.GetPos(), c.GetPos());
+  // rotate around vector perpendicular  to p and in_plane_v
+  geom::Vec3 axis=geom::Normalize(geom::Cross(p.GetNormal(), in_plane_v));
+  geom::Mat3 rot_mat=geom::AxisRotation(axis, (-54/180.0)*M_PI);
+  cb_pos=ca.GetPos()+rot_mat*in_plane_v*bond_length;
+  return true;
+}
+
+}}}
+
diff --git a/modules/qa/src/impl/reduced_impl.hh b/modules/qa/src/impl/reduced_impl.hh
new file mode 100644
index 0000000000000000000000000000000000000000..43c312ea2d792cc9e1c0dae77668904b3d7c01c1
--- /dev/null
+++ b/modules/qa/src/impl/reduced_impl.hh
@@ -0,0 +1,62 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+
+#ifndef OST_QA_IMPL_REDUCED_HH
+#define OST_QA_IMPL_REDUCED_HH
+
+
+#include <ost/mol/mol.hh>
+
+#include <ost/qa/module_config.hh>
+#include <ost/qa/amino_acids.hh>
+#include <ost/qa/reduced_statistics.hh>
+
+namespace ost { namespace qa { namespace impl {
+
+class DLLEXPORT_OST_QA ReducedPotentialImpl : public mol::EntityVisitor {
+public:
+
+  ReducedPotentialImpl(const ReducedStatOptions& opts, mol::EntityHandle ent): 
+    opts_(opts), ent_(ent)
+  { }
+  
+  ReducedPotentialImpl(const ReducedStatOptions& opts, mol::EntityView ent): 
+    opts_(opts), view_(ent)
+  { }
+
+  virtual bool VisitResidue(const mol::ResidueHandle& res);
+
+  static bool GetCAlphaCBetaPos(const mol::ResidueHandle& res, 
+                                geom::Vec3& ca_pos, 
+                                geom::Vec3& cb_pos);
+                         
+  virtual void OnInteraction(AminoAcid aa_one, AminoAcid aa_two, 
+                             Real dist, Real angle)=0;
+private:  
+  void HandleResidue(AminoAcid aa_one, const geom::Vec3& ca_pos_one, 
+                     const geom::Vec3& cb_pos_one, 
+                     uint index_one, const mol::AtomHandle& ca_two);
+  ReducedStatOptions opts_;
+  mol::EntityHandle  ent_;
+  mol::EntityView    view_;
+};
+
+}}}
+
+#endif
diff --git a/modules/qa/src/interaction_statistics.cc b/modules/qa/src/interaction_statistics.cc
index 27422beaca060cecb54667c0005c927c088221c8..81399b27d725cd6626a82f3d28990e59cf5590f0 100644
--- a/modules/qa/src/interaction_statistics.cc
+++ b/modules/qa/src/interaction_statistics.cc
@@ -28,7 +28,6 @@ using namespace ost::mol::impl;
 namespace ost { namespace qa {
 
 InteractionStatistics::InteractionStatistics()
-: isCbetaStatisticsFlag_(false)
 {
 
 }
@@ -87,8 +86,7 @@ InteractionStatistics::InteractionStatistics(Real lower_cutoff,
     histogram_(IntegralClassifier(atom::UNKNOWN, 0),
                IntegralClassifier(atom::UNKNOWN, 0),
                ContinuousClassifier(int((upper_cutoff_-lower_cutoff_)/bucket_size),
-                                    lower_cutoff_, upper_cutoff_)),
-    isCbetaStatisticsFlag_(false)
+                                    lower_cutoff_, upper_cutoff_))
 {
   upper_sqr_=upper_cutoff_*upper_cutoff_;
   lower_sqr_=lower_cutoff_*lower_cutoff_;
@@ -170,49 +168,6 @@ void InteractionStatistics::Set(atom::ChemType a, atom::ChemType b,
 }
 
 
-void InteractionStatistics::RepairCbetaStatistics()
-{
- int num=int((upper_cutoff_-
-               lower_cutoff_)/bucket_size_);
-
- for (int k=0; k<num; ++k) {
-   for (int i=1; i<atom::UNKNOWN; ++i) {
-    for (int j=1; j<atom::UNKNOWN; ++j) {
-      //all C_alpha counts of non-glycine atome need to be asigned to Cbeta
-      if (this->GetCount(atom::ChemType(i), atom::ChemType(j),k) != 0 &&
-          this->GetCount(atom::ChemType(i-1), atom::ChemType(j-1),k) != 0) {
-        this->Set(atom::ChemType(i), atom::ChemType(j),k,
-                  this->GetCount(atom::ChemType(i), atom::ChemType(j), k) +
-                  this->GetCount(atom::ChemType(i-1), atom::ChemType(j-1),k));
-        this->Set(atom::ChemType(i-1), atom::ChemType(j-1),k,0);
-      }
-
-      if (this->GetCount(atom::ChemType(i), atom::ChemType(j),k) != 0 &&
-          this->GetCount(atom::ChemType(i), atom::ChemType(j-1),k) != 0) {
-        this->Set(atom::ChemType(i), atom::ChemType(j), k,
-                  this->GetCount(atom::ChemType(i), atom::ChemType(j),k) +
-                  this->GetCount(atom::ChemType(i), atom::ChemType(j-1),k));
-        this->Set(atom::ChemType(i), atom::ChemType(j-1),k,0);
-      }
-
-      if (this->GetCount(atom::ChemType(i), atom::ChemType(j),k) != 0 &&
-          this->GetCount(atom::ChemType(i-1), atom::ChemType(j),k) != 0) {
-        this->Set(atom::ChemType(i), atom::ChemType(j),k,
-                  this->GetCount(atom::ChemType(i), atom::ChemType(j), k) +
-                  this->GetCount(atom::ChemType(i-1), atom::ChemType(j),k));
-        this->Set(atom::ChemType(i-1), atom::ChemType(j),k,0);
-      }
-
-    }
-   }
-  }
-
-  isCbetaStatisticsFlag_ = true;
-
-
-}
-
-
 template <typename DS>
 void InteractionStatistics::Serialize(DS& ds)
 {
diff --git a/modules/qa/src/interaction_statistics.hh b/modules/qa/src/interaction_statistics.hh
index a1e8eeb48e1c2eee1efb969eb74a17987968335f..ca66774bdfd4f1ae47c490fdb169d70cb791062c 100644
--- a/modules/qa/src/interaction_statistics.hh
+++ b/modules/qa/src/interaction_statistics.hh
@@ -95,15 +95,6 @@ public:
   ///        account.
   void Set(atom::ChemType a, atom::ChemType b, int distance_bin, int counts);
 
-  
-  /// for Cbeta potentials:
-  /// in the initial selection Cbetas are counted and, if a residue
-  /// has no Cbeta, the Calpha is taken instead.
-  /// Afterwards the statistics needs to be corrected:
-  /// Calpha counts are Cbeta counts ...
-  void RepairCbetaStatistics();
-
-
   /// \internal
   template <typename DS>
   void Serialize(DS& ds);
@@ -111,9 +102,6 @@ public:
   virtual bool VisitResidue(const mol::ResidueHandle& r);
   virtual bool VisitAtom(const mol::AtomHandle& a);
 
-  inline bool isCbetaStaistics() {return isCbetaStatisticsFlag_;}
-
-
 private:
   InteractionStatistics();
 
@@ -128,8 +116,6 @@ private:
   mol::EntityView        view_b_;
   AminoAcid              amino_acid_;
   InteractionHistogram   histogram_;
-
-  bool        isCbetaStatisticsFlag_;
 };
 
 }}
diff --git a/modules/qa/src/packing_potential.cc b/modules/qa/src/packing_potential.cc
index e7a473fd3ac496291c2c459da974ae930fec9548..10a7de4aeb20f1642f743915bc3cab7719d7062c 100644
--- a/modules/qa/src/packing_potential.cc
+++ b/modules/qa/src/packing_potential.cc
@@ -187,10 +187,7 @@ bool PackingPotential::VisitAtom(const mol::AtomHandle& atom)
        e=views_.end(); i!=e; ++i) {
     count+=i->FindWithin(atom.GetPos(), options_.cutoff).size();
   }
-
-  count=count>options_.max_counts ? options_.max_counts : count;
-
-  energy_+=energies_.Get(aa, count/options_.bucket_size);
+  energy_+=this->GetPackingEnergy(aa, count);
   energy_counts_++;
   return false;
 }
diff --git a/modules/qa/src/packing_potential.hh b/modules/qa/src/packing_potential.hh
index dec0054f672319ab71d3ab108a907b18a46b1c9b..ea95ad86b498db88760a9dd3604e78c05b3041c6 100644
--- a/modules/qa/src/packing_potential.hh
+++ b/modules/qa/src/packing_potential.hh
@@ -84,10 +84,17 @@ public:
   /// 
   /// See documentation for PackingStatistics::Extract()
   Real GetTotalEnergy(const mol::EntityView& view, 
-                        const mol::EntityViewList& views);
+                      const mol::EntityViewList& views);
 
   int GetEnergyCounts();
   
+  
+  Real GetPackingEnergy(AminoAcid aa, int count) const
+  {
+    count=count>options_.max_counts ? options_.max_counts : count;
+    return energies_.Get(aa, count/options_.bucket_size);
+  }
+  const PackingPotentialOpts& GetOptions() const { return options_; }
   template <typename DS>
   void Serialize(DS& ds);
   
@@ -109,7 +116,7 @@ private:
   // used to calculate total energy...
   mol::EntityView        view_;
   mol::EntityViewList    views_;  
-  Real                 energy_;
+  Real                   energy_;
   int                    energy_counts_;
 };
 
diff --git a/modules/qa/src/packing_statistics.hh b/modules/qa/src/packing_statistics.hh
index 48266bd6e69d375777bc88c4e51d4af649af1c47..3e6ced0c553ecd22f1cbfc14ce3bb74100a86769 100644
--- a/modules/qa/src/packing_statistics.hh
+++ b/modules/qa/src/packing_statistics.hh
@@ -69,10 +69,10 @@ public:
   template <typename DS>
   void Serialize(DS& ds)
   {
-  ds & cutoff_;
-  ds & max_counts_;
-  ds & bucket_size_;
-  ds & histogram_;
+    ds & cutoff_;
+    ds & max_counts_;
+    ds & bucket_size_;
+    ds & histogram_;
   }
 
   Real            cutoff_;
diff --git a/modules/qa/src/reduced_potential.cc b/modules/qa/src/reduced_potential.cc
new file mode 100644
index 0000000000000000000000000000000000000000..b6c308e0cc2747893f0a91d084d6187c027ad9e5
--- /dev/null
+++ b/modules/qa/src/reduced_potential.cc
@@ -0,0 +1,153 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+
+#include <ost/io/binary_data_source.hh>
+#include <ost/io/binary_data_sink.hh>
+#include <ost/io/container_serialization.hh>
+#include "reduced_potential.hh"
+#include "impl/reduced_impl.hh"
+namespace ost { namespace qa {
+
+
+namespace {
+
+class ReducedEnergiesCalc : public impl::ReducedPotentialImpl {
+public:
+
+  ReducedEnergiesCalc(const ReducedStatOptions& opts, ReducedEnergies& energies,
+                      mol::EntityHandle ent, bool norm): 
+    impl::ReducedPotentialImpl(opts, ent),
+    energies_(energies), energy_(0.0), norm_(norm), count_(0)
+  { }
+  ReducedEnergiesCalc(const ReducedStatOptions& opts, ReducedEnergies& energies,
+                      mol::EntityView ent, bool norm): 
+    impl::ReducedPotentialImpl(opts, ent),
+    energies_(energies), energy_(0.0), norm_(norm), count_(0)
+  { }
+  virtual void OnInteraction(AminoAcid aa_one, AminoAcid aa_two, 
+                             Real dist, Real angle)
+  {
+    //std::cout << aa_one << " " << aa_two << " " << dist  << " " << angle << std::endl;
+    energy_+=energies_.Get(aa_one, aa_two, dist, angle);
+    count_+=1;
+  }
+  
+  Real GetEnergy() const 
+  {
+    if (norm_) {
+      return count_ > 0 ? energy_ /count_ : 0.0;
+    }
+    return energy_;
+  }
+private:
+  ReducedEnergies&   energies_;
+  Real energy_;
+  bool norm_;
+  uint64_t count_;
+};
+
+
+}
+
+bool ReducedPotential::GetCAlphaCBetaPos(const mol::ResidueHandle& res, 
+                                         geom::Vec3& ca_pos, 
+                                         geom::Vec3& cb_pos)
+{
+  return impl::ReducedPotentialImpl::GetCAlphaCBetaPos(res, ca_pos, cb_pos);
+}
+
+ReducedPotentialPtr ReducedPotential::Load(const String& filename)
+{
+  std::ifstream stream(filename.c_str(), std::ios_base::binary);
+  io::BinaryDataSource ds(stream);
+  ReducedPotentialPtr p(new ReducedPotential);
+  ds >> *p.get();
+  return p;
+}
+
+
+ReducedPotentialPtr ReducedPotential::Create(const ReducedStatisticsPtr& stat)
+{
+  ReducedPotentialPtr pot(new ReducedPotential);
+  pot->opts_=stat->GetOptions();
+  pot->energies_=ReducedEnergies(0.0, IntegralClassifier(20, 0), 
+                                 IntegralClassifier(20, 0),
+                                 ContinuousClassifier(pot->opts_.num_dist_bins, 
+                                                      pot->opts_.lower_cutoff, 
+                                                      pot->opts_.upper_cutoff),
+                                 ContinuousClassifier(pot->opts_.num_angular_bins, 
+                                                      0.0, M_PI));
+  pot->InitFromStats(stat);
+  return pot;
+}
+
+void ReducedPotential::InitFromStats(const ReducedStatisticsPtr& stats)
+{
+    typedef ReducedEnergies::IndexType Index;
+    uint64_t total_count=stats->GetTotalCount();
+    for (size_t i=0; i<Xxx; ++i) {
+      for (size_t j=0; j<Xxx; ++j) {
+        uint64_t t2=stats->GetCount(AminoAcid(i), AminoAcid(j));
+        for (size_t k=0; k<opts_.num_dist_bins; ++k) {
+          for (size_t l=0; l<opts_.num_angular_bins; ++l) {
+            uint64_t t3=stats->GetCount(AminoAcid(i), AminoAcid(j), k, l);
+            // could be moved outside of the loop and cached...
+            uint64_t t4=stats->GetCount(k, l);
+            float f1=t2 > 0 ?(float(t3)/float(t2)) : 0.0;
+            float f2=total_count > 0 ? (float(t4)/float(total_count)) : 0.0;
+            float d = f2>1e-10 ? f1/f2: 0.0;
+            float e=0.582*(log(1+0.02*t2)-log(1+0.02*t2*d));
+            energies_.Set(Index(i, j, k, l), e);
+          }
+        }
+      }
+    }
+}
+
+void ReducedPotential::Save(const String& filename)
+{  
+  std::ofstream stream(filename.c_str(), std::ios_base::binary);
+  io::BinaryDataSink ds(stream);
+  ds << *this;
+}
+
+
+template <typename DS>
+void ReducedPotential::Serialize(DS& ds)
+{
+  ds & opts_;
+  ds & energies_;
+}
+
+Real ReducedPotential::GetTotalEnergy(ost::mol::EntityHandle ent, bool norm)
+{
+  ReducedEnergiesCalc calc(opts_, energies_, ent, norm);
+  ent.Apply(calc);
+  return calc.GetEnergy();
+}
+
+Real ReducedPotential::GetTotalEnergy(ost::mol::EntityView ent, bool norm)
+{
+  ReducedEnergiesCalc calc(opts_, energies_, ent.GetHandle(), norm);
+  ent.Apply(calc);
+  return calc.GetEnergy();
+}
+
+
+}}
diff --git a/modules/qa/src/reduced_potential.hh b/modules/qa/src/reduced_potential.hh
new file mode 100644
index 0000000000000000000000000000000000000000..0f90debce307e003657877c1d9caec0c56b75f2a
--- /dev/null
+++ b/modules/qa/src/reduced_potential.hh
@@ -0,0 +1,78 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#ifndef OST_QA_REDUCED_POTENTIAL_HH
+#define OST_QA_REDUCED_POTENTIAL_HH
+
+#include <ost/qa/reduced_statistics.hh>
+
+
+namespace ost { namespace qa {
+
+
+class ReducedPotential;
+  
+typedef boost::shared_ptr<ReducedPotential> ReducedPotentialPtr;
+
+typedef MultiClassifier<float, int, int, float, float> ReducedEnergies;
+/// \brief reduced model statistical potential operating on the residue level
+class DLLEXPORT_OST_QA ReducedPotential {
+public:
+
+  
+  
+  static ReducedPotentialPtr Create(const ReducedStatisticsPtr& stats);
+  static ReducedPotentialPtr Load(const String& filename);
+  
+  void Save(const String& filename);
+  
+  
+  template <typename DS>
+  void Serialize(DS& ds);
+  
+  const ReducedStatOptions& GetOptions() const { return opts_; }
+  
+  Real GetTotalEnergy(ost::mol::EntityHandle ent, bool normalize=true);
+  
+  Real GetTotalEnergy(ost::mol::EntityView ent, bool normalize=true);
+  static bool GetCAlphaCBetaPos(const mol::ResidueHandle& res, 
+                                geom::Vec3& ca_pos, 
+                                geom::Vec3& cb_pos);
+
+  Real GetEnergy(AminoAcid aa_one, AminoAcid aa_two, 
+                 Real ca_dist, Real angle) const
+  {
+    if (aa_one==Xxx || aa_two==Xxx) { return 0.0; }
+    if (ca_dist<opts_.lower_cutoff || ca_dist>=opts_.upper_cutoff) {
+      return 0.0;
+    }
+    if (angle<0.0 || angle>M_PI) { return 0.0; }
+    return energies_.Get(aa_one, aa_two, ca_dist, angle);
+  }
+private:
+  void InitFromStats(const ReducedStatisticsPtr& stats);
+  ReducedPotential() { }
+  
+  ReducedStatOptions opts_;
+  ReducedEnergies    energies_;
+};
+
+
+}}
+
+#endif
diff --git a/modules/qa/src/reduced_statistics.cc b/modules/qa/src/reduced_statistics.cc
new file mode 100644
index 0000000000000000000000000000000000000000..3a75afe840c6c03640e9e4c64719ba34638ee304
--- /dev/null
+++ b/modules/qa/src/reduced_statistics.cc
@@ -0,0 +1,152 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+
+#include <ost/log.hh>
+#include <ost/mol/mol.hh>
+#include "amino_acids.hh"
+#include "reduced_statistics.hh"
+#include "impl/reduced_impl.hh"
+
+#include <ost/io/binary_data_source.hh>
+#include <ost/io/binary_data_sink.hh>
+#include <ost/io/container_serialization.hh>
+
+namespace ost { namespace qa {
+
+
+namespace {
+
+class ReducedStatExtractor : public impl::ReducedPotentialImpl {
+public:
+  
+  ReducedStatExtractor(const ReducedStatOptions& opts, ReducedHistogram& histo,
+                       mol::EntityHandle ent): 
+    impl::ReducedPotentialImpl(opts, ent),
+    histo_(histo)
+  { }
+  
+  ReducedStatExtractor(const ReducedStatOptions& opts, ReducedHistogram& histo,
+                       mol::EntityView ent): 
+    impl::ReducedPotentialImpl(opts, ent),
+    histo_(histo)
+  { }
+  
+  virtual void OnInteraction(AminoAcid aa_one, AminoAcid aa_two, 
+                             Real dist, Real angle)
+  {
+    histo_.Add(1, aa_one, aa_two, dist, angle);
+  }
+private:
+  ReducedHistogram&   histo_;
+};
+
+
+}
+
+uint64_t ReducedStatistics::GetTotalCount() const
+{
+  typedef ReducedHistogram::IndexType Index;
+  uint64_t count=0;
+  for (size_t i=0; i<Xxx; ++i) {
+    for (size_t j=0; j<Xxx; ++j) {
+      for (size_t k=0; k<opts_.num_dist_bins; ++k) {
+        for (size_t l=0; l<opts_.num_angular_bins; ++l) {
+          count+=histo_.Get(Index(i, j, k, l));
+        }
+      }
+    }
+  }
+  return count;
+}
+
+uint64_t ReducedStatistics::GetCount(AminoAcid aa_one, AminoAcid aa_two) const
+{
+  typedef ReducedHistogram::IndexType Index;
+  uint64_t count=0;
+  for (size_t k=0; k<opts_.num_dist_bins; ++k) {
+    for (size_t l=0; l<opts_.num_angular_bins; ++l) {
+      count+=histo_.Get(Index(aa_one, aa_two, k, l));
+    }
+  }
+  return count;
+}
+
+uint64_t ReducedStatistics::GetCount(int dist_bin, int ang_bin) const
+{
+  typedef ReducedHistogram::IndexType Index;
+  uint64_t count=0;
+  for (size_t i=0; i<Xxx; ++i) {
+    for (size_t j=0; j<Xxx; ++j) {
+      count+=histo_.Get(Index(i, j, dist_bin, ang_bin));
+    }
+  }
+  return count;
+}
+
+void ReducedStatistics::Save(const String& filename)
+{
+  std::ofstream stream(filename.c_str(), std::ios_base::binary);
+  io::BinaryDataSink ds(stream);
+  ds << *this;
+}
+
+
+ReducedStatisticsPtr ReducedStatistics::Load(const String& filename)
+{
+  std::ifstream stream(filename.c_str(), std::ios_base::binary);
+  io::BinaryDataSource ds(stream);
+  ReducedStatisticsPtr p(new ReducedStatistics);
+  ds >> *p.get();
+  return p;
+}
+
+template <typename DS>
+void ReducedStatistics::Serialize(DS& ds)
+{
+  ds & opts_;
+  ds & histo_;
+}
+
+
+void ReducedStatistics::Extract(mol::EntityHandle ent)
+{
+  if (ent.GetChainCount()!=1) {
+    std::stringstream ss;
+    ss << "Expected exactly one chain, but entity has " 
+       <<  ent.GetChainCount() << " chains";
+    throw std::runtime_error(ss.str());
+  }
+  ReducedStatExtractor extractor(opts_, histo_, ent);
+  ent.Apply(extractor);
+}
+
+void ReducedStatistics::Extract(mol::EntityView ent)
+{
+  if (ent.GetChainCount()!=1) {
+    std::stringstream ss;
+    ss << "Expected exactly one chain, but entity has " 
+       <<  ent.GetChainCount() << " chains";
+    throw std::runtime_error(ss.str());
+  }
+  ReducedStatExtractor extractor(opts_, histo_, ent.GetHandle());
+  ent.Apply(extractor);
+}
+
+
+}}
\ No newline at end of file
diff --git a/modules/qa/src/reduced_statistics.hh b/modules/qa/src/reduced_statistics.hh
new file mode 100644
index 0000000000000000000000000000000000000000..7d1a24800cc85f0363181705b1dabd2c579d7d7e
--- /dev/null
+++ b/modules/qa/src/reduced_statistics.hh
@@ -0,0 +1,123 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2010 by the OpenStructure authors
+//
+// This library 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 3.0 of the License, or (at your option)
+// any later version.
+// This library 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 this library; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+//------------------------------------------------------------------------------
+#ifndef OST_QA_REDUCED_STATISTICS_HH
+#define OST_QA_REDUCED_STATISTICS_HH
+
+#include <ost/qa/histogram.hh>
+#include <ost/qa/amino_acids.hh>
+namespace ost { 
+
+namespace mol {
+
+class EntityHandle;
+
+}  
+namespace qa {
+
+/// \brief aggregates the option for the reduced model statistics
+struct DLLEXPORT_OST_QA ReducedStatOptions {
+  ReducedStatOptions(): lower_cutoff(0), upper_cutoff(0), 
+                        num_angular_bins(0), num_dist_bins(0), 
+                        sequence_sep(0)
+  { }
+  
+  ReducedStatOptions(Real l_cutoff, Real u_cutoff, uint n_ang_bins, 
+                     uint n_dist_bins, uint ssep):
+    lower_cutoff(l_cutoff), upper_cutoff(u_cutoff), 
+    num_angular_bins(n_ang_bins), num_dist_bins(n_dist_bins),
+    sequence_sep(ssep)
+  { }
+  Real lower_cutoff;
+  Real upper_cutoff;
+  uint num_angular_bins;
+  uint num_dist_bins;
+  uint sequence_sep;
+  
+  
+  template <typename DS>
+  void Serialize(DS& ds)
+  {
+    ds & lower_cutoff;
+    ds & upper_cutoff;
+    ds & num_angular_bins;
+    ds & num_dist_bins;
+    ds & sequence_sep;
+  }
+};
+
+
+class ReducedStatistics;
+typedef boost::shared_ptr<ReducedStatistics> ReducedStatisticsPtr;
+
+
+// parametrized as first amino acid, second amino acid, 
+// calpha-calpha distance, angle
+typedef Histogram<int, int, float, float>  ReducedHistogram;
+
+class DLLEXPORT_OST_QA ReducedStatistics {
+public:
+  ReducedStatistics(Real l_cutoff, Real u_cutoff, uint num_ang_bins, 
+                    uint num_dist_bins, uint ssep):
+    opts_(l_cutoff, u_cutoff, num_ang_bins, num_dist_bins, ssep),
+    histo_(IntegralClassifier(20, 0), IntegralClassifier(20, 0),
+           ContinuousClassifier(num_dist_bins, l_cutoff, u_cutoff),
+           ContinuousClassifier(num_ang_bins, 0.0, M_PI))
+  { }
+  
+  const ReducedStatOptions& GetOptions() const { return opts_; }
+  
+  /// \brief extract the statistics from the given entity (handle)
+  void Extract(mol::EntityHandle ent);
+  
+  /// \brief extract statistics from given entity (view)
+  void Extract(mol::EntityView ent);
+  
+  void Save(const String& filename);
+  
+  
+  static ReducedStatisticsPtr Load(const String& filename);
+  /// \internal
+  template <typename DS>
+  void Serialize(DS& ds);
+  
+  uint64_t GetTotalCount() const;
+  
+  uint64_t GetCount(AminoAcid aa_one, AminoAcid aa_two) const;
+  
+  
+  uint64_t GetCount(AminoAcid aa_one, AminoAcid aa_two, int dist_bin, 
+                    int ang_bin)
+  {
+    return histo_.Get(ReducedHistogram::IndexType(aa_one, aa_two, dist_bin, 
+                                                  ang_bin));
+  }
+  
+  uint64_t GetCount(int dist_bin, int ang_bin) const;
+private:
+  ReducedStatistics(): opts_(), histo_() {}
+  ReducedStatOptions opts_;
+  ReducedHistogram  histo_;
+};
+
+
+
+}}
+
+
+#endif
diff --git a/modules/qa/src/torsion_potential.cc b/modules/qa/src/torsion_potential.cc
index 651718a4f04bc0d53faf6fadf3dd1ab8eb328e0c..2ecf8c655f24de49220a00be1b09b24d1e14b856 100644
--- a/modules/qa/src/torsion_potential.cc
+++ b/modules/qa/src/torsion_potential.cc
@@ -16,6 +16,7 @@
 // along with this library; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 //------------------------------------------------------------------------------
+
 #include "torsion_potential.hh"
 #include "amino_acids.hh"
 
@@ -39,10 +40,9 @@ namespace {
 
 class TorsionEnergyCalc : public mol::EntityVisitor {
 public:
-  TorsionEnergyCalc(TorsionPotential::TorsionEnergies& energies, 
+  TorsionEnergyCalc(const TorsionPotentialPtr& pot, 
                     TorsionPotentialOpts opts):
-    energies_(energies), energy_(0.0),
-    opts_(opts), num_torsions_(0)
+    pot_(pot), energy_(0.0), num_torsions_(0)
   {
   }
   
@@ -75,24 +75,16 @@ public:
     Real next_phi=next_phit.GetAngle()*180/M_PI - 0.001; if (next_phi<-180) next_phi=-180;
     Real next_psi=next_psit.GetAngle()*180/M_PI - 0.001; if (next_psi<-180) next_psi=-180;
 
+    
     // calculate position of the amino acid in the alphabet
-    int icenter=this->GetAAIndex(ca);
-
-    if (icenter >-1) {
-      energy_+=energies_.Get(icenter, prev_phi, prev_psi,
-                             central_phi, central_psi,
-                             next_phi, next_psi);
-      num_torsions_++;
-    } 
-    else {
-      LOG_INFO("Amino acid not found in alphabets...");
-    }
+    energy_+=pot_->GetTorsionEnergy(ca, prev_phi, prev_psi, central_phi, 
+                                    central_psi, next_phi, next_psi);
+    ++num_torsions_;
     return false;
   }
 
   Real GetEnergy() const {
     return energy_;
-    //return num_torsions_==0?0:energy_/num_torsions_;
   }
 
   int GetEnergyCounts() const {
@@ -100,29 +92,11 @@ public:
   }
 
 private:
-  int GetAAIndex(AminoAcid aa)
-  {
-    return this->GetIndex(aa, opts_.alphabet);
-  }
-
-  
-  int GetIndex(AminoAcid aa, AminoAcidAlphabet& alpha) {
-    AminoAcidAlphabet::iterator i=alpha.begin();
-    for (int index=0; i!=alpha.end(); ++i, ++index) {
-      if ((*i).Contains(aa)) {
-        return index;        
-      }
-
-    }
-    return -1;
-  }
-private:
-  TorsionPotential::TorsionEnergies& energies_;
+  TorsionPotentialPtr pot_;
   AminoAcid prev_;
   AminoAcid center_;
   mol::ResidueHandle cr_;
   Real energy_;  
-  TorsionPotentialOpts opts_;  
   int    num_torsions_;  
 };
 
@@ -153,6 +127,18 @@ TorsionPotentialOpts::TorsionPotentialOpts():
 }
 
 
+int TorsionPotential::GetAAIndex(AminoAcid aa) const 
+{
+  AminoAcidAlphabet::const_iterator i=options_.alphabet.begin();
+  for (int index=0; i!=options_.alphabet.end(); ++i, ++index) {
+    if ((*i).Contains(aa)) {
+      return index;        
+    }
+  }
+  return -1;
+}
+
+
 TorsionPotentialPtr TorsionPotential::Create(TorsionStatisticsPtr statistics,
                                              const TorsionPotentialOpts& opts,
                                              bool calculate_average_energy_flag)
@@ -225,7 +211,7 @@ void TorsionPotential::SaveToFile(const String& path)
 
 Real TorsionPotential::GetTotalEnergy(mol::EntityHandle entity) 
 {
-  TorsionEnergyCalc c(energies_, options_);  
+  TorsionEnergyCalc c(this->shared_from_this(), options_);  
   entity.Apply(c);  
   num_torsions_ = c.GetEnergyCounts();
   return c.GetEnergy();
@@ -233,7 +219,7 @@ Real TorsionPotential::GetTotalEnergy(mol::EntityHandle entity)
 
 Real TorsionPotential::GetTotalEnergy(mol::EntityView entity) 
 {
-  TorsionEnergyCalc c(energies_, options_);
+  TorsionEnergyCalc c(this->shared_from_this(), options_);
   entity.Apply(c);
   num_torsions_ = c.GetEnergyCounts();
   return c.GetEnergy();
diff --git a/modules/qa/src/torsion_potential.hh b/modules/qa/src/torsion_potential.hh
index 68faeb24fc2ab71cc4c261edf6d719452dd25201..d0048e84ccce0ada40901e93dd70fea536d57d04 100644
--- a/modules/qa/src/torsion_potential.hh
+++ b/modules/qa/src/torsion_potential.hh
@@ -30,6 +30,7 @@
 */
 #include <ost/qa/torsion_statistics.hh>
 #include <boost/shared_ptr.hpp>
+#include <boost/enable_shared_from_this.hpp>
 #include <vector>
 #include <boost/scoped_ptr.hpp>
 
@@ -67,7 +68,8 @@ typedef boost::shared_ptr<TorsionPotential> TorsionPotentialPtr;
 /// \brief Torsion potential
 /// 
 /// The torsion potential class is parametrisable by TorsionPotentialOpts.
-class DLLEXPORT_OST_QA TorsionPotential {
+class DLLEXPORT_OST_QA TorsionPotential : 
+   public boost::enable_shared_from_this<TorsionPotential> {
 public:
   /// \brief  create new torsion potential with the given torsion statistics 
   ///         and options
@@ -89,6 +91,18 @@ public:
 
   /// \brief retrieve total number of energy local (i.e. valid residues)
   int GetEnergyCounts() const;
+  
+  
+  
+  Real GetTorsionEnergy(AminoAcid central_aa, Real prev_phi, Real prev_psi,
+                        Real central_phi, Real central_psi,  
+                        Real next_phi, Real next_psi) const {
+    int icenter=this->GetAAIndex(central_aa);
+    return energies_.Get(icenter, prev_phi, prev_psi,
+                         central_phi, central_psi,
+                         next_phi, next_psi);
+  }
+                        
 
   /// \brief save torsion potential
   /// 
@@ -106,6 +120,9 @@ public:
   typedef MultiClassifier<float, int, Real, Real,
                           Real, Real, Real, Real> TorsionEnergies;
 private:
+  
+  int GetAAIndex(AminoAcid aa) const;
+  
   void Fill(const TorsionStatisticsPtr& stat,
             bool calculate_average_energy_flag);
 
diff --git a/modules/qa/src/torsion_statistics.hh b/modules/qa/src/torsion_statistics.hh
index 15f20089a5d8e7950621d79c347c612bbd0005d0..74ad15562e4a504ebd20dfa83645a7f67002ce44 100644
--- a/modules/qa/src/torsion_statistics.hh
+++ b/modules/qa/src/torsion_statistics.hh
@@ -70,8 +70,8 @@ public:
                   Real next_phi_angle, Real next_psi_angle) const;
                   
   uint64_t GetCount(Real prev_phi_angle, Real prev_psi_angle,
-                  Real central_phi_angle, Real central_psi_angle,
-                  Real next_phi_angle, Real next_psi_angle) const;
+                    Real central_phi_angle, Real central_psi_angle,
+                    Real next_phi_angle, Real next_psi_angle) const;
 
   uint64_t GetCount(const AminoAcidSet& central_aa) const;
 
diff --git a/modules/seq/alg/pymod/renumber.py b/modules/seq/alg/pymod/renumber.py
index 39ea9fb489949845fb65681ac1cbb6f000f4e56e..39f34ba7b0dc68b4c84421e6b14ac606a9ddc107 100644
--- a/modules/seq/alg/pymod/renumber.py
+++ b/modules/seq/alg/pymod/renumber.py
@@ -1,11 +1,11 @@
 from ost import io, seq, mol, conop
-import ost
+from ost import *
 
-def Renumber(seq_handle):
+def Renumber(seq_handle, sequence_number_with_attached_view=1):
   """
   Function to renumber an entity according to an alignment between the model sequence 
-  and the full-length target sequence. The aligned model sequence with an attached 
-  view needs to be provided. Upon succcess, the renumbered entity is returned.
+  and the full-length target sequence. The aligned model sequence or the alignment itself
+  with an attached view needs to be provided. Upon succcess, the renumbered entity is returned.
 
   .. code-block:: python
 
@@ -16,35 +16,70 @@ def Renumber(seq_handle):
     pdb_seq=seq.SequenceFromChain("model", ent.chains[0])
     aln=ClustalW(s,pdb_seq)
     aln.AttachView(1,ent.chains[0].Select(""))
-    e=Renumber(aln.GetSequence(1))
+    e=Renumber(aln.GetSequence(sequence_number_with_attached_view))
     io.SavePDB(e, "renum.pdb")
    
   """
-  if seq_handle.HasAttachedView()==False:
-    raise RuntimeError, "Sequence Handle has no attached view"
-  changed_residue_count=0
-  renumberingFlag = False
-  ent_n=mol.CreateEntity()
-  ed=ent_n.RequestXCSEditor()
-  c=ed.InsertChain(" ")
-  for pos in range(len(seq_handle)):
-    if seq_handle[pos]!='-':
-      r=seq_handle.GetResidue(pos)
-      if r.IsValid():
-          #print seq_handle[pos],r.number.num,pos+1
-          if r.number.num!=pos+1:
-            changed_residue_count+=1
-            renumberingFlag = True
-          r_n=ed.AppendResidue(c,r.name, mol.ResNum(pos+1))
-          for atom in r.atoms:
-            ed.InsertAtom(r_n,atom.name,atom.pos,atom.prop)
-      else:
-        err='Error: renumbering failed at position %s' %pos
-        raise RuntimeError, err
-  if renumberingFlag == True:
-    err = 'Warning: %s residues have been renumbered!' %changed_residue_count
-    ost.LogMessage(err)
-  conop.ConnectAll(ent_n)
-  return ent_n
+  if isinstance(seq_handle, seq.SequenceHandle):
+    if seq_handle.HasAttachedView()==False:
+      raise RuntimeError, "Sequence Handle has no attached view"
+    changed_residue_count=0
+    renumberingFlag = False
+    ent_n=mol.CreateEntity()
+    ed=ent_n.EditXCS()
+    c=ed.InsertChain(" ")
+    for pos in range(len(seq_handle)):
+      if seq_handle[pos]!='-':
+        r=seq_handle.GetResidue(pos)
+        if r.IsValid():
+            #print seq_handle[pos],r.number.num,pos+1
+            if r.number.num!=pos+1:
+              changed_residue_count+=1
+              renumberingFlag = True
+            r_n=ed.AppendResidue(c,r.name, mol.ResNum(pos+1))
+            for atom in r.atoms:
+              ed.InsertAtom(r_n,atom.name,atom.pos,atom.prop)
+        else:
+          err='Error: renumbering failed at position %s' %pos
+          raise RuntimeError, err
+    if renumberingFlag == True:
+      err = 'Warning: %s residues have been renumbered!' %changed_residue_count
+      LogInfo(err)
+    conop.ConnectAll(ent_n)
+    return ent_n
 
+  elif isinstance(seq_handle, seq.AlignmentHandle):
+    if seq_handle.GetSequence(sequence_number_with_attached_view).HasAttachedView()==False:
+      raise RuntimeError, "Sequence Handle has no attached view"
+    dir(seq_handle)
+    counter=0
+    changed_residue_count=0
+    renumberingFlag = False
+    ent_n=mol.CreateEntity()
+    ed=ent_n.EditXCS()
+    c=ed.InsertChain(seq_handle.GetSequence(sequence_number_with_attached_view).GetAttachedView().chains[0].name)
+    for col in seq_handle:
+      if col[0]!='-' and col[1]!='-':
+        if col[0]==col[1]:
+          rnum=seq_handle.GetSequence(sequence_number_with_attached_view).GetResidueIndex(counter)
+          r=seq_handle.GetSequence(sequence_number_with_attached_view).GetResidue(counter)
+          if r.IsValid():
+            if r.number.num!=counter+1:
+              changed_residue_count+=1
+              renumberingFlag = True
+            r_n=ed.AppendResidue(c,r.name, mol.ResNum(counter+1))
+            for atom in r.atoms:
+              ed.InsertAtom(r_n,atom.name,atom.pos,atom.element, atom.b_factor, 
+                            atom.occupancy, atom.is_hetatom)
+
+          else:
+            raise RuntimeError("invalide residue at postion %s (renumbering failed)" %(counter))
+        else:
+          raise RuntimeError("residue mismatch at position %d (%s vs %s) (renumbering failed)"%(counter, col[0],col[1]))
+      counter+=1
+    if renumberingFlag == True:
+      err = 'Warning: %s residues have been renumbered!' %changed_residue_count
+      LogInfo(err)
+    conop.ConnectAll(ent_n)
+    return ent_n
 
diff --git a/modules/seq/alg/tests/CMakeLists.txt b/modules/seq/alg/tests/CMakeLists.txt
index 37969a869b14c0f740f2b8e221509120f1cd1a6e..aafdabc4b723b7ee0ac6b978eb28cf34f95b5c23 100644
--- a/modules/seq/alg/tests/CMakeLists.txt
+++ b/modules/seq/alg/tests/CMakeLists.txt
@@ -2,6 +2,7 @@ set(OST_SEQ_ALG_UNIT_TESTS
   test_merge_pairwise_alignments.cc
   test_sequence_identity.cc
   tests.cc
+  test_renumber.py
 )
 
 ost_unittest(seq_alg "${OST_SEQ_ALG_UNIT_TESTS}")
diff --git a/modules/seq/alg/tests/test_renumber.py b/modules/seq/alg/tests/test_renumber.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d365a9b77ff2e0b9ffe80aad910cd428b599854
--- /dev/null
+++ b/modules/seq/alg/tests/test_renumber.py
@@ -0,0 +1,124 @@
+import unittest
+from ost import *
+from ost import settings
+from ost import seq
+from ost.bindings.clustalw import *
+from ost.seq.alg import renumber
+
+class TestRenumber(unittest.TestCase):
+  
+  def setUp(self):
+    self.target_seq = io.LoadSequence("testfiles/peptide.fasta")
+    self.peptide_original = io.LoadEntity("testfiles/peptide_original.pdb")
+    self.peptide_plus_5 = io.LoadEntity("testfiles/peptide_plus_5.pdb")
+    self.peptide_random = io.LoadEntity("testfiles/peptide_random.pdb")
+    self.peptide_del_1_2 = io.LoadEntity("testfiles/peptide_del_1_2.pdb")
+    self.peptide_del_4 = io.LoadEntity("testfiles/peptide_del_4.pdb")
+    self.peptide_mutation_3 = io.LoadEntity("testfiles/peptide_mutation_3.pdb")
+    
+
+  def testPeptidePlusFive(self):
+    """
+    All residue numbers shifted by 5.
+    Check whether internal atom order changes while renumbering
+    (a new entity is generated in the edit_mode)
+    TODO: add more basic tests: are all properties preserved?
+    """
+    model_seq=seq.SequenceFromChain(" ", self.peptide_plus_5.chains[0]) 
+    model_seq.name="model"
+    aln=ClustalW(self.target_seq,model_seq)
+    aln.AttachView(1,self.peptide_plus_5.Select(""))
+    ent_n=renumber.Renumber(aln)
+
+    for r_counter in range(len(self.peptide_original.residues)):
+      assert self.peptide_original.residues[r_counter].qualified_name == ent_n.residues[r_counter].qualified_name, \
+              "Renumbering failed on residue level: restoring from ResNum+5"
+      for atom_nr in range(len(self.peptide_original.residues[r_counter].atoms)):
+        assert self.peptide_original.residues[r_counter].atoms[atom_nr].name==ent_n.residues[r_counter].atoms[atom_nr].name, \
+                "Renumbering failed on atom level: restoring from ResNum+5"
+  
+
+  def testPeptideRandom(self):
+    """
+    Change residue names in random order
+    """
+    model_seq=seq.SequenceFromChain(" ", self.peptide_random.chains[0]) 
+    model_seq.name="model"
+    aln=ClustalW(self.target_seq,model_seq)
+    aln.AttachView(1,self.peptide_random.Select(""))
+    ent_n=renumber.Renumber(aln)
+
+    for r_counter in range(len(self.peptide_original.residues)):
+      assert self.peptide_original.residues[r_counter].qualified_name == ent_n.residues[r_counter].qualified_name, \
+             "Renumbering failed on residue level: restoring from random residue numbers"
+      for atom_nr in range(len(self.peptide_original.residues[r_counter].atoms)):
+        assert self.peptide_original.residues[r_counter].atoms[atom_nr].name==ent_n.residues[r_counter].atoms[atom_nr].name, \
+               "Renumbering failed on atom level: restoring from random residue numbers"
+
+
+  def testPeptideDel_1_2(self):
+    """
+    First two residues were removed
+    """
+    model_seq=seq.SequenceFromChain(" ", self.peptide_del_1_2.chains[0]) 
+    model_seq.name="model"
+    aln=ClustalW(self.target_seq,model_seq)
+    aln.AttachView(1,self.peptide_del_1_2.Select(""))
+    ent_n=renumber.Renumber(aln)
+
+    for r_counter in range(len(self.peptide_original.residues)):
+      if r_counter==0 or r_counter==1:
+        continue
+      assert self.peptide_original.residues[r_counter].qualified_name == ent_n.residues[r_counter-2].qualified_name, \
+             "Renumbering failed on residue level: restoring from random residue numbers"
+      for atom_nr in range(len(self.peptide_original.residues[r_counter].atoms)):
+        assert self.peptide_original.residues[r_counter].atoms[atom_nr].name==ent_n.residues[r_counter-2].atoms[atom_nr].name, \
+               "Renumbering failed on atom level: restoring from random residue numbers"
+
+
+  def testPeptideDel_4(self):
+    """
+    Residues in the middle (position 4) was removed
+    """
+    model_seq=seq.SequenceFromChain(" ", self.peptide_del_4.chains[0]) 
+    model_seq.name="model"
+    aln=ClustalW(self.target_seq,model_seq)
+    aln.AttachView(1,self.peptide_del_4.Select(""))
+    ent_n=renumber.Renumber(aln)
+
+    flag=0
+    for r_counter in range(len(self.peptide_original.residues)):
+      if r_counter==3:
+        flag=1
+        continue
+      assert self.peptide_original.residues[r_counter].qualified_name == ent_n.residues[r_counter-flag].qualified_name, \
+             "Renumbering failed on residue level: restoring from random residue numbers"
+      for atom_nr in range(len(self.peptide_original.residues[r_counter].atoms)):
+        assert self.peptide_original.residues[r_counter].atoms[atom_nr].name==ent_n.residues[r_counter-flag].atoms[atom_nr].name, \
+               "Renumbering failed on atom level: restoring from random residue numbers"
+
+
+  def testPeptideMutation_3(self):
+    """
+    Mutation to GLY at postion 3
+    """
+    model_seq=seq.SequenceFromChain(" ", self.peptide_mutation_3.chains[0]) 
+    model_seq.name="model"
+    aln=ClustalW(self.target_seq,model_seq)
+    aln.AttachView(1,self.peptide_mutation_3.Select(""))
+    self.assertRaises(RuntimeError, renumber.Renumber, aln)
+
+
+
+if __name__ == "__main__":
+  # test renumbering
+  # test if clustalw package is available on system, otherwise ignore tests
+  try:
+    clustalw_path=settings.Locate(('clustalw', 'clustalw2'))
+  except(settings.FileNotFound):
+    print "Could not find clustalw executable: ignoring unit tests"
+    exit(0)  
+  try:
+    unittest.main()
+  except Exception, e:
+    print e
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide.fasta b/modules/seq/alg/tests/testfiles/peptide.fasta
new file mode 100644
index 0000000000000000000000000000000000000000..8366b04ca04fb059f3d15348e964b9bdf8f4490e
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide.fasta
@@ -0,0 +1,2 @@
+>peptide
+MPTNA
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_del_1_2.pdb b/modules/seq/alg/tests/testfiles/peptide_del_1_2.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..06fc7e30a5bd50f197a3db75a8cda18ba1b5361f
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_del_1_2.pdb
@@ -0,0 +1,20 @@
+ATOM     16  N   THR     1     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  THR     1     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   THR     1     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   THR     1     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     20  CB  THR     1     -27.274  -7.369   8.683  1.00  0.00           C
+ATOM     21  OG1 THR     1     -28.080  -6.880   9.762  1.00  0.00           O
+ATOM     22  CG2 THR     1     -28.139  -8.227   7.772  1.00  0.00           C
+ATOM     23  N   ASN     2     -25.736  -7.349  11.452  1.00  0.00           N
+ATOM     24  CA  ASN     2     -25.104  -6.609  12.495  1.00  0.00           C
+ATOM     25  C   ASN     2     -23.742  -7.171  12.684  1.00  0.00           C
+ATOM     26  O   ASN     2     -22.806  -6.454  13.030  1.00  0.00           O
+ATOM     27  CB  ASN     2     -25.901  -6.728  13.795  1.00  0.00           C
+ATOM     28  CG  ASN     2     -27.189  -5.929  13.764  1.00  0.00           C
+ATOM     29  OD1 ASN     2     -27.340  -5.007  12.963  1.00  0.00           O
+ATOM     30  ND2 ASN     2     -28.124  -6.282  14.639  1.00  0.00           N
+ATOM     31  N   ALA     3     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA     3     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA     3     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA     3     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA     3     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_del_4.pdb b/modules/seq/alg/tests/testfiles/peptide_del_4.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..183ce9c57a125cc1bd0a16c7125b1fb13154de5d
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_del_4.pdb
@@ -0,0 +1,27 @@
+ATOM      1  N   MET     1     -29.037  -8.783  14.347  1.00  0.00           N
+ATOM      2  CA  MET     1     -28.985  -9.502  13.056  1.00  0.00           C
+ATOM      3  C   MET     1     -27.597  -9.852  12.665  1.00  0.00           C
+ATOM      4  O   MET     1     -26.614  -9.275  13.129  1.00  0.00           O
+ATOM      5  CB  MET     1     -29.575  -8.640  11.938  1.00  0.00           C
+ATOM      6  CG  MET     1     -31.084  -8.470  12.016  1.00  0.00           C
+ATOM      7  SD  MET     1     -31.752  -7.534  10.628  1.00  0.00           S
+ATOM      8  CE  MET     1     -33.497  -7.530  11.030  1.00  0.00           C
+ATOM      9  N   PRO     2     -27.533 -10.838  11.828  1.00  0.00           N
+ATOM     10  CA  PRO     2     -26.273 -11.293  11.337  1.00  0.00           C
+ATOM     11  C   PRO     2     -25.709 -10.233  10.478  1.00  0.00           C
+ATOM     12  O   PRO     2     -24.518 -10.265  10.186  1.00  0.00           O
+ATOM     13  CB  PRO     2     -26.616 -12.565  10.559  1.00  0.00           C
+ATOM     14  CG  PRO     2     -28.043 -12.386  10.161  1.00  0.00           C
+ATOM     15  CD  PRO     2     -28.699 -11.637  11.286  1.00  0.00           C
+ATOM     16  N   THR     3     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  THR     3     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   THR     3     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   THR     3     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     20  CB  THR     3     -27.274  -7.369   8.683  1.00  0.00           C
+ATOM     21  OG1 THR     3     -28.080  -6.880   9.762  1.00  0.00           O
+ATOM     22  CG2 THR     3     -28.139  -8.227   7.772  1.00  0.00           C
+ATOM     31  N   ALA     4     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA     4     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA     4     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA     4     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA     4     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_mutation_3.pdb b/modules/seq/alg/tests/testfiles/peptide_mutation_3.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..be9fa82c7d15a43b2a9d906466c33c74d0293fca
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_mutation_3.pdb
@@ -0,0 +1,32 @@
+ATOM      1  N   MET     1     -29.037  -8.783  14.347  1.00  0.00           N
+ATOM      2  CA  MET     1     -28.985  -9.502  13.056  1.00  0.00           C
+ATOM      3  C   MET     1     -27.597  -9.852  12.665  1.00  0.00           C
+ATOM      4  O   MET     1     -26.614  -9.275  13.129  1.00  0.00           O
+ATOM      5  CB  MET     1     -29.575  -8.640  11.938  1.00  0.00           C
+ATOM      6  CG  MET     1     -31.084  -8.470  12.016  1.00  0.00           C
+ATOM      7  SD  MET     1     -31.752  -7.534  10.628  1.00  0.00           S
+ATOM      8  CE  MET     1     -33.497  -7.530  11.030  1.00  0.00           C
+ATOM      9  N   PRO     2     -27.533 -10.838  11.828  1.00  0.00           N
+ATOM     10  CA  PRO     2     -26.273 -11.293  11.337  1.00  0.00           C
+ATOM     11  C   PRO     2     -25.709 -10.233  10.478  1.00  0.00           C
+ATOM     12  O   PRO     2     -24.518 -10.265  10.186  1.00  0.00           O
+ATOM     13  CB  PRO     2     -26.616 -12.565  10.559  1.00  0.00           C
+ATOM     14  CG  PRO     2     -28.043 -12.386  10.161  1.00  0.00           C
+ATOM     15  CD  PRO     2     -28.699 -11.637  11.286  1.00  0.00           C
+ATOM     16  N   GLY     3     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  GLY     3     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   GLY     3     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   GLY     3     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     23  N   ASN     4     -25.736  -7.349  11.452  1.00  0.00           N
+ATOM     24  CA  ASN     4     -25.104  -6.609  12.495  1.00  0.00           C
+ATOM     25  C   ASN     4     -23.742  -7.171  12.684  1.00  0.00           C
+ATOM     26  O   ASN     4     -22.806  -6.454  13.030  1.00  0.00           O
+ATOM     27  CB  ASN     4     -25.901  -6.728  13.795  1.00  0.00           C
+ATOM     28  CG  ASN     4     -27.189  -5.929  13.764  1.00  0.00           C
+ATOM     29  OD1 ASN     4     -27.340  -5.007  12.963  1.00  0.00           O
+ATOM     30  ND2 ASN     4     -28.124  -6.282  14.639  1.00  0.00           N
+ATOM     31  N   ALA     5     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA     5     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA     5     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA     5     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA     5     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_original.pdb b/modules/seq/alg/tests/testfiles/peptide_original.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..8068ae46b1353f2c52556919ef5cf89c2d5e5a1f
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_original.pdb
@@ -0,0 +1,35 @@
+ATOM      1  N   MET     1     -29.037  -8.783  14.347  1.00  0.00           N
+ATOM      2  CA  MET     1     -28.985  -9.502  13.056  1.00  0.00           C
+ATOM      3  C   MET     1     -27.597  -9.852  12.665  1.00  0.00           C
+ATOM      4  O   MET     1     -26.614  -9.275  13.129  1.00  0.00           O
+ATOM      5  CB  MET     1     -29.575  -8.640  11.938  1.00  0.00           C
+ATOM      6  CG  MET     1     -31.084  -8.470  12.016  1.00  0.00           C
+ATOM      7  SD  MET     1     -31.752  -7.534  10.628  1.00  0.00           S
+ATOM      8  CE  MET     1     -33.497  -7.530  11.030  1.00  0.00           C
+ATOM      9  N   PRO     2     -27.533 -10.838  11.828  1.00  0.00           N
+ATOM     10  CA  PRO     2     -26.273 -11.293  11.337  1.00  0.00           C
+ATOM     11  C   PRO     2     -25.709 -10.233  10.478  1.00  0.00           C
+ATOM     12  O   PRO     2     -24.518 -10.265  10.186  1.00  0.00           O
+ATOM     13  CB  PRO     2     -26.616 -12.565  10.559  1.00  0.00           C
+ATOM     14  CG  PRO     2     -28.043 -12.386  10.161  1.00  0.00           C
+ATOM     15  CD  PRO     2     -28.699 -11.637  11.286  1.00  0.00           C
+ATOM     16  N   THR     3     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  THR     3     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   THR     3     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   THR     3     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     20  CB  THR     3     -27.274  -7.369   8.683  1.00  0.00           C
+ATOM     21  OG1 THR     3     -28.080  -6.880   9.762  1.00  0.00           O
+ATOM     22  CG2 THR     3     -28.139  -8.227   7.772  1.00  0.00           C
+ATOM     23  N   ASN     4     -25.736  -7.349  11.452  1.00  0.00           N
+ATOM     24  CA  ASN     4     -25.104  -6.609  12.495  1.00  0.00           C
+ATOM     25  C   ASN     4     -23.742  -7.171  12.684  1.00  0.00           C
+ATOM     26  O   ASN     4     -22.806  -6.454  13.030  1.00  0.00           O
+ATOM     27  CB  ASN     4     -25.901  -6.728  13.795  1.00  0.00           C
+ATOM     28  CG  ASN     4     -27.189  -5.929  13.764  1.00  0.00           C
+ATOM     29  OD1 ASN     4     -27.340  -5.007  12.963  1.00  0.00           O
+ATOM     30  ND2 ASN     4     -28.124  -6.282  14.639  1.00  0.00           N
+ATOM     31  N   ALA     5     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA     5     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA     5     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA     5     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA     5     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_plus_5.pdb b/modules/seq/alg/tests/testfiles/peptide_plus_5.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..c64a572640047c0f784ecf3ccd733b4756f39f92
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_plus_5.pdb
@@ -0,0 +1,35 @@
+ATOM      1  N   MET     6     -29.037  -8.783  14.347  1.00  0.00           N
+ATOM      2  CA  MET     6     -28.985  -9.502  13.056  1.00  0.00           C
+ATOM      3  C   MET     6     -27.597  -9.852  12.665  1.00  0.00           C
+ATOM      4  O   MET     6     -26.614  -9.275  13.129  1.00  0.00           O
+ATOM      5  CB  MET     6     -29.575  -8.640  11.938  1.00  0.00           C
+ATOM      6  CG  MET     6     -31.084  -8.470  12.016  1.00  0.00           C
+ATOM      7  SD  MET     6     -31.752  -7.534  10.628  1.00  0.00           S
+ATOM      8  CE  MET     6     -33.497  -7.530  11.030  1.00  0.00           C
+ATOM      9  N   PRO     7     -27.533 -10.838  11.828  1.00  0.00           N
+ATOM     10  CA  PRO     7     -26.273 -11.293  11.337  1.00  0.00           C
+ATOM     11  C   PRO     7     -25.709 -10.233  10.478  1.00  0.00           C
+ATOM     12  O   PRO     7     -24.518 -10.265  10.186  1.00  0.00           O
+ATOM     13  CB  PRO     7     -26.616 -12.565  10.559  1.00  0.00           C
+ATOM     14  CG  PRO     7     -28.043 -12.386  10.161  1.00  0.00           C
+ATOM     15  CD  PRO     7     -28.699 -11.637  11.286  1.00  0.00           C
+ATOM     16  N   THR     8     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  THR     8     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   THR     8     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   THR     8     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     20  CB  THR     8     -27.274  -7.369   8.683  1.00  0.00           C
+ATOM     21  OG1 THR     8     -28.080  -6.880   9.762  1.00  0.00           O
+ATOM     22  CG2 THR     8     -28.139  -8.227   7.772  1.00  0.00           C
+ATOM     23  N   ASN     9     -25.736  -7.349  11.452  1.00  0.00           N
+ATOM     24  CA  ASN     9     -25.104  -6.609  12.495  1.00  0.00           C
+ATOM     25  C   ASN     9     -23.742  -7.171  12.684  1.00  0.00           C
+ATOM     26  O   ASN     9     -22.806  -6.454  13.030  1.00  0.00           O
+ATOM     27  CB  ASN     9     -25.901  -6.728  13.795  1.00  0.00           C
+ATOM     28  CG  ASN     9     -27.189  -5.929  13.764  1.00  0.00           C
+ATOM     29  OD1 ASN     9     -27.340  -5.007  12.963  1.00  0.00           O
+ATOM     30  ND2 ASN     9     -28.124  -6.282  14.639  1.00  0.00           N
+ATOM     31  N   ALA    10     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA    10     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA    10     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA    10     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA    10     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/alg/tests/testfiles/peptide_random.pdb b/modules/seq/alg/tests/testfiles/peptide_random.pdb
new file mode 100644
index 0000000000000000000000000000000000000000..74597e72bf51d7f8f0f6fcacb198dd14d16f7e3f
--- /dev/null
+++ b/modules/seq/alg/tests/testfiles/peptide_random.pdb
@@ -0,0 +1,35 @@
+ATOM      1  N   MET     6     -29.037  -8.783  14.347  1.00  0.00           N
+ATOM      2  CA  MET     6     -28.985  -9.502  13.056  1.00  0.00           C
+ATOM      3  C   MET     6     -27.597  -9.852  12.665  1.00  0.00           C
+ATOM      4  O   MET     6     -26.614  -9.275  13.129  1.00  0.00           O
+ATOM      5  CB  MET     6     -29.575  -8.640  11.938  1.00  0.00           C
+ATOM      6  CG  MET     6     -31.084  -8.470  12.016  1.00  0.00           C
+ATOM      7  SD  MET     6     -31.752  -7.534  10.628  1.00  0.00           S
+ATOM      8  CE  MET     6     -33.497  -7.530  11.030  1.00  0.00           C
+ATOM      9  N   PRO     1     -27.533 -10.838  11.828  1.00  0.00           N
+ATOM     10  CA  PRO     1     -26.273 -11.293  11.337  1.00  0.00           C
+ATOM     11  C   PRO     1     -25.709 -10.233  10.478  1.00  0.00           C
+ATOM     12  O   PRO     1     -24.518 -10.265  10.186  1.00  0.00           O
+ATOM     13  CB  PRO     1     -26.616 -12.565  10.559  1.00  0.00           C
+ATOM     14  CG  PRO     1     -28.043 -12.386  10.161  1.00  0.00           C
+ATOM     15  CD  PRO     1     -28.699 -11.637  11.286  1.00  0.00           C
+ATOM     16  N   THR     7     -26.565  -9.309  10.007  1.00  0.00           N
+ATOM     17  CA  THR     7     -26.102  -8.194   9.247  1.00  0.00           C
+ATOM     18  C   THR     7     -25.296  -7.372  10.186  1.00  0.00           C
+ATOM     19  O   THR     7     -24.295  -6.768   9.810  1.00  0.00           O
+ATOM     20  CB  THR     7     -27.274  -7.369   8.683  1.00  0.00           C
+ATOM     21  OG1 THR     7     -28.080  -6.880   9.762  1.00  0.00           O
+ATOM     22  CG2 THR     7     -28.139  -8.227   7.772  1.00  0.00           C
+ATOM     23  N   ASN     4     -25.736  -7.349  11.452  1.00  0.00           N
+ATOM     24  CA  ASN     4     -25.104  -6.609  12.495  1.00  0.00           C
+ATOM     25  C   ASN     4     -23.742  -7.171  12.684  1.00  0.00           C
+ATOM     26  O   ASN     4     -22.806  -6.454  13.030  1.00  0.00           O
+ATOM     27  CB  ASN     4     -25.901  -6.728  13.795  1.00  0.00           C
+ATOM     28  CG  ASN     4     -27.189  -5.929  13.764  1.00  0.00           C
+ATOM     29  OD1 ASN     4     -27.340  -5.007  12.963  1.00  0.00           O
+ATOM     30  ND2 ASN     4     -28.124  -6.282  14.639  1.00  0.00           N
+ATOM     31  N   ALA     2     -16.677  -4.828  10.806  1.00  0.00           N
+ATOM     32  CA  ALA     2     -15.984  -3.708  10.241  1.00  0.00           C
+ATOM     33  C   ALA     2     -15.498  -2.863  11.363  1.00  0.00           C
+ATOM     34  O   ALA     2     -14.369  -2.378  11.344  1.00  0.00           O
+ATOM     35  CB  ALA     2     -16.917  -2.901   9.352  1.00  0.00           C
\ No newline at end of file
diff --git a/modules/seq/base/doc/seq.rst b/modules/seq/base/doc/seq.rst
index 243ec0d49108938923169456f4ba9e9cef8a927f..ade28f583e7b10f8dd9d7e0a4337e52347480b0b 100644
--- a/modules/seq/base/doc/seq.rst
+++ b/modules/seq/base/doc/seq.rst
@@ -17,10 +17,11 @@ Attaching Structures to Sequences
 --------------------------------------------------------------------------------
 
 
-Being a structural biology framework, it is not surprising that the sequence 
-classes have been designed to work together with structural data. Each sequence 
-can have an attached :class:`~mol.EntityView` allowing for fast mapping between 
-residues in the entity view and position in the sequence. 
+As OpenStructure is a computational structural biology framework, it is not
+surprising that the sequence classes have been designed to work together with
+structural data. Each sequence can have an attached :class:`~mol.EntityView`
+allowing for fast mapping between residues in the entity view and position in
+the sequence.
 
 .. _sequence-offset:
 
diff --git a/modules/seq/base/pymod/export_sequence.cc b/modules/seq/base/pymod/export_sequence.cc
index ab36fdaed36c6fd40b3d8669b0a135b0a0cef3bd..b3632fc507db5bdf281a80c7384173a70fe7e0d0 100644
--- a/modules/seq/base/pymod/export_sequence.cc
+++ b/modules/seq/base/pymod/export_sequence.cc
@@ -301,6 +301,7 @@ void export_sequence()
     .def("GetLength", &AlignmentHandle::GetLength)
     .def("__len__", &AlignmentHandle::GetLength)
     .def("GetSequences", &AlignmentHandle::GetSequences)
+    .def("GetCoverage", &AlignmentHandle::GetSequences)
     .def("AttachView", attach_view_a)
     .def("AttachView", attach_view_b)
     .def("Cut", &AlignmentHandle::Cut)
diff --git a/modules/seq/base/src/alignment_handle.cc b/modules/seq/base/src/alignment_handle.cc
index d2a7ab85d387051d43edbadac9419925b5ac7fee..bf2c12fdf61f3a16e340891915011011f8c25fa0 100644
--- a/modules/seq/base/src/alignment_handle.cc
+++ b/modules/seq/base/src/alignment_handle.cc
@@ -263,4 +263,12 @@ int AlignmentHandle::GetSequenceOffset(int seq_index)
   this->CheckValidity();
   return impl_->GetSequence(seq_index)->GetOffset();
 }
+
+Real AlignmentHandle::GetCoverage(int seq_index) const
+{
+  this->CheckValidity();
+  return impl_->GetCoverage(seq_index);
+}
+
+
 }}
diff --git a/modules/seq/base/src/alignment_handle.hh b/modules/seq/base/src/alignment_handle.hh
index bcba027d92f718fb0d874e96361dfc4f0387ffbd..823e78be1ef5e2e7ade4e5c0f690df9d1190f261 100644
--- a/modules/seq/base/src/alignment_handle.hh
+++ b/modules/seq/base/src/alignment_handle.hh
@@ -158,6 +158,13 @@ public:
   iterator end() const;
 
   bool IsValid() const { return impl_.get()!=0; }
+    
+  ///\brief get coverage of a specifi sequence 
+  ///
+  /// returns a value representing how extensively the specified sequence
+  /// covers the first sequence (sequence 0). The function return a value
+  /// between 0 (no coverage) and 1 (full coverage)
+  Real GetCoverage(int seq_index) const;
   
 private:
   void CheckValidity() const;
diff --git a/modules/seq/base/src/impl/sequence_list_impl.cc b/modules/seq/base/src/impl/sequence_list_impl.cc
index b955d8b4cf1244e144d9c3bed82b4688b47afbed..16759dbcf67dbc1d71d356dfca886b2922dd5fd3 100644
--- a/modules/seq/base/src/impl/sequence_list_impl.cc
+++ b/modules/seq/base/src/impl/sequence_list_impl.cc
@@ -178,4 +178,22 @@ SequenceListImplPtr SequenceListImpl::Slice(int first, int n) const
   }
 }
 
+Real SequenceListImpl::GetCoverage(int seq_index) const
+{
+  int a=0, b=0;
+  String seq_string_0 = GetSequence(0)->GetString();
+  String seq_string_index = GetSequence(seq_index)->GetString();
+  for (int i=0; i<GetSequence(0)->GetLength(); ++i) {
+    if (seq_string_0[i]!='-') {
+      a+=1;
+      if (seq_string_index[i]!='-') {
+        b+=1;
+      }
+    }
+  }
+  Real coverage=Real(b)/Real(a);
+  return coverage;
+}
+
+
 }}}
diff --git a/modules/seq/base/src/impl/sequence_list_impl.hh b/modules/seq/base/src/impl/sequence_list_impl.hh
index 66bedd61f47c4cb5d40374b92dfc94c2213ecee9..ab382b8c8faf98687757f7c916c2c92ccc36207a 100644
--- a/modules/seq/base/src/impl/sequence_list_impl.hh
+++ b/modules/seq/base/src/impl/sequence_list_impl.hh
@@ -78,7 +78,7 @@ public:
     return this->GetMaxLength()==this->GetMinLength();
   }
 
-
+  Real GetCoverage(int seq_index) const;
 
   SequenceListImplPtr Copy() const;
 
diff --git a/modules/seq/base/tests/test_aligned_column.cc b/modules/seq/base/tests/test_aligned_column.cc
index f76573df3c883f7f91b076442dae9900e0c5a42e..757c8d8cb5496119324f0e666388b390b7ee2929 100644
--- a/modules/seq/base/tests/test_aligned_column.cc
+++ b/modules/seq/base/tests/test_aligned_column.cc
@@ -43,7 +43,7 @@ struct Fixture {
   Fixture() {
     eh = CreateEntity();
     eh.SetName("TestEntity");
-    XCSEditor e=eh.RequestXCSEditor();
+    XCSEditor e=eh.EditXCS();
     chain = e.InsertChain("A");
     res1 = e.AppendResidue(chain, "ARG");
     e.InsertAtom(res1, "CA",geom::Vec3(1,0,0));
diff --git a/modules/seq/base/tests/test_alignment.cc b/modules/seq/base/tests/test_alignment.cc
index 0491f7d35c124c846b5ddd48cee8965e77492025..b4ee98a40f8cb53fd92b2d749d0e121e45e81b3c 100644
--- a/modules/seq/base/tests/test_alignment.cc
+++ b/modules/seq/base/tests/test_alignment.cc
@@ -38,7 +38,7 @@ struct Fixture {
   Fixture() {
     eh = CreateEntity();
     eh.SetName("TestEntity");
-    XCSEditor e=eh.RequestXCSEditor();
+    XCSEditor e=eh.EditXCS();
     chain = e.InsertChain("A");
     res1 = e.AppendResidue(chain, "ARG");
     e.InsertAtom(res1, "CA",geom::Vec3(1,0,0));
@@ -74,6 +74,15 @@ BOOST_AUTO_TEST_CASE(alignment_triv)
   BOOST_CHECK_NO_THROW(AlignmentFromSequenceList(list));
 }
 
+BOOST_AUTO_TEST_CASE(aln_throw_invalid)
+{
+  AlignmentHandle s;
+  BOOST_CHECK_THROW(CheckHandleValidity(s), InvalidHandle);
+  s=CreateAlignment();
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(s));
+}
+
+
 BOOST_AUTO_TEST_CASE(alignment_count_and_length)
 {
   AlignmentHandle a = CreateAlignment();
diff --git a/modules/seq/base/tests/test_seq.py b/modules/seq/base/tests/test_seq.py
index 26abba6896e53f32f19ef43cb4d44e5999bb6c2f..80f13e364c07e3ba9665f34e62a462af79ae79ec 100644
--- a/modules/seq/base/tests/test_seq.py
+++ b/modules/seq/base/tests/test_seq.py
@@ -6,7 +6,7 @@ from ost import seq
 
 def fixture():
   e=mol.CreateEntity()
-  ede=e.RequestXCSEditor()
+  ede=e.EditXCS()
   chain=ede.InsertChain('A')
   for res in 'ABCDEFGH':
     r=ede.AppendResidue(chain, res)
diff --git a/modules/seq/base/tests/test_sequence.cc b/modules/seq/base/tests/test_sequence.cc
index e787aafb7c3de95e8d93c2b55de8b3b9bba7c8f4..d628e14dd9c5ec10df82817c864f68bcc097dbd7 100644
--- a/modules/seq/base/tests/test_sequence.cc
+++ b/modules/seq/base/tests/test_sequence.cc
@@ -34,7 +34,7 @@ struct Fixture {
   Fixture() {
     eh = CreateEntity();
     eh.SetName("TestEntity");
-    XCSEditor e=eh.RequestXCSEditor();
+    XCSEditor e=eh.EditXCS();
     chain = e.InsertChain("A");
     res1 = e.AppendResidue(chain, "ARG");
     e.InsertAtom(res1, "CA",geom::Vec3(1,0,0));
@@ -65,6 +65,14 @@ BOOST_AUTO_TEST_CASE(seq_triv)
   BOOST_CHECK_THROW(s.SetString("1"), InvalidSequence);
 }
 
+BOOST_AUTO_TEST_CASE(seq_throw_invalid)
+{
+  SequenceHandle s;
+  BOOST_CHECK_THROW(CheckHandleValidity(s), InvalidHandle);
+  s=CreateSequence("A", "abcd");
+  BOOST_CHECK_NO_THROW(CheckHandleValidity(s));
+}
+
 BOOST_AUTO_TEST_CASE(seq_length)
 {
   SequenceHandle s=CreateSequence("S1", "abfcdadeaf");
diff --git a/scripts/bump-version.py b/scripts/bump-version.py
new file mode 100755
index 0000000000000000000000000000000000000000..85c3c1063502110c982407fe46f193dcfbc54c85
--- /dev/null
+++ b/scripts/bump-version.py
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+import sys
+out=[]
+version=sys.argv[1].split('.')
+if len(version)==2:
+  major, minor, patch=(int(version[0]), int(version[1]), 0)
+else:
+  major, minor, patch=(int(version[0]), int(version[1]), int(version[2]))
+for line in open('modules/config/version.hh'):
+  if line.startswith('#define OST_VERSION_MAJOR'):
+    out.append('#define OST_VERSION_MAJOR %d\n' % major)
+  elif line.startswith('#define OST_VERSION_MINOR'):
+    out.append('#define OST_VERSION_MINOR %d\n' % minor)
+  elif line.startswith('#define OST_VERSION_PATCH'):
+    out.append('#define OST_VERSION_PATCH %d\n' % patch)
+  elif line.startswith("#define OST_VERSION_STRING"):
+    out.append('#define OST_VERSION_STRING "%d.%d.%d"\n' % (major,minor,patch))
+  else:
+    out.append(line)
+
+open('modules/config/version.hh', 'w').write(''.join(out))
\ No newline at end of file
diff --git a/scripts/init.py b/scripts/init.py
index e175e08446fbcb198294093850999b1f3dade0ea..732120f6da62d07aab5176e5fbe70d31e983149f 100644
--- a/scripts/init.py
+++ b/scripts/init.py
@@ -1,212 +1,3 @@
-import __main__
-import sys
-import os.path
-import optparse
-from ost import io, mol, seq, geom, conop, gui, settings
-import ost
-try: 
-  from ost import img
-  import ost.img.alg
-  _img_present=True
-except ImportError:
-  _img_present=False
-  pass
-import httplib
-
-from PyQt4 import QtGui, QtCore
-from ost.gui.scene.init_inspector import _InitInspector
-from ost.gui.init_menubar import _InitMenuBar
-from ost.gui.init_spacenav import _InitSpaceNav
-from ost.gui.init_context_menu import _InitContextMenu
-from ost.gui.init_splash import _InitSplash
-from ost.gui.dng import termuse
-
-from PyQt4.QtGui import *
-def _my_exit(code):
-  QtGui.QApplication.instance().quit()
-  gui.GostyApp.Instance().ProcessEvents()
-  sys._exit(code)
-
-sys._exit=sys.exit
-sys.exit=_my_exit
-
-def _InitRuleBasedBuilder():
-  compound_lib_path=os.path.join(ost.GetSharedDataPath(), 'compounds.chemlib')
-  if os.path.exists(compound_lib_path):
-    conop_inst=conop.Conopology.Instance()
-    compound_lib=conop.CompoundLib.Load(compound_lib_path)
-    conop_inst.RegisterBuilder(conop.RuleBasedBuilder(compound_lib), 'RBB')
-    conop_inst.SetDefaultBuilder('RBB')
-
-# switch to rule-based builder for high fidelity if compounds.chemlib is 
-# available
-_InitRuleBasedBuilder()
-
-def _CheckRestore():
-  settings = QtCore.QSettings()
-  restore = settings.value("restore_settings",QtCore.QVariant(False)).toBool()
-  if not restore:
-    settings.clear()
-  settings.setValue("restore_settings",QtCore.QVariant(True))
-
-def _InitPanels(app):
-  panels = app.perspective.panels
-  panels.AddWidgetToPool('ost.gui.FileBrowser', -1)
-  panels.AddWidgetToPool('ost.gui.PythonShell', 1)
-  panels.AddWidgetToPool('ost.gui.RemoteLoader', -1)
-  panels.AddWidgetToPool('ost.gui.SceneWin', 1)
-  panels.AddWidgetToPool('ost.gui.SequenceViewer', 1)
-  panels.AddWidgetToPool('ost.gui.MessageWidget', 1)
-  if not panels.Restore("ui/perspective/panels"):
-    panels.AddWidget(gui.PanelPosition.LEFT_PANEL, app.scene_win)
-    panels.AddWidgetByName(gui.PanelPosition.LEFT_PANEL, 
-                           'ost.gui.FileBrowser', False)    
-    panels.AddWidgetByName(gui.PanelPosition.LEFT_PANEL, 
-                           'ost.gui.RemoteLoader', False)
-    panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.seq_viewer)
-    panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.py_shell)
-    panels.AddWidget(gui.PanelPosition.RIGHT_PANEL, app.message_widget)
-    return False
-  return True
-
-
-def _InitFrontEnd():
-  _CheckRestore()
-  app=gui.GostyApp.Instance()
-  app.SetAppTitle("DNG")
-  main_area=app.perspective.main_area
-  _InitMenuBar(app)
-  _InitSpaceNav(app)
-  _InitContextMenu(app)
-  main_area.AddPersistentWidget("3D Scene", "gl_win" , app.gl_win, int(QtCore.Qt.WindowMaximized))
-  app.perspective.Restore()
-  additional_modules=getattr(__main__, 'ADDITIONAL_GUI_MODULES', [])
-  for module_name in additional_modules:
-    __import__(module_name)
-  app.ProcessEvents()
-
-  _InitInspector(app)
-  
-  if not _InitPanels(app):
-    _InitSplash()
-  
-def _load_files():
-  for pdb_id in options.pdb_ids:
-    pdb_id, sel=_SplitIDSel(pdb_id)
-    selection=_get_selection_query(sel)
-    gui.FileLoader.LoadFrom(pdb_id,"pdb.org",selection)
-    
-  input_files=[_SplitIDSel(arg) for arg in loading_list]
-  for f in input_files:
-    selection=_get_selection_query(f[1])
-    gui.FileLoader.LoadObject(f[0],selection)
-
-def _get_selection_query(sel):
-  if len(options.query)>0:
-    if len(sel)>0:
-      return '(%s) and (%s)' % (options.query, sel)
-    else:
-      return options.query
-  elif len(sel)>0:
-    return sel
-  return ""
-
-def _execute_script():
-  script=script_argv[0]
-  sys_argv_backup=sys.argv
-  sys.argv=script_argv
-  try:
-    execfile(script, __main__.__dict__)
-  finally:
-    sys.argv=sys_argv_backup     
-
-def show_help(option, opt, value, parser):
-  parser.print_help()
-  QtGui.QApplication.instance().exit()
-  sys.exit(-1)
-
-def parse_script_option(option, opt, value, parser):
-  script_argv.append(value)
-  for arg in parser.rargs:
-     script_argv.append(arg)
-  del parser.rargs[0:len(parser.rargs)]
-
-def _SplitIDSel(name):
-  pos=name.find('[')
-  if pos>-1:
-    return name[:pos], name[pos+1:-1]
-  return name, ''  
-
-loading_list=[]
-script_argv=[]
-images=[]
-viewers=[]
-usage = 'usage: dng [options] [files to load]'
-class OstOptionParser(optparse.OptionParser):
-  def __init__(self, **kwargs):
-    optparse.OptionParser.__init__(self, **kwargs)
-  def exit(self, status_code, error_message):
-    print error_message,
-    QtGui.QApplication.instance().exit()
-    sys.exit(-1)
-
-parser=OstOptionParser(usage=usage,conflict_handler="resolve")
-parser.add_option("-h", "--help", action="callback", callback=show_help, help="show this help message and exit")
-parser.add_option("-v", "--verbosity_level", action="store", type="int", dest="vlevel", default=2, 
-                  help="sets the verbosity level [default: %default]")
-parser.add_option("-s", "--script", action="callback", default=[], dest="script", type="string", callback=parse_script_option, help="executes a script (syntax: -s SCRIPT [options] [args]) Anything that follows this option is passed to the script")
-parser.add_option("-p", "--pdb_id", dest="pdb_ids", default=[],action="append", help="PDB file ID. The file will be retrieved from PDB")
-parser.add_option("-b", "--builder", dest="builder", default="HEURISTIC", help="Type of builder used by the progam (either RULE_BASED or HEURISTIC) [default: %default]")
-parser.add_option("-c", "--compound_library", dest="complib", default="compounds.chemlib", help="Compound library for the RULE_BASED builder (only used if --builder option is set to RULE_BASED, otherwise ignored [default: %default]")
-parser.add_option("-q", "--query", dest="query", default="", help="Selection query to be highlighted automatically upon loading (only used together with -p option or when a PDB file is loaded, otherwise ignored [default: None]")
-parser.disable_interspersed_args()
-(options, args) = parser.parse_args()
-
-if len(parser.rargs)!=0:
-  for rargs_string in parser.rargs:
-    if not rargs_string.endswith('.py'):  
-      loading_list.append(rargs_string)
-    else:
-      print 'Error:  one of the files to load is a Python script, use -s flag to execute it\n'
-      QtGui.QApplication.instance().exit()
-      sys.exit(-1)    
-
-if len(options.script)!=0:
-  script_argv=options.script
-
-if options.builder=="RULE_BASED":
-  from ost import conop
-  compound_lib=conop.CompoundLib.Load(options.complib)
-  rbb=conop.RuleBasedBuilder(compound_lib)
-  conop.Conopology.Instance().RegisterBuilder(rbb,'rbb')
-  conop.Conopology.Instance().SetDefaultBuilder('rbb')
-
-home = os.getenv('HOME') or os.getenv('USERPROFILE')
-_ostrc=os.path.join(home, '.ostrc')
-if os.path.exists(_ostrc):
-  try:
-    exec(open(_ostrc))
-  except Exception, e:
-    print e
-else:
-  rcfile=open(_ostrc,"w")
-  print >> rcfile, '# This python file is parsed by ost and dng at startup'
-  print >> rcfile, '# Its content is made available in the global namespace'
-  print >> rcfile, '# It can be used to define custom variables and functions'
-  print >> rcfile, '# For example:'
-  print >> rcfile, '# IMPORTANT_DIR="path/to/important/dir"'
-  rcfile.close()
-
-PushVerbosityLevel(options.vlevel)
-working_dir=settings.GetValue("DNG_WORKING_DIR",None)
-
-if working_dir != None and os.path.isdir(working_dir):
-  os.chdir(working_dir)
-
-_InitFrontEnd()
-
-if len(loading_list)!=0 or len(options.pdb_ids)!=0:
-  _load_files()
-  scene.Autoslab()
-if len(script_argv)!=0:
-  _execute_script()
+from ost import *
+from ost import gui
+import ost.gui.dng.init
\ No newline at end of file
diff --git a/scripts/init_cl.py b/scripts/init_cl.py
index fba11d8adb9fa5a6f6b9baca7905b9de55c028e5..b173207477f1620c5ea7c60c617210223ba5ea75 100644
--- a/scripts/init_cl.py
+++ b/scripts/init_cl.py
@@ -10,6 +10,9 @@ def show_help(option, opt, value, parser):
 def interactive_flag(option, opt, value, parser):
   pass
 
+def stop():
+  sys.exit(0)
+
 usage = 'usage: ost [ost options] [script to execute] [script parameters]'
 class OstOptionParser(optparse.OptionParser):
   def __init__(self, **kwargs):