diff --git a/CMakeLists.txt b/CMakeLists.txt
index 346da8a262f31c8093787c5a933e9aca18c63aa5..08d517d1b6384426a4a4088a7f7a2aba23d92e15 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -6,7 +6,7 @@ cmake_minimum_required(VERSION 2.6.4 FATAL_ERROR)
 project(OpenStructure CXX C)
 set (OST_VERSION_MAJOR 1)
 set (OST_VERSION_MINOR 2)
-set (OST_VERSION_PATCH 1)
+set (OST_VERSION_PATCH 2)
 set (OST_VERSION_STRING ${OST_VERSION_MAJOR}.${OST_VERSION_MINOR}.${OST_VERSION_PATCH} )
 set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/cmake_support)
 include(OST)
@@ -46,7 +46,6 @@ option(USE_DOUBLE_PRECISION "whether to compile in double precision"
 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 "whether unit tests should be compiled by default" OFF)
 option(ENABLE_STATIC "whether static libraries should be compiled" OFF)
 option(DEBIAN_STYLE_LIBEXEC "whether 'libexec' should be put under 'lib/openstructure" OFF)
@@ -306,9 +305,12 @@ endif()
 
 add_subdirectory(modules)
 add_subdirectory(scripts)
+add_subdirectory(tools)
+# deployment has to come last, to ensure that all install commands are run before deployment
+# magic is done
 add_subdirectory(deployment)
+
 set(FILES_TO_BE_REMOVED ${CMAKE_SOURCE_DIR}/stage tests)
-add_subdirectory(tools)
 set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES
                              "${FILES_TO_BE_REMOVED}")
 
diff --git a/build_configs/buildconfig_arch_clang b/build_configs/buildconfig_arch_clang
new file mode 100644
index 0000000000000000000000000000000000000000..b77971c56aca6baa9ac12ce82dfa4e6344c309bf
--- /dev/null
+++ b/build_configs/buildconfig_arch_clang
@@ -0,0 +1,10 @@
+set(PYTHON_BINARY "/usr/bin/python2"  CACHE PATH "")
+set(CMAKE_C_COMPILER "/usr/bin/clang" CACHE PATH "")
+set(CMAKE_CXX_COMPILER "/usr/bin/clang++" CACHE PATH "")
+set(CMAKE_AR "/usr/bin/llvm-ar" CACHE PATH "")
+set(CMAKE_LINKER "/usr/bin/llvm-ld" CACHE PATH "")
+set(CMAKE_NM "/usr/bin/llvm-inm" CACHE PATH "")
+set(CMAKE_OBJDUMP "/usr/bin/llvm-objdump" CACHE PATH "")
+set(CMAKE_RANLIB "/usr/bin/llvm-ranlib" CACHE PATH "")
+set(CMAKE_CXX_FLAGS_RELEASE "-Wno-array-bounds -pthread -O3 -DNDEBUG -Wno-parentheses -Wno-constant-logical-operand -fcolor-diagnostics" CACHE STRING "")
+set(CMAKE_CXX_FLAGS_DEBUG "-Wno-array-bounds -g -pthread -Wno-parentheses -Wno-constant-logical-operand -fcolor-diagnostics" CACHE STRING "")
diff --git a/cmake_support/CheckLSBTypes.cmake b/cmake_support/CheckLSBTypes.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..93857bfa4967fc8ff6088d0b82b130b9dacb65cd
--- /dev/null
+++ b/cmake_support/CheckLSBTypes.cmake
@@ -0,0 +1,70 @@
+# - If included, system dependent information types like lsb_release name, architecture type
+#   and some other useful information stored for global CMAKE use
+#
+#   !!! The content of these variables should not be used in cross compilation projects !!!
+#
+# Copyright (C) 2011 by Michael Goetting  <mgoettin at techfak dot uni-bielefeld dot de>
+#
+# This file may be licensed under the terms of the
+# GNU Lesser General Public License Version 3 (the ``LGPL''),
+# or (at your option) any later version.
+#
+# Software distributed under the License is distributed
+# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
+# express or implied. See the LGPL for the specific language
+# governing rights and limitations.
+#
+# You should have received a copy of the LGPL along with this
+# program. If not, go to http://www.gnu.org/licenses/lgpl.html
+# or write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# The development of this software was supported by:
+#   CoR-Lab, Research Institute for Cognition and Robotics
+#     Bielefeld University
+
+SET(LSB_DISTRIBUTOR_ID "unkown")
+SET(LSB_RELEASE "unkown")
+SET(LSB_CODENAME "unkown")
+SET(LSB_BIT_TYPE "unkown")
+SET(LSB_ARCH_TYPE "unkown")
+
+# ---- (mgoettin 10/17/2011) TODO: Update this to match all OS ----
+SET(LSB_PROCESSOR_ARCH ${CMAKE_SYSTEM_PROCESSOR})
+
+# ---- Get the system bit type ----
+IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
+  SET(LSB_BIT_TYPE 64)
+ELSE()
+  SET(LSB_BIT_TYPE 32)    
+ENDIF() 
+
+# ---- Get the system LSB data ----
+IF(UNIX)
+  
+    FIND_PROGRAM(LSB_RELEASE_EXECUTABLE lsb_release)
+    IF(LSB_RELEASE_EXECUTABLE)
+        # ---- Get the distribution codename ----
+        EXECUTE_PROCESS(COMMAND ${LSB_RELEASE_EXECUTABLE} -s -c
+          OUTPUT_VARIABLE TMP_LSB_CODENAME
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+        STRING(TOLOWER ${TMP_LSB_CODENAME} LSB_CODENAME)
+        # ---- Get the release name ----
+        EXECUTE_PROCESS(COMMAND ${LSB_RELEASE_EXECUTABLE} -s -r
+          OUTPUT_VARIABLE TMP_LSB_RELEASE
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+        STRING(TOLOWER ${TMP_LSB_RELEASE} LSB_RELEASE)
+        # ---- Get the distributor id ----
+        EXECUTE_PROCESS(COMMAND ${LSB_RELEASE_EXECUTABLE} -s -i
+          OUTPUT_VARIABLE TMP_LSB_DISTRIBUTOR_ID
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+        STRING(TOLOWER ${TMP_LSB_DISTRIBUTOR_ID} LSB_DISTRIBUTOR_ID)
+        
+        MESSAGE(STATUS "LSB-Release system information::
+           LSB Distributor-ID: ${LSB_DISTRIBUTOR_ID}
+           LSB Release: ${LSB_RELEASE}
+           LSB Codename: ${LSB_CODENAME}
+           System bit type: ${LSB_BIT_TYPE} bit")
+       
+    ENDIF(LSB_RELEASE_EXECUTABLE) 
+ENDIF(UNIX)
diff --git a/cmake_support/CopyDependencies.cmake b/cmake_support/CopyDependencies.cmake
new file mode 100644
index 0000000000000000000000000000000000000000..ae48aaa8867e499c9cda736aaae59132496c0a87
--- /dev/null
+++ b/cmake_support/CopyDependencies.cmake
@@ -0,0 +1,899 @@
+#-------------------------------------------------------------------------------
+#  Author:  Andreas Schenk
+#
+#  This file contains functions to determine, copy and verify the dependencies
+#  of the application bundle.
+#
+#  Part of this code was taken from BundleUtilities.cmake, distributed
+#  under the OSI-approved BSD License (see below), and adapted.
+#-------------------------------------------------------------------------------
+
+#  CMake - Cross Platform Makefile Generator
+#  Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
+#  All rights reserved.
+#  
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions
+#  are met:
+#  
+#  * Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#  
+#  * Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in the
+#    documentation and/or other materials provided with the distribution.
+#  
+#  * Neither the names of Kitware, Inc., the Insight Software Consortium,
+#    nor the names of their contributors may be used to endorse or promote
+#    products derived from this software without specific prior written
+#    permission.
+#  
+#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+#  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+#=============================================================================
+# function copy dependencies
+#=============================================================================
+function(copy_dependencies binaries)
+  #--------------------------------------------------------------------------
+  message("copy dependencies: resolving binary paths")
+  #--------------------------------------------------------------------------
+  message(STATUS "  binaries='${binaries}'")
+  set(resolved_binaries)
+  foreach(binary ${binaries})
+    get_filename_component(resolved_binary ${binary} REALPATH)
+    if(NOT ${resolved_binary} MATCHES ${CMAKE_INSTALL_PREFIX})
+      message(FATAL_ERROR "Binary path: '${resolved_binary}' points to outside bundle.")
+    endif(NOT ${resolved_binary} MATCHES ${CMAKE_INSTALL_PREFIX})
+    list(APPEND resolved_binaries ${resolved_binary})
+  endforeach(binary)
+  list(REMOVE_DUPLICATES resolved_binaries)
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: determining dependencies")
+  #--------------------------------------------------------------------------
+  collect_dependencies("${resolved_binaries}" keys)
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: copying files")
+  #--------------------------------------------------------------------------
+  list(LENGTH keys n)
+  math(EXPR n ${n}*2)
+
+  set(i 0)
+  foreach(key ${keys})
+    math(EXPR i ${i}+1)
+    if(${${key}_COPYFLAG})
+      message(STATUS "${i}/${n}: copying '${${key}_RESOLVED_ITEM}' to '${${key}_RESOLVED_EMBEDDED_ITEM}'")
+      set(item "${${key}_ITEM}")
+      copy_resolved_item("${${key}_RESOLVED_ITEM}" "${${key}_RESOLVED_EMBEDDED_ITEM}")
+    else(${${key}_COPYFLAG})
+      message(STATUS "${i}/${n}: *NOT* copying '${${key}_RESOLVED_ITEM}'")
+    endif(${${key}_COPYFLAG})
+  endforeach(key)
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: changing install names")
+  #--------------------------------------------------------------------------
+  foreach(key ${keys})
+    math(EXPR i ${i}+1)
+    if(APPLE)
+      if(NOT ${${key}_SYSTEMFLAG})
+        message(STATUS "${i}/${n}: changing install names for '${${key}_RESOLVED_EMBEDDED_ITEM}'")
+        change_install_names_for_item(keys "${key}")
+      else(NOT ${${key}_SYSTEMFLAG})
+        message(STATUS "${i}/${n}: skipping install name change for system library: '${${key}_RESOLVED_EMBEDDED_ITEM}'")
+      endif(NOT ${${key}_SYSTEMFLAG})
+    else(APPLE)
+      message(STATUS "${i}/${n}: changing install names not required on this platform '${${key}_RESOLVED_EMBEDDED_ITEM}'")
+    endif(APPLE)
+  endforeach(key)
+
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: verifying binaries")
+  #--------------------------------------------------------------------------
+  verify(keys)
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: cleaning up")
+  #--------------------------------------------------------------------------
+  clear_keys(keys)
+
+  #--------------------------------------------------------------------------
+  message("copy dependencies: done")
+  #--------------------------------------------------------------------------
+endfunction(copy_dependencies)
+
+#=============================================================================
+# function collect_dependencies
+#=============================================================================
+function(collect_dependencies binaries keys_var)
+  set(${keys_var} PARENT_SCOPE)
+
+  # First add all binaries to the keys. 
+  # This is done before dependency resolution because one of the binaries could
+  # potentially be a dependency. 
+  foreach(exe ${binaries})
+    get_filename_component(exepath "${exe}" PATH)
+    set_keys_for_item(${keys_var} "${exe}" "${exe}" 0 0)
+  endforeach(exe)
+
+  # Get dependencies and add them to the keys.
+  foreach(exe ${binaries})
+    get_filename_component(exepath "${exe}" PATH)
+    add_dependencies_for_item(${keys_var}  "${exe}" "${exepath}")
+  endforeach(exe)
+
+  # Propagate values to caller's scope:
+  set(${keys_var} ${${keys_var}} PARENT_SCOPE)
+  foreach(key ${${keys_var}})
+    set(${key}_ITEM "${${key}_ITEM}" PARENT_SCOPE)
+    set(${key}_RESOLVED_ITEM "${${key}_RESOLVED_ITEM}" PARENT_SCOPE)
+    set(${key}_RESOLVED_EMBEDDED_ITEM "${${key}_RESOLVED_EMBEDDED_ITEM}" PARENT_SCOPE)
+    set(${key}_COPYFLAG "${${key}_COPYFLAG}" PARENT_SCOPE)
+    set(${key}_SYSTEMFLAG "${${key}_SYSTEMFLAG}" PARENT_SCOPE)
+  endforeach(key)
+
+endfunction(collect_dependencies)
+
+
+
+
+#=============================================================================
+# function set_keys_for_item
+#=============================================================================
+function(set_keys_for_item keys_var context resolved_item copyflag systemflag)
+  get_item_key("${resolved_item}" key)
+  list(LENGTH ${keys_var} length_before)
+  append_unique(${keys_var} "${key}")
+  list(LENGTH ${keys_var} length_after)
+
+  if(NOT length_before EQUAL length_after)
+    if(${copyflag} AND (NOT ${systemflag}) )
+      resolve_embedded_item("${resolved_item}" resolved_embedded_item)
+      set(${key}_RESOLVED_EMBEDDED_ITEM "${resolved_embedded_item}" PARENT_SCOPE)
+      if(${resolved_embedded_item} STREQUAL ${resolved_item})
+        set(${key}_COPYFLAG 0 PARENT_SCOPE)
+      else(${resolved_embedded_item} STREQUAL ${resolved_item})
+        set(${key}_COPYFLAG 1 PARENT_SCOPE)
+      endif(${resolved_embedded_item} STREQUAL ${resolved_item})
+      set(${key}_SYSTEMFLAG 0 PARENT_SCOPE)
+    else(${copyflag} AND (NOT ${systemflag}) )
+      set(${key}_COPYFLAG ${copyflag} PARENT_SCOPE)
+      set(${key}_SYSTEMFLAG ${systemflag} PARENT_SCOPE)
+      set(${key}_RESOLVED_EMBEDDED_ITEM "${resolved_item}" PARENT_SCOPE)
+    endif(${copyflag} AND (NOT ${systemflag}) )
+    set(${keys_var} ${${keys_var}} PARENT_SCOPE)
+    get_filename_component(item_name "${resolved_item}" NAME)
+    set(${key}_ITEM "${item_name}" PARENT_SCOPE)
+    set(${key}_RESOLVED_ITEM "${resolved_item}" PARENT_SCOPE)
+
+  else(NOT length_before EQUAL length_after)
+    message(FATAL_ERROR "Item key '${key}' already in the list. This should not happen.")
+  endif(NOT length_before EQUAL length_after)
+endfunction(set_keys_for_item)
+
+#=============================================================================
+# function get_item_key
+#=============================================================================
+function(get_item_key item key_var)
+  get_filename_component(item_name "${item}" REALPATH)
+  if(WIN32)
+    string(TOLOWER "${item_name}" item_name)
+  endif()
+  string(REGEX REPLACE "\\." "_" item_name "${item_name}")
+  string(REGEX REPLACE "/" "_"   item_name "${item_name}")
+  string(REGEX REPLACE "\\\\" "_" ${key_var} "${item_name}")
+  set(${key_var} ${${key_var}} PARENT_SCOPE)
+endfunction(get_item_key)
+
+
+#=============================================================================
+# function clear_keys
+#=============================================================================
+function(clear_keys keys_var)
+  foreach(key ${${keys_var}})
+    set(${key}_ITEM PARENT_SCOPE)
+    set(${key}_RESOLVED_ITEM PARENT_SCOPE)
+    set(${key}_RESOLVED_EMBEDDED_ITEM PARENT_SCOPE)
+    set(${key}_COPYFLAG PARENT_SCOPE)
+    set(${key}_SYSTEMFLAG PARENT_SCOPE)
+  endforeach(key)
+  set(${keys_var} PARENT_SCOPE)
+endfunction(clear_keys)
+
+
+
+#=============================================================================
+# function resolve_item
+#=============================================================================
+function(resolve_item context item exepath resolved_item_var)
+  set(resolved_item "${item}")
+
+  # @rpath references are relative to the paths built into the binaries with -rpath
+  # rpath resolution comes first, as the rpath might contain a @loader_path or @executable_path reference
+  if(resolved_item MATCHES "@rpath")
+    get_rpath("${context}" rpath)
+    string(REPLACE "@rpath/" "${rpath}/" resolved_item "${resolved_item}")
+  endif(resolved_item MATCHES "@rpath")
+
+  # @executable_path references are assumed relative to exepath
+  if(resolved_item MATCHES "@executable_path")
+    string(REPLACE "@executable_path" "${exepath}" resolved_item "${resolved_item}")
+  endif(resolved_item MATCHES "@executable_path")
+
+  # @loader_path references are assumed relative to the
+  # PATH of the given "context" (presumably another library)
+  if(resolved_item MATCHES "@loader_path")
+    get_filename_component(contextpath "${context}" PATH)
+    string(REPLACE "@loader_path" "${contextpath}" resolved_item "${resolved_item}")
+  endif(resolved_item MATCHES "@loader_path")
+  
+  get_filename_component(resolved_item "${resolved_item}" REALPATH)
+
+  if(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
+    set(${resolved_item_var} "${resolved_item}" PARENT_SCOPE)
+    return()
+  endif(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
+
+  set(ri "ri-NOTFOUND")
+  find_file(ri "${item}" ${exepath}  NO_DEFAULT_PATH)
+  find_file(ri "${item}" ${exepath}  /usr/lib)
+  if(WIN32 AND NOT UNIX)
+    find_program(ri "${item}" PATHS "${exepath}" NO_DEFAULT_PATH)
+    find_program(ri "${item}" PATHS "${exepath}")
+  endif(WIN32 AND NOT UNIX)
+  if(ri)
+    set(resolved_item "${ri}")
+    set(ri "ri-NOTFOUND")
+  endif(ri)
+
+  if(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
+    set(${resolved_item_var} "${resolved_item}" PARENT_SCOPE)
+  else(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
+    message(FATAL_ERROR "cannot resolve item '${item}' in context:'${context}'. Partially resolved path is: '${resolved_item}'")
+  endif(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
+endfunction(resolve_item)
+
+
+#=============================================================================
+# function resolve_embedded_item
+#=============================================================================
+function(resolve_embedded_item item resolved_item_var)
+  if(${item} MATCHES ${CMAKE_INSTALL_PREFIX})
+    # item already embedded
+    set(${resolved_item_var} ${item} PARENT_SCOPE)
+  else(${item} MATCHES ${CMAKE_INSTALL_PREFIX})
+    # only embed libraries, therefore put into lib dir
+    get_filename_component(item_name "${item}" NAME)
+    set(${resolved_item_var} "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}/${item_name}" PARENT_SCOPE)
+  endif(${item} MATCHES ${CMAKE_INSTALL_PREFIX})
+endfunction(resolve_embedded_item)
+
+
+
+
+
+#=============================================================================
+# function change_install_names_for_item
+#=============================================================================
+function(change_install_names_for_item keys_var key)
+
+  # Ensure the item is within the install directory
+  if(${${key}_RESOLVED_EMBEDDED_ITEM} MATCHES ${CMAKE_INSTALL_PREFIX})
+    set(prereqs "")
+    get_filename_component(exepath ${${key}_RESOLVED_EMBEDDED_ITEM} PATH)
+    string(REPLACE ${CMAKE_INSTALL_PREFIX} "" rel_path ${exepath})
+    string(REGEX REPLACE "/[^/]*" "/.." inv_rel_path ${rel_path})
+    get_dependencies_for_item("${${key}_RESOLVED_EMBEDDED_ITEM}" prereqs)
+    set(changes "")
+    foreach(pr ${prereqs})
+      # Each referenced item's key is "rkey" in the loop:
+      get_filename_component(exepath ${${key}_RESOLVED_EMBEDDED_ITEM} PATH)
+      resolve_item( ${${key}_RESOLVED_EMBEDDED_ITEM} ${pr} exepath resolved_pr)
+      get_item_key("${resolved_pr}" rkey)
+      list(FIND ${keys_var} ${rkey} r_found)
+      if(r_found EQUAL -1)
+        MESSAGE(FATAL_ERROR "Key: '${rkey}' not found in dependency list. Cannot change install name.")
+      endif(r_found EQUAL -1)
+      if(NOT ${${rkey}_SYSTEMFLAG})
+        get_filename_component(ref_exepath ${${rkey}_RESOLVED_EMBEDDED_ITEM} PATH)
+        string(REPLACE ${CMAKE_INSTALL_PREFIX} "" ref_rel_path ${ref_exepath})
+        set(diff_path @loader_path${inv_rel_path}${ref_rel_path}/)
+        set(changes ${changes} "-change" "${pr}" "${diff_path}${${rkey}_ITEM}")
+      endif(NOT ${${rkey}_SYSTEMFLAG})
+    endforeach(pr)
+     
+    execute_process(COMMAND chmod u+w "${${key}_RESOLVED_EMBEDDED_ITEM}")
+    
+    # Change this item's id and all of its references in one call
+    # to install_name_tool:
+    execute_process(COMMAND install_name_tool ${changes} -id "${${key}_ITEM}" "${${key}_RESOLVED_EMBEDDED_ITEM}")
+  else( ${${key}_RESOLVED_EMBEDDED_ITEM} MATCHES ${CMAKE_INSTALL_PREFIX})
+    MESSAGE(FATAL_ERROR "Trying to change install name for: ${${key}_RESOLVED_EMBEDDED_ITEM}, which is outside of install directory")
+  endif(${${key}_RESOLVED_EMBEDDED_ITEM} MATCHES ${CMAKE_INSTALL_PREFIX})
+
+endfunction(change_install_names_for_item)
+
+
+
+#=============================================================================
+# function verify
+#=============================================================================
+function(verify keys_var)
+  foreach(key ${${keys_var}})
+    get_dependencies_for_item("${${key}_RESOLVED_EMBEDDED_ITEM}" dependencies)
+    get_filename_component(exepath ${${key}_RESOLVED_EMBEDDED_ITEM} PATH)
+    foreach(dep ${dependencies})
+      resolve_item( ${${key}_RESOLVED_EMBEDDED_ITEM} ${dep} exepath resolved_dep)
+      is_system_lib(${resolved_dep} system_flag)
+      if(NOT ${system_flag})
+        if(NOT ${resolved_dep} MATCHES ${CMAKE_INSTALL_PREFIX})
+          MESSAGE("Warning: item:'${${key}_RESOLVED_EMBEDDED_ITEM}' contains external dependency:'${resolved_dep}'")
+        endif(NOT ${resolved_dep} MATCHES ${CMAKE_INSTALL_PREFIX})
+      endif(NOT ${system_flag})
+    endforeach(dep)
+  endforeach(key)
+endfunction(verify)
+
+
+#=============================================================================
+# function add_dependencies_for_item
+#=============================================================================
+function(add_dependencies_for_item keys_var  item exepath)
+  if(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+    message(FATAL_ERROR "Item '${item}' does not exist.")
+  endif(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+
+  get_dependencies_for_item(${item} dependencies)
+  foreach(dep ${dependencies})
+    resolve_item("${item}" "${dep}" "${exepath}" resolved_dep)
+    get_item_key("${resolved_dep}" dep_key)
+    list(FIND ${keys_var} ${dep_key} dep_found)
+    if(dep_found EQUAL -1)
+      message(STATUS "Resolved '${dep}' to: '${resolved_dep}'")
+      is_system_lib(${resolved_dep} system_flag)
+      if(${system_flag})
+        MESSAGE(STATUS "Skipping system library:'${resolved_dep}'")
+        set_keys_for_item(${keys_var} ${item} ${resolved_dep} 0 1)
+      else(${system_flag})
+        set_keys_for_item(${keys_var} ${item} ${resolved_dep} 1   0)
+        add_dependencies_for_item(${keys_var} ${resolved_dep} ${exepath})
+      endif(${system_flag})
+    endif(dep_found EQUAL -1)
+  endforeach(dep ${dependencies})
+  # Propagate values to caller's scope:
+  set(${keys_var} ${${keys_var}} PARENT_SCOPE)
+  foreach(key ${${keys_var}})
+    set(${key}_ITEM "${${key}_ITEM}" PARENT_SCOPE)
+    set(${key}_RESOLVED_ITEM "${${key}_RESOLVED_ITEM}" PARENT_SCOPE)
+    set(${key}_RESOLVED_EMBEDDED_ITEM "${${key}_RESOLVED_EMBEDDED_ITEM}" PARENT_SCOPE)
+    set(${key}_COPYFLAG "${${key}_COPYFLAG}" PARENT_SCOPE)
+    set(${key}_SYSTEMFLAG "${${key}_SYSTEMFLAG}" PARENT_SCOPE)
+  endforeach(key)
+endfunction(add_dependencies_for_item)
+
+
+
+#=============================================================================
+# function append_unique
+#=============================================================================
+function(append_unique list_var value)
+  set(contains 0)
+  foreach(item ${${list_var}})
+    if("${item}" STREQUAL "${value}")
+      set(contains 1)
+      break()
+    endif("${item}" STREQUAL "${value}")
+  endforeach(item)
+
+  if(NOT contains)
+    set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
+  endif(NOT contains)
+endfunction(append_unique)
+
+
+#=============================================================================
+# function copy_python
+#=============================================================================
+function(copy_python include_path version new_binary_path)
+
+
+  get_filename_component(real_python_include_path ${include_path} REALPATH)
+  get_filename_component(python_root_dir ${real_python_include_path}/../.. REALPATH) 
+  file(COPY ${python_root_dir}/${LIB_DIR}/python${version}/ DESTINATION ${CMAKE_INSTALL_PREFIX}/${LIB_DIR}/python${version})
+  file(GLOB  py_config_files "${include_path}/pyconfig*.h")
+  file(COPY ${py_config_files} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/python${version})
+  file(GLOB_RECURSE python_so_files "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}/python${version}/*.so")
+  if(NOT APPLE)
+  foreach(so_file ${python_so_files})
+    remove_rpath("${so_file}")
+  endforeach(so_file)
+  endif(NOT APPLE)
+  read_config(ost_config)
+  if(APPLE)
+    file(COPY ${python_root_dir}/Resources/Python.app/Contents/MacOS/Python DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
+    set(${new_binary_path} "${CMAKE_INSTALL_PREFIX}/bin/Python" PARENT_SCOPE)
+    string(REGEX REPLACE "pyexec=\"[^\n\$]*\"" "pyexec=\"\$DNG_BINDIR/Python\"\nexport PYTHONHOME=\$DNG_ROOT" ost_config "${ost_config}")
+  else(APPLE)
+    file(GLOB python_libs "${python_root_dir}/${LIB_DIR}/libpython${version}.so*")
+    file(COPY ${python_libs} DESTINATION ${CMAKE_INSTALL_PREFIX}/${LIB_DIR})
+    file(COPY ${python_root_dir}/bin/python${version} DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)
+    set(${new_binary_path} "${CMAKE_INSTALL_PREFIX}/bin/python${version}" PARENT_SCOPE)
+    string(REGEX REPLACE "pyexec=\"[^\n\$]*\"" "pyexec=\"\$DNG_BINDIR/python${version}\"\nexport PYTHONHOME=\$DNG_ROOT" ost_config "${ost_config}")
+  endif(APPLE)
+  write_config("${ost_config}")
+endfunction(copy_python)
+
+#=============================================================================
+# function read_config
+#=============================================================================
+function(read_config ost_config_var)
+  file(READ "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/ost_config" ost_config)
+  set(${ost_config_var} "${ost_config}" PARENT_SCOPE)
+endfunction(read_config)
+
+#=============================================================================
+# function write_config
+#=============================================================================
+function(write_config ost_config)
+  file(WRITE "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/ost_config" "${ost_config}")
+endfunction(write_config)
+
+#=============================================================================
+# function write_bundle_binary
+#=============================================================================
+function(write_bundle_binary binary_name real_binary)
+  file(WRITE "${CMAKE_INSTALL_PREFIX}/../MacOS/${binary_name}" "#!/bin/sh\nexec \"\${0%/*}/${real_binary}\"\n")
+  execute_process(COMMAND chmod ugo+x "${CMAKE_INSTALL_PREFIX}/../MacOS/${binary_name}")
+endfunction(write_bundle_binary)
+
+#=============================================================================
+# function add_linked_bundle
+#=============================================================================
+function(add_linked_bundle parent_bundle_name bundle_name binary_name bundle_identifier bundle_icon)
+  get_filename_component(dmg_main_path ${CMAKE_INSTALL_PREFIX}/../../../../ PATH)
+  file(MAKE_DIRECTORY "${dmg_main_path}/${bundle_name}.app/Contents/MacOS/")
+  file(MAKE_DIRECTORY "${dmg_main_path}/${bundle_name}.app/Contents/Resources/")
+  file(WRITE "${dmg_main_path}/${bundle_name}.app/Contents/MacOS/${binary_name}" "#!/bin/sh\nexec \"\${0%/*}/../../../${parent_bundle_name}.app/Contents/Resources/bin/${binary_name}\"\n")
+  get_filename_component(icon_name ${bundle_icon} NAME)
+  file(COPY ${bundle_icon} DESTINATION "${dmg_main_path}/${bundle_name}.app/Contents/Resources")
+  create_plist(${binary_name} ${bundle_name} ${bundle_identifier} ${icon_name} "${dmg_main_path}/${bundle_name}.app/Contents/Info.plist")
+  execute_process(COMMAND chmod ugo+x "${dmg_main_path}/${bundle_name}.app/Contents/MacOS/${binary_name}")
+endfunction(add_linked_bundle)
+
+#=============================================================================
+# function create_plist
+#=============================================================================
+function(create_plist BUNDLE_EXECUTABLE BUNDLE_NAME BUNDLE_IDENTIFIER BUNDLE_ICON FILENAME)
+  set( info_plist "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
+<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" 
+    \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
+<plist version=\"1.0\">
+<dict>
+  <key>CFBundleDevelopmentRegion</key>
+  <string>English</string>
+  <key>CFBundleExecutable</key>
+  <string>\@BUNDLE_EXECUTABLE\@</string>
+  <key>CFBundleName</key>
+  <string>\@BUNDLE_NAME\@</string>  
+  <key>CFBundleDisplayName</key>
+  <string>\@BUNDLE_NAME\@</string>  
+  <key>CFBundleHelpBookFolder</key>
+  <string>\@BUNDLE_NAME\@ Manual</string>
+  <key>CFBundleHelpBookName</key>
+  <string>OpenStructure Help</string>
+  <key>CFBundleIconFile</key>
+  <string>\@BUNDLE_ICON\@</string>
+  <key>CFBundleIdentifier</key>
+  <string>\@BUNDLE_IDENTIFIER\@</string>
+  <key>CFBundleInfoDictionaryVersion</key>
+  <string>6.0</string>
+  <key>CFBundlePackageType</key>
+  <string>APPL</string>
+  <key>CFBundleSignature</key>
+  <string>????</string>
+  <key>CFBundleVersion</key>
+  <string></string>
+  <key>NSMainNibFile</key>
+  <string>MainMenu</string>
+  <key>NSPrincipalClass</key>
+  <string>NSApplication</string>
+</dict>
+</plist>")
+  string(CONFIGURE "${info_plist}" info_plist_replaced)
+  file(WRITE  ${FILENAME} "${info_plist_replaced}")
+endfunction(create_plist)
+
+#=============================================================================
+# function echo_all_cmake_variable_values
+#=============================================================================
+
+function(echo_all_cmake_variable_values)
+  message("")
+  get_cmake_property(vs VARIABLES)
+  foreach(v ${vs})
+    message("${v}='${${v}}'")
+  endforeach(v)
+  message("")
+endfunction(echo_all_cmake_variable_values)
+
+
+#=============================================================================
+#=============================================================================
+# OSX specific functions
+#=============================================================================
+#=============================================================================
+
+if(APPLE)
+
+#=============================================================================
+# function get_dependencies_for_item (OSX)
+#=============================================================================
+function(get_dependencies_for_item  item list_var)
+
+  if(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+    message(FATAL_ERROR "Cannot find item: '${item}' to get dependencies.")
+  endif(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+
+  find_program(otool_cmd "otool" PATHS "/usr/local/bin" "/usr/bin")
+  if(NOT otool_cmd)
+    message(FATAL_ERROR "Could not find otool - cannot analyze dependencies.")
+  endif(NOT otool_cmd)
+
+  execute_process( COMMAND ${otool_cmd} -L ${item} OUTPUT_VARIABLE otool_cmd_ov RESULT_VARIABLE retcode )
+  if(retcode)
+    MESSAGE(FATAL_ERROR "otool stopped with return code: '${retcode}'")
+  endif(retcode)
+  # Convert to a list of lines:
+  string(REGEX REPLACE ";" "\\\\;" candidates "${otool_cmd_ov}")
+  set(eol_char "E")
+  string(REGEX REPLACE "\n" "${eol_char};" candidates "${candidates}")
+
+  # check for install id and remove it from list, since otool -L can include a reference to itself
+  set(install_id)
+  execute_process( COMMAND ${otool_cmd} -D ${item} OUTPUT_VARIABLE install_id_ov  RESULT_VARIABLE retcode)
+  if(retcode)
+    MESSAGE(FATAL_ERROR "otool stopped with return code: '${retcode}'")
+  endif(retcode)
+  # second line is install name
+  string(REGEX REPLACE ".*:\n" "" install_id "${install_id_ov}")
+  if(install_id)
+    string(REGEX MATCH "[^\n ].*[^\n ]" install_id "${install_id}")
+  endif(install_id)
+
+  # Analyze each line for file names that match the regular expression:
+  set(otool_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)\\)${eol_char}$")
+  set(dep_list)
+  foreach(candidate ${candidates})
+    if("${candidate}" MATCHES "${otool_regex}")
+      # Extract information from each candidate:
+      string(REGEX REPLACE "${otool_regex}" "\\1" dep "${candidate}")
+      if(NOT "${dep}" STREQUAL "${install_id}")
+        list(APPEND dep_list ${dep})
+      endif(NOT "${dep}" STREQUAL "${install_id}")
+    endif("${candidate}" MATCHES "${otool_regex}")
+  endforeach(candidate)
+  set(${list_var} ${dep_list} PARENT_SCOPE)
+endfunction(get_dependencies_for_item)
+
+#=============================================================================
+# function get_rpath (OSX)
+#=============================================================================
+function(get_rpath target rpath_var)
+  find_program(rpath_exe "otool" PATHS "/usr/local/bin" "/usr/bin")
+  if(NOT rpath_exe)
+    message(FATAL_ERROR "Could not find otool - cannot resolve rpath.")
+  endif(NOT rpath_exe)
+ execute_process(
+    COMMAND ${rpath_exe} "-l" ${target}
+    OUTPUT_VARIABLE rpath_cmd_ov
+    RESULT_VARIABLE retcode
+  )
+  if(retcode)
+    MESSAGE(FATAL_ERROR "otool stopped with return code: '${retcode}'")
+  endif(retcode)
+  set(rpath_cmd_regex ".*LC_RPATH\n *cmdsize [0-9]*\n\ *path ([^\n ]*) \\(offset.*")
+  if(rpath_cmd_ov MATCHES ${rpath_cmd_regex})
+    string(REGEX REPLACE ${rpath_cmd_regex} "\\1"  rpath ${rpath_cmd_ov})
+    set(${rpath_var} ${rpath} PARENT_SCOPE)
+  endif(rpath_cmd_ov MATCHES ${rpath_cmd_regex})
+endfunction(get_rpath)
+
+#=============================================================================
+# function copy_qt (OSX)
+#=============================================================================
+function(copy_qt library_dir plugin_dir plugins)
+  file(COPY "${library_dir}/Resources/qt_menu.nib"
+       DESTINATION "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/"
+       FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
+  file(COPY ${plugin_dir}
+       DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/openstructure) 
+  file(GLOB_RECURSE QT_PLUGINS "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/*.dylib")
+  set(${plugins} ${QT_PLUGINS} PARENT_SCOPE)
+  file(WRITE "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/qt.conf" "[Paths]\nPlugins=../plugins\n")
+endfunction(copy_qt)
+
+#=============================================================================
+# function is_system_lib (OSX)
+#=============================================================================
+function(is_system_lib item system_var)
+  if(item MATCHES "^(/System/Library/|/usr/lib/)")
+    set(${system_var}  1 PARENT_SCOPE)
+  else()
+    set(${system_var}  0 PARENT_SCOPE)
+  endif()
+endfunction(is_system_lib)
+
+#=============================================================================
+# function copy_resolved_item (OSX)
+#=============================================================================
+function(copy_resolved_item resolved_item resolved_embedded_item)
+  if("${resolved_item}" STREQUAL "${resolved_embedded_item}")
+    message(STATUS "warning: resolved_item == resolved_embedded_item - not copying...")
+  else()
+    message(STATUS "copying COMMAND ${CMAKE_COMMAND} -E copy ${resolved_item} ${resolved_embedded_item}")
+    execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${resolved_item}" "${resolved_embedded_item}")
+  endif()
+
+endfunction(copy_resolved_item)
+
+
+elseif(WIN32 AND NOT UNIX)
+
+#=============================================================================
+#=============================================================================
+# Windows specific functions
+#=============================================================================
+#=============================================================================
+
+
+#=============================================================================
+# function get_dependencies_for_item (Windows)
+#=============================================================================
+function(get_dependencies_for_item  item list_var)
+
+  if(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+    message(FATAL_ERROR "Cannot find item: '${item}' to get dependencies.")
+  endif(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+
+  find_program(dumpbin_cmd "dumpbin")
+  if(NOT dumpbin_cmd)
+    message(FATAL_ERROR "Could not find dumpbin - cannot analyze dependencies.")
+    return()
+  endif(NOT dumpbin_cmd)
+
+  set(ENV{VS_UNICODE_OUTPUT} "") # Block extra output from inside VS IDE.
+  execute_process( COMMAND ${dumpbin_cmd}  /dependents ${item} OUTPUT_VARIABLE dumpbin_cmd_ov RESULT_VARIABLE retcode)
+  if(retcode)
+    MESSAGE(FATAL_ERROR "dumpbin stopped with return code: '${retcode}'")
+  endif(retcode)
+  # Convert to a list of lines:
+  string(REGEX REPLACE ";" "\\\\;" candidates "${dumpbin_cmd_ov}")
+  set(eol_char "E")
+  string(REGEX REPLACE "\n" "${eol_char};" candidates "${candidates}")
+
+  # Analyze each line for file names that match the regular expression:
+  set(dumpbin_regex "^    ([^ ].*[Dd][Ll][Ll])${eol_char}$")
+  set(dep_list)
+  foreach(candidate ${candidates})
+    if("${candidate}" MATCHES "${dumpbin_regex}")
+      # Extract information from each candidate:
+      string(REGEX REPLACE "${dumpbin_regex}" "\\1" dep "${candidate}")
+      list(APPEND dep_list ${dep})
+    endif("${candidate}" MATCHES "${dumpbin_regex}")
+  set(${list_var} ${dep_list} PARENT_SCOPE)
+endfunction(get_dependencies_for_item)
+
+#=============================================================================
+# function get_rpath (Windows)
+#=============================================================================
+function(get_rpath target rpath_var)
+  message(FATAL_ERROR "get_rpath not implemented for Windows.")
+endfunction(get_rpath)
+
+#=============================================================================
+# function is_system_lib (Windows)
+#=============================================================================
+function(is_system_lib item system_var)
+  string(TOLOWER "${item}" lower)
+  string(TOLOWER "$ENV{SystemRoot}" sysroot)
+  string(REGEX REPLACE "\\\\" "/" sysroot "${sysroot}")
+  string(TOLOWER "$ENV{windir}" windir)
+  string(REGEX REPLACE "\\\\" "/" windir "${windir}")
+  if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*msvc[^/]+dll)")
+    set(${system_var}  1 PARENT_SCOPE)
+  else()
+    set(${system_var}  0 PARENT_SCOPE)
+  endif()
+endfunction(is_system_lib)
+
+#=============================================================================
+# function copy_resolved_item (Windows)
+#=============================================================================
+function(copy_resolved_item resolved_item resolved_embedded_item)
+  # ignore case on Windows
+  string(TOLOWER "${resolved_item}" resolved_item_compare)
+  string(TOLOWER "${resolved_embedded_item}" resolved_embedded_item_compare)
+
+  if("${resolved_item_compare}" STREQUAL "${resolved_embedded_item_compare}")
+    message(STATUS "warning: resolved_item == resolved_embedded_item - not copying...")
+  else()
+    message(STATUS "copying COMMAND ${CMAKE_COMMAND} -E copy ${resolved_item} ${resolved_embedded_item}")
+    execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${resolved_item}" "${resolved_embedded_item}")
+  endif()
+
+endfunction(copy_resolved_item)
+
+elseif(UNIX)
+
+
+#=============================================================================
+#=============================================================================
+# Linux specific functions
+#=============================================================================
+#=============================================================================
+
+#=============================================================================
+# function get_dependencies_for_item (Linux)
+#=============================================================================
+function(get_dependencies_for_item item list_var)
+
+  if(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+    message(FATAL_ERROR "Cannot find item: '${item}' to get dependencies.")
+  endif(NOT IS_ABSOLUTE "${item}" AND EXISTS "${item}")
+
+  find_program(ldd_cmd "ldd" PATHS "/usr/local/bin" "/usr/bin")
+  if(NOT ldd_cmd)
+    message(FATAL_ERROR "Could not find ldd - cannot analyze dependencies.")
+    return()
+  endif(NOT ldd_cmd)
+  set(old_ld_library_path $ENV{LD_LIBRARY_PATH})
+  set(ENV{LD_LIBRARY_PATH} "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}:$ENV{LD_LIBRARY_PATH}")
+  execute_process( COMMAND ${ldd_cmd}  ${item} OUTPUT_VARIABLE ldd_cmd_ov ERROR_VARIABLE ldd_cmd_ev RESULT_VARIABLE retcode)
+  set(ENV{LD_LIBRARY_PATH} ${old_ld_library_path})
+  if(retcode)
+    if(${ldd_cmd_ov})
+      message(${ldd_cmd_ov})
+    endif(${ldd_cmd_ov})
+    if(${ldd_cmd_ev})
+      message(${ldd_cmd_ev})
+    endif(${ldd_cmd_ev})
+    message("command:'${ldd_cmd}'  '${item}'")
+    message(FATAL_ERROR "ldd stopped with return code: '${retcode}'")
+  endif(retcode)
+  # Convert to a list of lines:
+  string(REGEX REPLACE ";" "\\\\;" candidates "${ldd_cmd_ov}")
+  set(eol_char "E")
+  string(REGEX REPLACE "\n" "${eol_char};" candidates "${candidates}")
+
+  # Analyze each line for file names that match the regular expression:
+  set(ldd_regex "^[\t ]*[^\t ]+ => ([^\t\(]+) .*${eol_char}$")
+  set(ldd_regex_error "not found${eol_char}$")
+  set(ldd_regex_fallback "^[\t ]*([^\t ]+) => ([^\t ]+).*${eol_char}$")
+  set(dep_list)
+  foreach(candidate ${candidates})
+    if("${candidate}" MATCHES "${ldd_regex}")
+      # Extract information from each candidate:
+      if("${candidate}" MATCHES "${ldd_regex_error}")
+        string(REGEX REPLACE "${ldd_regex_fallback}" "\\1" dep "${candidate}")
+      else("${candidate}" MATCHES "${ldd_regex_error}")
+        string(REGEX REPLACE "${ldd_regex}" "\\1" dep "${candidate}")
+      endif("${candidate}" MATCHES "${ldd_regex_error}")
+      list(APPEND dep_list ${dep})
+    endif("${candidate}" MATCHES "${ldd_regex}")
+  endforeach(candidate)
+  set(${list_var} ${dep_list} PARENT_SCOPE)
+endfunction(get_dependencies_for_item)
+
+#=============================================================================
+# function get_rpath (Linux)
+#=============================================================================
+function(get_rpath target rpath_var)
+  find_program(rpath_exe "readelf" PATHS "/usr/local/bin" "/usr/bin")
+  if(NOT rpath_exe)
+    message(FATAL_ERROR "Could not find readelf - cannot resolve rpath.")
+  endif(NOT rpath_exe)
+ execute_process(
+    COMMAND ${rpath_exe} "-d" ${target}
+    OUTPUT_VARIABLE rpath_cmd_ov
+    RESULT_VARIABLE retcode
+  )
+  if(retcode)
+    MESSAGE(FATAL_ERROR "readelf stopped with return code: '${retcode}'")
+  endif(retcode)
+  
+  set(rpath_cmd_regex "Library rpath: \[([^\n ]*):\]")
+  if(rpath_cmd_ov MATCHES ${rpath_cmd_regex})
+    string(REGEX REPLACE ${rpath_cmd_regex} "\\1"  rpath ${rpath_cmd_ov})
+    set(${rpath_var} ${rpath} PARENT_SCOPE)
+  endif(rpath_cmd_ov MATCHES ${rpath_cmd_regex})
+endfunction(get_rpath)
+
+#=============================================================================
+# function copy_qt (Linux)
+#=============================================================================
+function(copy_qt library_dir plugin_dir plugins)
+  file(COPY ${plugin_dir}
+       DESTINATION ${CMAKE_INSTALL_PREFIX}/libexec/openstructure) 
+  file(GLOB_RECURSE QT_PLUGINS "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/*.so")
+  foreach(plugin ${QT_PLUGINS})
+    remove_rpath("${plugin}")
+  endforeach(plugin)
+  set(${plugins} ${QT_PLUGINS} PARENT_SCOPE)
+  file(WRITE "${CMAKE_INSTALL_PREFIX}/libexec/openstructure/qt.conf" "[Paths]\nPlugins=../plugins\n")
+endfunction(copy_qt)
+
+#=============================================================================
+# function is_system_lib (Linux)
+#=============================================================================
+function(is_system_lib item system_var)
+  if(item MATCHES "/cmov/|ld-linux[\\.\\-]|libc[\\.\\-]|libdl[\\.\\-]|libdrm[\\.\\-]|libelf[\\.\\-]|libexpat[\\.\\-]|libfontconfig[\\.\\-]|libfreetype[\\.\\-]|libg[\\.\\-]|libgcc_s[\\.\\-]|libGL[\\.\\-]|libglib[\\.\\-]|libgthread[\\.\\-]|lib(ice|ICE)[\\.\\-]|libnvidia[\\.\\-]|libpthread[\\.\\-]|libse(pol|linux)[\\.\\-]|libSM[\\.\\-]|libstdc\\+\\+[\\.\\-]|libX[a-zA-Z0-9]*[\\.\\-]|libxcb[\\.\\-]|pylibc[\\.\\-]")
+    set(${system_var} 1 PARENT_SCOPE)
+  else()
+    set(${system_var}  0 PARENT_SCOPE)
+  endif()
+endfunction(is_system_lib)
+
+#=============================================================================
+# function copy_resolved_item (Linux)
+#=============================================================================
+function(copy_resolved_item resolved_item resolved_embedded_item)
+  get_filename_component(real_resolved_item "${resolved_item}" REALPATH)
+  get_filename_component(real_resolved_embedded_item "${resolved_embedded_item}" REALPATH)
+
+  if("${real_resolved_item}" STREQUAL "${real_resolved_embedded_item}")
+    message(STATUS "warning: resolved_item == resolved_embedded_item - not copying...")
+  else()
+    message(STATUS "copying ${resolved_item} to ${resolved_embedded_item} including symlinks")
+    # determine all the symlinks pointing to the current item and copy them into the package
+    # along with the item
+    get_filename_component(external_path  ${real_resolved_item} PATH)
+    get_filename_component(embedded_path  ${real_resolved_embedded_item} PATH)
+    get_filename_component(external_name  ${real_resolved_item} NAME)
+    string(REGEX REPLACE "([a-zA-Z]+).*" "\\1" name_base ${external_name})
+    file(GLOB candidates "${external_path}/${name_base}*" )
+    set(external_files)
+    foreach(candidate ${candidates})
+      get_filename_component(real_candidate "${candidate}" REALPATH)
+      if(real_candidate STREQUAL ${real_resolved_item})
+        list(APPEND external_files ${candidate})
+      endif(real_candidate STREQUAL ${real_resolved_item})
+    endforeach(candidate)
+    file(COPY ${external_files} DESTINATION ${embedded_path})
+    remove_rpath("${real_resolved_embedded_item}")
+  endif()
+
+endfunction(copy_resolved_item)
+
+
+
+
+
+#=============================================================================
+# function remove_rpath (Linux)
+#=============================================================================
+function(remove_rpath file)
+  execute_process(COMMAND stat --format %a  "${file}" OUTPUT_VARIABLE permissions)
+  execute_process(COMMAND chmod ugo+x "${file}")
+  string(SUBSTRING ${permissions} 0 3 permissions)
+  file(RPATH_REMOVE FILE "${file}")
+  execute_process(COMMAND chmod ${permissions} "${file}")
+endfunction(remove_rpath)
+
+
+
+else(APPLE)
+  MESSAGE("Unknown platform, deployment will not work.")
+endif(APPLE)
diff --git a/cmake_support/Deployment.cmake b/cmake_support/Deployment.cmake
deleted file mode 100644
index e4f6d949b992162cf51d0f76b91849c13c5a9c52..0000000000000000000000000000000000000000
--- a/cmake_support/Deployment.cmake
+++ /dev/null
@@ -1,41 +0,0 @@
-INCLUDE(InstallRequiredSystemLibraries)
-
-
-set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "OpenStructure Framework")
-set(CPACK_PACKAGE_VENDOR "2008-2010 -- The OpenStructure Team")
-set(CPACK_PACKAGE_DESCRIPTION_FILE "${PROJECT_SOURCE_DIR}/ReadMe.txt")
-set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE.txt")
-set(CPACK_PACKAGE_VERSION_MAJOR "1")
-set(CPACK_PACKAGE_VERSION_MINOR "0")
-if (OST_REV)
-  set(CPACK_PACKAGE_VERSION_PATCH "0a1_${OST_REV}")
-else()
-  set(CPACK_PACKAGE_VERSION_PATCH "0a1")
-endif()
-set(OST_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}")
-set(CPACK_PACKAGE_INSTALL_DIRECTORY "openstructure ${OST_VERSION}" )
-
-IF(WIN32 AND NOT UNIX)
-# There is a bug in NSI that does not handle full unix paths properly. Make
-# sure there is at least one set of four (4) backlashes.
-  set(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/graphics/\\\\icon_32.png")
-  #set(CPACK_NSIS_INSTALLED_ICON_NAME "bin/\\\\gosty.exe")
-  set(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY}")
-  set(CPACK_NSIS_HELP_LINK "http:www.openstructure.org")
-  #set(CPACK_NSIS_URL_INFO_ABOUT "http:www.my-personal-home-page.com")
-  set(CPACK_NSIS_CONTACT "users@maillist.unibas.ch")
-  set(CPACK_NSIS_MODIFY_PATH ON)
-  set(CPACK_SOURCE_STRIP_FILES TRUE)
-  set(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/graphics/\\\\icon_32.png")
-  set(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "")
-  set(CPACK_PACKAGE_EXECUTABLES "dng" "DNG")
-  set(CPACK_PACKAGE_EXECUTABLES "gipltng" "gipltng")
-  set(CPACK_INSTALL_DIRECTORIES "d:/progams/lib")
-  # set(CPACK_STRIP_FILES "bin/gosty" 
-                        # "bin/ost.bat"
-                        # "bin/ost_cl.bat"
-                        # "bin\gipltng.bat
-  # )
-ENDIF()
-
-INCLUDE(CPack) #this must come last
diff --git a/cmake_support/OST.cmake b/cmake_support/OST.cmake
index e6dfb2ae0d4fb748a455f89e0ed51524acab4ba9..fb478ec085f04136e2ec359fc5f8c460572742ff 100644
--- a/cmake_support/OST.cmake
+++ b/cmake_support/OST.cmake
@@ -357,10 +357,14 @@ macro(executable_libexec)
   set_target_properties(${_ARG_NAME}
                         PROPERTIES RUNTIME_OUTPUT_DIRECTORY
                        "${LIBEXEC_STAGE_PATH}")  
-  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 (NOT _ARG_NO_RPATH AND NOT _ARG_STATIC)
+    if (APPLE)
+      set_target_properties(${_ARG_NAME} PROPERTIES
+                            LINK_FLAGS "-Wl,-rpath,@loader_path/../../lib")
+    elseif (UNIX)
+      set_target_properties(${_ARG_NAME} PROPERTIES INSTALL_RPATH "$ORIGIN/../../${LIB_DIR}")
+    endif (APPLE)
+  endif (NOT _ARG_NO_RPATH AND NOT _ARG_STATIC)
   if (_ARG_LINK)
     target_link_libraries(${_ARG_NAME} ${_ARG_LINK})
   endif()
@@ -422,7 +426,7 @@ macro(script)
     substitute(IN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${_INPUT}" OUT_FILE ${_ARG_NAME} 
                DICT ${_ARG_SUBSTITUTE})
   endif()
-  install(FILES ${_ARG_NAME} DESTINATION ${_ARG_OUTPUT_DIR} 
+  install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${_ARG_NAME} DESTINATION ${_ARG_OUTPUT_DIR} 
           PERMISSIONS WORLD_EXECUTE GROUP_EXECUTE OWNER_EXECUTE 
                       WORLD_READ GROUP_READ OWNER_READ)
   copy_if_different("./" "${STAGE_DIR}/${_ARG_OUTPUT_DIR}" 
@@ -437,9 +441,10 @@ endmacro()
 #   Calls pyuic on every input file. The resulting python files are stored in
 #   the variable with name out_files.
 #-------------------------------------------------------------------------------
-macro(ui_to_python LIBNAME STAGEDIR)
+macro(ui_to_python LIBNAME PYMODDIR STAGEDIR)
   set(_input_files ${ARGN})
   add_custom_target("${LIBNAME}_ui" ALL)
+  add_dependencies("_${LIBNAME}" "${LIBNAME}_ui")
   find_program(_PYUIC_EXECUTABLE
     NAMES pyuic4-${PYTHON_VERSION} pyuic4 pyuic
     PATHS  ENV PATH 
@@ -457,9 +462,10 @@ macro(ui_to_python LIBNAME STAGEDIR)
                        COMMAND ${_PYUIC_EXECUTABLE} -o ${_abs_out_file} ${_in_file}
                        VERBATIM DEPENDS ${input_file}
                        )
-    list(APPEND ${out_files} ${_abs_out_file})
+    list(APPEND out_files ${_abs_out_file})
   endforeach()
   compile_py_files(_${LIBNAME} ${STAGEDIR} ${out_files})
+  install(FILES ${out_files} DESTINATION "${LIB_DIR}/${PYMODDIR}")
 endmacro()
 
 #-------------------------------------------------------------------------------
@@ -541,8 +547,9 @@ macro(pymod)
  
     if (NOT ENABLE_STATIC)
       if (_USE_RPATH)
+        string(REGEX REPLACE "/[^/]*" "/.." inv_pymod_path "/${PYMOD_DIR}")
         set_target_properties("_${_LIB_NAME}"
-                              PROPERTIES INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${LIB_DIR}")
+                              PROPERTIES INSTALL_RPATH "$ORIGIN${inv_pymod_path}/")
       else()
         set_target_properties("_${_LIB_NAME}"
                               PROPERTIES INSTALL_RPATH "")
@@ -574,7 +581,7 @@ macro(pymod)
   # build ui files
   #-----------------------------------------------------------------------------
   if (_ARG_UI)
-    ui_to_python(${_LIB_NAME} ${PYMOD_STAGE_DIR} ${_ARG_UI})
+    ui_to_python(${_LIB_NAME} ${PYMOD_DIR} ${PYMOD_STAGE_DIR} ${_ARG_UI})
   endif()  
   #-----------------------------------------------------------------------------
   # compile python files
diff --git a/deployment/CMakeLists.txt b/deployment/CMakeLists.txt
index 1a55585477a522275cc23467e5a91f5e99fb984c..19d084aec2979e7d898f2dfaebb4cab60f1135d0 100644
--- a/deployment/CMakeLists.txt
+++ b/deployment/CMakeLists.txt
@@ -1,8 +1,32 @@
-# todo implement get_ost_rev for git
-#get_ost_rev()
-include(Deployment)
-set(SUBST_DIC OST_VERSION="${OST_VERSION}")
-add_custom_target(deploymnt ALL)
-substitute(IN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/README.html.in OUT_FILE README.html 
-               DICT ${SUBST_DIC})
-add_subdirectory(win)
+#-------------------------------------------------------------------------------
+#  Author:  Andreas Schenk
+#
+#  This file contains the CPack configuration common to all platforms.
+#
+#-------------------------------------------------------------------------------
+
+#only include deployment configureation for the main project and not for subprojects
+if(${PROJECT_SOURCE_DIR} STREQUAL ${CMAKE_SOURCE_DIR})
+
+  INCLUDE(InstallRequiredSystemLibraries)
+  
+  set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "OpenStructure Framework")
+  set(CPACK_PACKAGE_VENDOR "2008-2010 -- The OpenStructure Team")
+  set(CPACK_PACKAGE_DESCRIPTION_FILE "${PROJECT_SOURCE_DIR}/ReadMe.txt")
+  set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE.txt")
+  set(CPACK_PACKAGE_VERSION_MAJOR ${OST_VERSION_MAJOR})
+  set(CPACK_PACKAGE_VERSION_MINOR ${OST_VERSION_MINOR})
+  set(CPACK_PACKAGE_VERSION_PATCH ${OST_VERSION_PATCH})
+  
+  # using include instead of add_subdirectory avoid creating a child scope
+  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+    include(macos/CMakeLists.txt) 
+  elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+    include(linux/CMakeLists.txt) 
+  elseif(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
+    include(windows/CMakeLists.txt) 
+  endif()
+
+  INCLUDE(CPack) 
+
+endif(${PROJECT_SOURCE_DIR} STREQUAL ${CMAKE_SOURCE_DIR})
diff --git a/deployment/linux/CMakeLists.txt b/deployment/linux/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..191fecd1d810d969d5c91fcb131eacf3f5f810c5
--- /dev/null
+++ b/deployment/linux/CMakeLists.txt
@@ -0,0 +1,59 @@
+#-------------------------------------------------------------------------------
+#  Author:  Andreas Schenk
+#
+#  This file contains the Linux specific CPack configuration.
+#
+#-------------------------------------------------------------------------------
+
+if(NOT CPACK_GENERATOR)
+  include(CheckLSBTypes)
+  if(( ${LSB_DISTRIBUTOR_ID} MATCHES "centos" AND ${LSB_RELEASE} GREATER 5.9)
+   OR (${LSB_DISTRIBUTOR_ID} MATCHES "redhat" AND ${LSB_RELEASE} GREATER 5.9)
+   OR (${LSB_DISTRIBUTOR_ID} MATCHES "fedora"))
+    set(CPACK_GENERATOR "RPM")
+  elseif(${LSB_DISTRIBUTOR_ID} MATCHES "debian")
+    set(CPACK_GENERATOR "DEB")
+  else()
+    set(CPACK_GENERATOR "TGZ")
+  endif()
+endif(NOT CPACK_GENERATOR)
+
+if(CPACK_GENERATOR MATCHES "DEB")
+  set(CPACK_DEBIAN_PACKAGE_MAINTAINER "The OpenStructure developers")
+elseif(CPACK_GENERATOR MATCHES "RPM")
+elseif(CPACK_GENERATOR MATCHES "TGZ")
+  install(CODE "
+    if(NOT ${CMAKE_INSTALL_PREFIX} MATCHES \${CMAKE_INSTALL_PREFIX})
+      set(LIB_DIR ${LIB_DIR})#pass libdir variable in install code block
+      if(NOT ${_USE_RPATH} STREQUAL ON)
+        message(\"======================================================================\")
+        message(\"|          Warning, no rpaths will be embedded upon install.         |\")
+        message(\"|        Dependency resolution during packaging will not work.       |\")
+        message(\"| Add -DUSE-RPATH=1 when running cmake to switch on rpath embedding. |\")
+        message(\"======================================================================\")
+      endif(NOT ${_USE_RPATH} STREQUAL ON)
+      set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/ost/cmake_support)
+      include(CopyDependencies)
+      set(OST_BINARIES \"\${CMAKE_INSTALL_PREFIX}/bin/lddt\"
+                       \"\${CMAKE_INSTALL_PREFIX}/bin/chemdict_tool\"
+                       \"\${CMAKE_INSTALL_PREFIX}/bin/molck\"
+                       \"\${CMAKE_INSTALL_PREFIX}/libexec/openstructure/gosty\")
+
+      copy_python(${PYTHON_INCLUDE_PATH} ${PYTHON_VERSION} new_python_binary)
+      list(APPEND OST_BINARIES \${new_python_binary})
+
+      file(GLOB_RECURSE OST_PYMODS \"\${CMAKE_INSTALL_PREFIX}/${LIB_DIR}/*.so\")
+      list(APPEND  OST_BINARIES \${OST_PYMODS})
+
+      #copy Qt stuff
+      copy_qt(${QT_LIBRARY_DIR} ${QT_PLUGINS_DIR} qt_plugins)
+      list(APPEND  OST_BINARIES \${qt_plugins})
+
+      copy_dependencies(\"\${OST_BINARIES}\")
+    endif(NOT ${CMAKE_INSTALL_PREFIX} MATCHES \${CMAKE_INSTALL_PREFIX})
+  ")
+elseif(CPACK_GENERATOR MATCHES "TGZ_NODEP")
+  set(CPACK_GENERATOR "TGZ")
+else(CPACK_GENERATOR MATCHES "DEB")
+  message(FATAL_ERROR "Uknown CPack generator")
+endif(CPACK_GENERATOR MATCHES "DEB")
diff --git a/deployment/linux/ldd-rec.pl b/deployment/linux/ldd-rec.pl
index e770bb6c07398416c2b4062365bd2530c6cd40b0..52e8455cfa101782b2bc9d8afef7e5ba712f4b73 100644
--- a/deployment/linux/ldd-rec.pl
+++ b/deployment/linux/ldd-rec.pl
@@ -16,7 +16,7 @@ push @check_queue, @ARGV;
 
 while (@check_queue) {
   my $to_check = pop @check_queue;
-  if (exists $checked_libs{$to_check}) {
+  if (exists $checked_libs{$to_check} or $to_check =~ /ld-linux.so.2/) {
     next;
   } else {
     $checked_libs{$to_check} = 1;
diff --git a/deployment/macos/CMakeLists.txt b/deployment/macos/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0183d8ec8ec09181350a76f15b0eb29ec3292d6a
--- /dev/null
+++ b/deployment/macos/CMakeLists.txt
@@ -0,0 +1,42 @@
+#-------------------------------------------------------------------------------
+#  Author:  Andreas Schenk
+#
+#  This file contains OSX specific CPack configuration.
+#
+#-------------------------------------------------------------------------------
+
+
+set(CPACK_GENERATOR Bundle)
+set(CPACK_BUNDLE_NAME DNG)
+set(CPACK_BUNDLE_PLIST ${PROJECT_SOURCE_DIR}/deployment/macos/Info.plist)
+set (CPACK_PACKAGE_ICON ${PROJECT_SOURCE_DIR}/graphics/icon.icns)
+set (CPACK_BUNDLE_ICON ${PROJECT_SOURCE_DIR}/graphics/icon.icns)
+set(CPACK_PACKAGE_INSTALL_DIRECTORY "openstructure ${OST_VERSION_STRING}" )
+install(CODE "
+  if(NOT ${CMAKE_INSTALL_PREFIX} STREQUAL \${CMAKE_INSTALL_PREFIX})
+    set(LIB_DIR ${LIB_DIR}) #pass libdir variable in install code block
+    set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/cmake_support)
+    include(CopyDependencies)
+  
+    set(OST_BINARIES \"\${CMAKE_INSTALL_PREFIX}/bin/lddt\"
+                     \"\${CMAKE_INSTALL_PREFIX}/bin/chemdict_tool\"
+                     \"\${CMAKE_INSTALL_PREFIX}/libexec/openstructure/gosty\")
+  
+    #copy python into bundle if a version different from the system version is used
+    if(NOT ${PYTHON_BINARY} MATCHES /usr/bin/)
+      copy_python(${PYTHON_INCLUDE_PATH} ${PYTHON_VERSION} new_python_binary)
+      list(APPEND OST_BINARIES \${new_python_binary})
+    endif(NOT ${PYTHON_BINARY} MATCHES /usr/bin/)  
+  
+    file(GLOB_RECURSE OST_PYMODS \"\${CMAKE_INSTALL_PREFIX}/${LIB_DIR}/*.so\")
+    list(APPEND  OST_BINARIES \${OST_PYMODS})
+    
+    #copy Qt stuff
+    copy_qt(${QT_LIBRARY_DIR} ${QT_PLUGINS_DIR} qt_plugins)
+    list(APPEND  OST_BINARIES \${qt_plugins})
+  
+    write_bundle_binary(dng ../Resources/bin/dng)
+    copy_dependencies(\"\${OST_BINARIES}\") 
+  endif(NOT ${CMAKE_INSTALL_PREFIX} STREQUAL \${CMAKE_INSTALL_PREFIX})
+")
+
diff --git a/deployment/win/CMakeLists.txt b/deployment/win/CMakeLists.txt
index 01c1a1d7a1ad9dab4b969f5516fdc071dc6bd440..f8b2c1c77f811a118d97d01bc4fe660093e74db7 100644
--- a/deployment/win/CMakeLists.txt
+++ b/deployment/win/CMakeLists.txt
@@ -1,13 +1,13 @@
-if(DEPLOYMENT)
-#  get_ost_rev()
-  include(Deployment)
-  set(SUBST_DICT OST_VERSION="${OST_VERSION}")
-  add_custom_target(deployment ALL)
-
-
-
-  if(WIN32)
-    script(NAME create_archive.bat INPUT create_archive.bat.in SUBSTITUTE ${SUBST_DICT} TARGET deployment)
-  endif()
-endif()
+#-------------------------------------------------------------------------------
+#  Author:  Andreas Schenk
+#
+#  This file contains the Windows specific CPack configuration.
+#
+#-------------------------------------------------------------------------------
+
+install(CODE "
+  if(NOT ${CMAKE_INSTALL_PREFIX} STREQUAL \${CMAKE_INSTALL_PREFIX})
+    message(FATAL_ERROR "The Windows installer cannot yet be created with CPack.")            
+  endif(NOT ${CMAKE_INSTALL_PREFIX} STREQUAL \${CMAKE_INSTALL_PREFIX})
+")
 
diff --git a/modules/base/pymod/table.py b/modules/base/pymod/table.py
index 37c45feb9f9c6589dd4b9eba45bc70852322c796..8ad6bf5776afa335ff67e5988ac12d1bad70cf82 100644
--- a/modules/base/pymod/table.py
+++ b/modules/base/pymod/table.py
@@ -1368,77 +1368,135 @@ Statistics for column %(col)s
         max_idx = i
     return max_val, max_idx
 
-  def PlotBar(self, col, xlabels=None, ylabel=None, title=None, 
-              color=None, yerr=None, width=0.8, bottom=0, 
+  def PlotBar(self, cols, x_labels=None, x_labels_rotation='horizontal', y_title=None, title=None, 
+              colors=None, yerr_cols=None, width=0.8, bottom=0, 
               legend=True, save=False):
+
+    """
+    Create a barplot of the data in cols. Every element of a column will be represented
+    as a single bar. If there are several columns, each row will be grouped together.
+
+    :param cols: Column names with data. If cols is a string, every element of that column
+                 will be represented as a single bar. If cols is a list, every row resulting
+                 of these columns will be grouped together. Every value of the table still
+                 is represented by a single bar.
+
+    :param x_labels: Label for every row on x-axis.
+    :type x_labels: :class:`list`
     
+    :param x_labels_rotation: Can either be 'horizontal', 'vertical' or a number that 
+                              describes the rotation in degrees.
+
+    :param y_title: Y-axis description
+    :type y_title: :class:`str`
+
+    :title: Title
+    :type title: :class:`str`
+
+    :param colors: Colors of the different bars in each group. Must be a list of valid
+                   colornames in matplotlib. Length of color and cols must be consistent.
+    :type colors: :class:`list`
+
+    :param yerr_cols: Columns containing the y-error information. Can either be a string
+                      if only one column is plotted or a list otherwise. Length of
+                      yerr_cols and cols must be consistent.
+
+    :param width: The available space for the groups on the x-axis is divided by the exact
+                  number of groups. The parameters width is the fraction of what is actually
+                  used. If it would be 1.0 the bars of the different groups would touch each other.
+    :type width: :class:`float`
+
+    :param bottom: Bottom
+    :type bottom: :class:`float`
+
+    :param legend: Legend for color explanation, the corresponding column respectively.
+    :type legend: :class:`bool`
+
+    :param save: If set, a png image with name $save in the current working directory will be saved.
+    :type save: :class:`str`
+
+    """
     try:
       import numpy as np
       import matplotlib.pyplot as plt
     except:
       raise ImportError('PlotBar relies on numpy and matplotlib, but I could not import it!')
-      
-    if len(col)>7:
+    
+    if len(cols)>7:
       raise ValueError('More than seven bars at one position looks rather meaningless...')
       
     standard_colors=['b','g','y','c','m','r','k']
     data=[]
-  
-    if not isinstance(col,list):
-      col=[col]
-    if not isinstance(yerr,list):
-      yerr=[yerr]*len(self.rows)
+    yerr_data=[]
+
+    if not isinstance(cols, list):
+      cols=[cols]
       
-    if not color:
-      color=standard_colors[:len(col)]
+    if yerr_cols:
+      if not isinstance(yerr_cols, list):
+        yerr_cols=[yerr_cols]
+      if len(yerr_cols)!=len(cols):
+        raise RuntimeError ('Number of cols and number of error columns must be consistent!')
       
-    for c in col:
+    for c in cols:
       cid=self.GetColIndex(c)
       temp=list()
       for r in self.rows:
         temp.append(r[cid])
-      data.append(temp)
-      
-    if len(yerr)!=len(data[0]):
-      raise RuntimeError('Number of elements in yerr must be consistent with number of elements in each column!')
+      data.append(temp)  
       
+    if yerr_cols:
+      for c in yerr_cols:
+        cid=self.GetColIndex(c)
+        temp=list()
+        for r in self.rows:
+          temp.append(r[cid])
+        yerr_data.append(temp)
+    else:
+      for i in range(len(cols)):
+        yerr_data.append(None)
+
+    if not colors:
+      colors=standard_colors[:len(cols)]
+
+    if len(cols)!=len(colors):
+      raise RuntimeError("Number of columns and number of colors must be consistent!")
+
     ind=np.arange(len(data[0]))
     single_bar_width=float(width)/len(data)
     
     fig=plt.figure()
-    
     ax=fig.add_subplot(111)
-    
     legend_data=[]
-    
+
     for i in range(len(data)):
-      legend_data.append(ax.bar(ind+i*single_bar_width,data[i],single_bar_width,color=color[i],yerr=yerr[i])[0])
+      legend_data.append(ax.bar(ind+i*single_bar_width,data[i],single_bar_width,bottom=bottom,color=colors[i],yerr=yerr_data[i], ecolor='black')[0])
       
     if title!=None:
-      nice_title=x_title
+      nice_title=title
     else:
       nice_title="coolest barplot on earth"
     ax.set_title(nice_title, size='x-large', fontweight='bold')  
     
-    if ylabel!=None:
-      nice_y=ylabel
+    if y_title!=None:
+      nice_y=y_title
     else:
       nice_y="score" 
     ax.set_ylabel(nice_y)
     
-    if xlabels:
-      if len(data[0])!=len(xlabels):
+    if x_labels:
+      if len(data[0])!=len(x_labels):
         raise ValueError('Number of xlabels is not consistent with number of rows!')
     else:
-      xlabels=list()
+      x_labels=list()
       for i in range(1,len(data[0])+1):
-        xlabels.append('Row '+str(i))
+        x_labels.append('Row '+str(i))
       
     ax.set_xticks(ind+width*0.5)
-    ax.set_xticklabels(xlabels)
+    ax.set_xticklabels(x_labels, rotation = x_labels_rotation)
       
     if legend:
-      ax.legend(legend_data, col)   
+      ax.legend(legend_data, cols)   
       
     if save:
       plt.savefig(save)
diff --git a/modules/bindings/pymod/CMakeLists.txt b/modules/bindings/pymod/CMakeLists.txt
index 89244b23f96c53c63e8b44385d3c64a1c07e197e..8cd78a87cdf3491c6839bdbb33e0e76d86dc91dc 100644
--- a/modules/bindings/pymod/CMakeLists.txt
+++ b/modules/bindings/pymod/CMakeLists.txt
@@ -9,5 +9,6 @@ clustalw.py
 utils.py
 naccess.py
 blast.py
+cadscore.py
 )
 pymod(NAME bindings PY ${OST_BINDINGS})
diff --git a/modules/bindings/pymod/__init__.py b/modules/bindings/pymod/__init__.py
index 388a6054e165dc7fdd572892a11abb4f5f69ae62..e7f855fe8211181bcf4ff603b0b6cddb4486df2e 100644
--- a/modules/bindings/pymod/__init__.py
+++ b/modules/bindings/pymod/__init__.py
@@ -4,4 +4,6 @@ from ost.bindings import blast
 from ost.bindings import tmtools
 from ost.bindings import naccess
 from ost.bindings import hbplus
-from ost.bindings import clustalw
\ No newline at end of file
+from ost.bindings import clustalw
+from ost.bindings import cadscore
+
diff --git a/modules/bindings/pymod/cadscore.py b/modules/bindings/pymod/cadscore.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdaef13a955422b98189fe11fdcc1908e88f40e0
--- /dev/null
+++ b/modules/bindings/pymod/cadscore.py
@@ -0,0 +1,154 @@
+#------------------------------------------------------------------------------
+# This file is part of the OpenStructure project <www.openstructure.org>
+#
+# Copyright (C) 2008-2009 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
+#------------------------------------------------------------------------------
+"""
+Wrapper for the CAD score.
+
+References:
+
+Olechnovic K, Kulberkyte E, Venclovas C., CAD-score: A new contact area 
+difference-based function for evaluation of protein structural models
+Proteins. 2012 Aug 30. [Epub ahead of print]
+
+Authors: Valerio Mariani, Alessandro Barbato
+"""
+
+import subprocess, os, tempfile, platform
+from ost import settings, io
+
+def _SetupFiles(model,reference):
+  # create temporary directory
+  tmp_dir_name=tempfile.mkdtemp()
+  dia = 'PDB'
+  for chain in model.chains:
+    if chain.name==" ":
+      raise RuntimeError("One of the chains in the model has no name. Cannot calculate CAD score")
+    if len(chain.name) > 1:
+      dia = 'CHARMM'
+      break;
+    for res in chain.residues:
+      if len(res.name) > 3:
+        dia = 'CHARMM'
+        break;
+  io.SavePDB(model, os.path.join(tmp_dir_name, 'model.pdb'), dialect=dia)
+  dia = 'PDB'
+  for chain in reference.chains:
+    if chain.name==" ":
+      raise RuntimeError("One of the chains in the reference has no name. Cannot calculate CAD score")
+    if len(chain.name) > 1:
+      dia = 'CHARMM'
+      break;
+    for res in chain.residues:
+      if len(res.name) > 3:
+        dia = 'CHARMM'
+        break;
+  io.SavePDB(reference, os.path.join(tmp_dir_name, 'reference.pdb'),dialect=dia)
+  return tmp_dir_name
+
+def _CleanupFiles(dir_name):
+  import shutil
+  shutil.rmtree(dir_name)
+
+
+class CADResult:
+  """
+  Holds the result of running CAD
+  
+  .. attribute:: globalAA
+    
+    The global CAD's atom-atom (AA) score
+  
+  .. attribute:: localAA
+  
+    Dictionary containing local CAD's atom-atom (AA) scores. 
+    
+    :type: dictionary (key: chain.resnum (e.g.: A.24), value: CAD local AA score (see CAD Documentation online)
+  """
+  def __init__(self, globalAA, localAA):    
+    self.globalAA=globalAA
+    self.localAA=localAA    
+
+def _ParseCADGlobal(lines):
+  interesting_lines=lines[1]
+  aa=float(interesting_lines.split()[10])
+  return aa
+
+def _ParseCADLocal(lines):
+  local_aa_dict={}
+  for lin in lines[11:]:
+    items=lin.split()
+    chain=items[0]
+    resnum=int(items[1])
+    key=chain+'.'+str(resnum)
+    aa=float(items[2])
+    local_aa_dict[key]=aa
+  return local_aa_dict
+
+def _RunCAD(max_iter, tmp_dir):
+  model_filename=os.path.join(tmp_dir, 'model.pdb')
+  reference_filename=os.path.join(tmp_dir, 'reference.pdb')
+  if platform.system() == "Windows":
+    raise RuntimeError('CAD score not available on Windows')
+  else:
+    cad_calc_path=settings.Locate('CADscore_calc.bash')  
+    cad_read_g_path=settings.Locate('CADscore_read_global_scores.bash')  
+    cad_read_l_path=settings.Locate('CADscore_read_local_scores.bash')  
+    command1="\"%s\" -o %i -m \"%s\" -t \"%s\" -D \"%s\"" %(cad_calc_path, max_iter, model_filename, reference_filename, os.path.join(tmp_dir,"cadtemp"))
+    command2="\"%s\" -D \"%s\"" %(cad_read_g_path, os.path.join(tmp_dir,"cadtemp"))
+    command3="\"%s\" -m \"%s\" -t \"%s\" -D \"%s\" -c AA" %(cad_read_l_path, model_filename, reference_filename,os.path.join(tmp_dir,"cadtemp"))
+  ps1=subprocess.Popen(command1, shell=True, stdout=subprocess.PIPE)
+  ps1.wait()
+  ps2=subprocess.Popen(command2, shell=True, stdout=subprocess.PIPE)
+  ps2.wait()
+  lines=ps2.stdout.readlines()
+  try:
+    globalAA=_ParseCADGlobal(lines)
+  except:
+    raise RuntimeError("CAD calculation failed")
+  ps3=subprocess.Popen(command3, shell=True, stdout=subprocess.PIPE)
+  ps3.wait()
+  lines=ps3.stdout.readlines()
+  try:
+    localAA=_ParseCADLocal(lines)
+  except:
+    raise RuntimeError("CAD calculation failed")
+
+  return CADResult(globalAA,localAA)
+
+
+def CADScore(model, reference, max_iter=300):
+  """
+  Calculates global and local atom-atom (AA) CAD Scores
+  
+
+  :param model: The model structure. 
+  :type model: :class:`~ost.mol.EntityView` or :class:`~ost.mol.EntityHandle`
+  :param reference: The reference structure
+  :type model2: :class:`~ost.mol.EntityView` or :class:`~ost.mol.EntityHandle`
+  :param max_iter: Optional. The maximum number of iteration for the tessellation algorithm before giving up. By default 300
+  :returns: The result of the CAD score calculation
+  :rtype: :class:`CADResult`
+  
+  :raises: :class:`~ost.settings.FileNotFound` if any of the CAD score exacutables could not be located.
+  :raises: :class:`RuntimeError` if the calculation failed
+  """
+  tmp_dir_name=_SetupFiles(model, reference)
+  result=_RunCAD(max_iter, tmp_dir_name)
+  _CleanupFiles(tmp_dir_name)
+  return result
+
diff --git a/modules/geom/src/composite3.cc b/modules/geom/src/composite3.cc
index 347629d2c059cd3be0ecdef523ab65363e20adb3..3813fb668c31f0b52f7a03d5388de12857a45b1a 100644
--- a/modules/geom/src/composite3.cc
+++ b/modules/geom/src/composite3.cc
@@ -19,6 +19,7 @@
 #include <sstream>
 #include <iomanip>
 #include <limits>
+#include <algorithm>
 
 #include <boost/filesystem/fstream.hpp>
 
diff --git a/modules/geom/src/quat.cc b/modules/geom/src/quat.cc
index 44e39ee2bb71d9c308d07cfb8a43ffa8403e6f8f..84fcb872a5a3deff62d114ecd15b3a734a273cc7 100644
--- a/modules/geom/src/quat.cc
+++ b/modules/geom/src/quat.cc
@@ -133,9 +133,9 @@ Vec3 find_orthogonal_vector(const Vec3& xyz)
   //if (vecnormsqr <= numeric_limits<Real>::epsilon())
   
   Real components[3] = {
-    fabs(xyz[0]),
-    fabs(xyz[1]),
-    fabs(xyz[2])
+    std::abs<Real>(xyz[0]),
+    std::abs<Real>(xyz[1]),
+    std::abs<Real>(xyz[2])
   };
         
   Real*  where = ::std::min_element(components, components+3);
diff --git a/modules/gfx/pymod/export_scene.cc b/modules/gfx/pymod/export_scene.cc
index 23ff9d687b497960588b169884690ff6a071243e..9f3042cb2d7328097691db1d338744d680d0946c 100644
--- a/modules/gfx/pymod/export_scene.cc
+++ b/modules/gfx/pymod/export_scene.cc
@@ -240,5 +240,7 @@ void export_Scene()
     .def("GetBoundingBox",scene_get_bb2)
     .def("GetBoundingBox",scene_get_bb3)
     .add_property("bounding_box",scene_get_bb1)
+    .add_property("export_aspect",&Scene::GetExportAspect,&Scene::SetExportAspect)
+    .add_property("show_export_aspect",&Scene::GetShowExportAspect,&Scene::SetShowExportAspect)
   ;
 }
diff --git a/modules/gfx/src/gfx_node.cc b/modules/gfx/src/gfx_node.cc
index 8d417aeec6660d3ecf3aa689cf68d3e90c781fa7..813ce6f413e677e8b884ae191f4b3a608b27a47c 100644
--- a/modules/gfx/src/gfx_node.cc
+++ b/modules/gfx/src/gfx_node.cc
@@ -141,7 +141,7 @@ bool GfxNode::IsAttachedToScene() const
 void GfxNode::Add(GfxObjP obj)
 {
   GfxNodeP node=obj;
-  this->Add(obj);
+  this->Add(node);
 }
 
 void GfxNode::Remove(GfxObjP obj)
diff --git a/modules/gfx/src/scene.cc b/modules/gfx/src/scene.cc
index 9212d8eab37f015b5019c25438efe75d162fb268..e4d37b841160760a1c130f832f0b9828abc03daa 100644
--- a/modules/gfx/src/scene.cc
+++ b/modules/gfx/src/scene.cc
@@ -140,7 +140,9 @@ Scene::Scene():
   update_bg_(false),
   bg_grad_(),
   bg_bm_(),
-  bg_tex_()
+  bg_tex_(),
+  export_aspect_(1.0),
+  show_export_aspect_(false)
 {
   transform_.SetTrans(Vec3(0,0,-100));
 }
@@ -1988,6 +1990,73 @@ void Scene::prep_blur()
   glFlush();
 }
 
+namespace {
+  class ViewportRenderer {
+    unsigned int vp_width_,vp_height_;
+    public:
+      ViewportRenderer(unsigned int vpw, unsigned int vph):
+      vp_width_(vpw), vp_height_(vph) 
+      { 
+#if OST_SHADER_SUPPORT_ENABLED
+        Shader::Instance().PushProgram();
+        Shader::Instance().Activate("");
+#endif
+        glPushAttrib(GL_ALL_ATTRIB_BITS);
+        glPushClientAttrib(GL_ALL_ATTRIB_BITS);
+
+        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);
+#if defined(OST_GL_VERSION_2_0)
+        glDisable(GL_MULTISAMPLE);
+#endif
+        glMatrixMode(GL_PROJECTION);
+        glPushMatrix();
+        glLoadIdentity();
+        glOrtho(0,vp_width_,0,vp_height_,-1,1);
+        glMatrixMode(GL_MODELVIEW);
+        glPushMatrix();
+        glLoadIdentity();
+      }
+
+      void DrawTex(GLuint tex_id) {
+        glEnable(GL_TEXTURE_2D);
+#if OST_SHADER_SUPPORT_ENABLED
+        if(OST_GL_VERSION_2_0) {
+          glActiveTexture(GL_TEXTURE0);
+        }
+#endif
+        glBindTexture(GL_TEXTURE_2D, tex_id);
+        glColor3f(0.0,0.0,0.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();
+     }
+
+     ~ViewportRenderer() {
+       glBindTexture(GL_TEXTURE_2D, 0);
+       glDisable(GL_TEXTURE_2D);
+       glMatrixMode(GL_PROJECTION);
+       glPopMatrix();
+       glMatrixMode(GL_MODELVIEW);
+       glPopMatrix();
+       glPopClientAttrib();
+       glPopAttrib();
+#if OST_SHADER_SUPPORT_ENABLED
+       Shader::Instance().PopProgram();
+#endif
+     }
+  };
+}
+
 void Scene::render_bg()
 {
   if(!gl_init_) return;
@@ -1998,65 +2067,62 @@ void Scene::render_bg()
     update_bg_=false;
   }
 
-  // setup state for simple texture quad
-#if OST_SHADER_SUPPORT_ENABLED
-  Shader::Instance().PushProgram();
-  Shader::Instance().Activate("");
-#endif
-  glPushAttrib(GL_ALL_ATTRIB_BITS);
-  glPushClientAttrib(GL_ALL_ATTRIB_BITS);
-
-  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);
-#if defined(OST_GL_VERSION_2_0)
-  glDisable(GL_MULTISAMPLE);
-#endif
-  glMatrixMode(GL_PROJECTION);
-  glPushMatrix();
-  glLoadIdentity();
-  glOrtho(0,vp_width_,0,vp_height_,-1,1);
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
-
-  // draw bg texture quad
-  glEnable(GL_TEXTURE_2D);
-#if OST_SHADER_SUPPORT_ENABLED
-  if(OST_GL_VERSION_2_0) {
-    glActiveTexture(GL_TEXTURE0);
+  {
+    ViewportRenderer vpr(vp_width_,vp_height_);
+    vpr.DrawTex(bg_tex_);
+    // dtor takes care of the rest
   }
-#endif
-  glBindTexture(GL_TEXTURE_2D, bg_tex_);
-  // draw
-  glColor3f(0.0,0.0,0.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 all settings
-  glBindTexture(GL_TEXTURE_2D, 0);
-  glDisable(GL_TEXTURE_2D);
-  glMatrixMode(GL_PROJECTION);
-  glPopMatrix();
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-  glPopClientAttrib();
-  glPopAttrib();
-#if OST_SHADER_SUPPORT_ENABLED
-  Shader::Instance().PopProgram();
-#endif
   check_gl_error("render_bg()");
 }
 
+void Scene::render_export_aspect()
+{
+  unsigned int a_width=static_cast<int>(static_cast<float>(vp_height_)*export_aspect_);
+  if(a_width<vp_width_) {
+    // need to draw horizontal boundaries
+    unsigned int o1=(vp_width_-a_width)>>1;
+    unsigned int o2=a_width+o1;
+    ViewportRenderer vpr(vp_width_,vp_height_);
+    glDisable(GL_DEPTH);
+    glEnable(GL_BLEND);
+    glColor4f(0.0,0.0,0.0,0.5);
+    glBegin(GL_QUADS);
+    glVertex2i(0,0);
+    glVertex2i(0,vp_height_);
+    glVertex2i(o1,vp_height_);
+    glVertex2i(o1,0);
+    glVertex2i(o2,0);
+    glVertex2i(o2,vp_height_);
+    glVertex2i(vp_width_,vp_height_);
+    glVertex2i(vp_width_,0);
+    glEnd();
+    // vpr dtor does gl cleanup
+  } else if(a_width>vp_width_) {
+    unsigned int a_height=static_cast<int>(static_cast<float>(vp_width_)/export_aspect_);
+    // need to draw vertical boundaries
+    unsigned int o1=(vp_height_-a_height)>>1;
+    unsigned int o2=a_height+o1;
+    ViewportRenderer vpr(vp_width_,vp_height_);
+    glDisable(GL_DEPTH);
+    glEnable(GL_BLEND);
+    glColor4f(0.0,0.0,0.0,0.5);
+    glBegin(GL_QUADS);
+    glVertex2i(0,0);
+    glVertex2i(0,o1);
+    glVertex2i(vp_width_,o1);
+    glVertex2i(vp_width_,0);
+    glVertex2i(0,o2);
+    glVertex2i(0,vp_height_);
+    glVertex2i(vp_width_,vp_height_);
+    glVertex2i(vp_width_,o2);
+    glEnd();
+    // vpr dtor does gl cleanup
+  }
+
+
+} // anon ns
+
 void Scene::render_scene()
 {
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -2110,6 +2176,8 @@ void Scene::render_scene()
 #endif
 
   render_glow();
+
+  if(show_export_aspect_) render_export_aspect();
 }
 
 void Scene::render_glow()
@@ -2422,4 +2490,20 @@ void Scene::do_autoslab()
   RequestRedraw();
 }
 
+void Scene::SetExportAspect(float a)
+{
+  if(a>0.0) {
+    export_aspect_=a;
+    if(show_export_aspect_) RequestRedraw();
+  }
+}
+
+void Scene::SetShowExportAspect(bool f)
+{
+  if(f!=show_export_aspect_) {
+    show_export_aspect_=f;
+    RequestRedraw();
+  }
+}
+
 }} // ns
diff --git a/modules/gfx/src/scene.hh b/modules/gfx/src/scene.hh
index f6f4c87f1544b091d0e51777b7b254501ae4d22b..a8a9afbe1a8170083358694a2be1b06da7724936 100644
--- a/modules/gfx/src/scene.hh
+++ b/modules/gfx/src/scene.hh
@@ -495,6 +495,11 @@ class DLLEXPORT_OST_GFX Scene {
   /// experimental feature
   void SetBeaconOff();
 
+  void SetExportAspect(float a);
+  float GetExportAspect() const {return export_aspect_;}
+  void SetShowExportAspect(bool f);
+  bool GetShowExportAspect() const {return show_export_aspect_;}
+
 protected:
   friend class GfxObj; 
   friend class GfxNode;
@@ -585,7 +590,8 @@ private:
   Bitmap bg_bm_;
   unsigned int bg_tex_;
   
-  
+  float export_aspect_; 
+  bool show_export_aspect_;
 
   void set_near(float n);
   void set_far(float f);
@@ -595,6 +601,7 @@ private:
   void prep_blur();
   void stereo_projection(int view);
   void render_bg();
+  void render_export_aspect();
   void render_scene();
   void render_glow();
   void render_stereo();
diff --git a/modules/gui/src/data_viewer/data_viewer_panel_base.cc b/modules/gui/src/data_viewer/data_viewer_panel_base.cc
index eb53154eef140a11ab9d215ab5a5137ce0127821..6405eb7774f285a666e80fc14eec050491dfe493 100644
--- a/modules/gui/src/data_viewer/data_viewer_panel_base.cc
+++ b/modules/gui/src/data_viewer/data_viewer_panel_base.cc
@@ -77,7 +77,8 @@ DataViewerPanelBase::DataViewerPanelBase(const Data& data,QWidget* parent):
   update_extent_(),
   fast_low_mag_(true),
   fast_high_mag_(true),
-  antialiasing_(true)
+  antialiasing_(true),
+  drag_start_()
 {
   update_min_max();
   UpdateNormalizer(data_min_,data_max_,1.0,false);
@@ -478,7 +479,6 @@ void DataViewerPanelBase::mousePressEvent(QMouseEvent* event)
     rubberband_->hide();
     last_x_=event->x();
     last_y_=event->y();
-    QPoint cp=FracPointToWin(geom::Vec2(clicked_position_));
     clicked_position_ = geom::Vec3(WinToFracPoint(QPoint(event->x(),event->y())));
     clicked_position_[2]=slab_;
     emit clicked(clicked_position_);
@@ -522,35 +522,34 @@ void DataViewerPanelBase::mouseMoveEvent(QMouseEvent* event)
     int dy = event->y()-last_y_;
     move(dx,dy);
   } else if(event->buttons() == Qt::LeftButton  && event->modifiers()==Qt::NoModifier) {
-    static Point drag_start;
     // left mouse drag does selection box
     if(!rubberband_->isVisible()){
-      drag_start=WinToPoint(rubberband_->geometry().topLeft());
+      drag_start_=WinToPoint(rubberband_->geometry().topLeft());
       rubberband_->show();
     }
     QSize vsize=size();
     Point mouse_pos=WinToPoint(event->x(),event->y());
     Point max_pos=WinToPoint(vsize.width(),vsize.height());
     Point min_pos=WinToPoint(0,0);
-    selection_=Extent(Point(std::max(min_pos[0],std::min(drag_start[0],mouse_pos[0])),
-                            std::max(min_pos[1],std::min(drag_start[1],mouse_pos[1])), slab_),
-                      Point(std::max(drag_start[0],std::min(max_pos[0],mouse_pos[0])),
-                            std::max(drag_start[1],std::min(max_pos[1],mouse_pos[1])), slab_));
+    selection_=Extent(Point(std::max(min_pos[0],std::min(drag_start_[0],mouse_pos[0])),
+                            std::max(min_pos[1],std::min(drag_start_[1],mouse_pos[1])), slab_),
+                      Point(std::max(drag_start_[0],std::min(max_pos[0],mouse_pos[0])),
+                            std::max(drag_start_[1],std::min(max_pos[1],mouse_pos[1])), slab_));
     if(selection_mode_>0){
       Size s=selection_.GetSize();
       int minsize=std::min<int>(s[0],s[1]);
       if(selection_mode_==2){
         minsize=1<<static_cast<int>(floor(log(Real(minsize))/log(Real(2.0))));
       }
-      if(drag_start[0]>mouse_pos[0] && drag_start[1]>mouse_pos[1]){
-        selection_.SetStart(drag_start-Point(minsize,minsize)+Point(1,1));
-        selection_.SetEnd(drag_start);        
-      }else if(drag_start[0]>mouse_pos[0] && drag_start[1]<=mouse_pos[1]){
-        selection_.SetStart(drag_start-Point(minsize,0)+Point(1,0));
-        selection_.SetEnd(drag_start+Point(0,minsize)-Point(0,1));        
-      }else if(drag_start[0]<=mouse_pos[0] && drag_start[1]>mouse_pos[1]){
-        selection_.SetStart(drag_start-Point(0,minsize)+Point(0,1));        
-        selection_.SetEnd(drag_start+Point(minsize,0)-Point(1,0));
+      if(drag_start_[0]>mouse_pos[0] && drag_start_[1]>mouse_pos[1]){
+        selection_.SetStart(drag_start_-Point(minsize,minsize)+Point(1,1));
+        selection_.SetEnd(drag_start_);        
+      }else if(drag_start_[0]>mouse_pos[0] && drag_start_[1]<=mouse_pos[1]){
+        selection_.SetStart(drag_start_-Point(minsize,0)+Point(1,0));
+        selection_.SetEnd(drag_start_+Point(0,minsize)-Point(0,1));        
+      }else if(drag_start_[0]<=mouse_pos[0] && drag_start_[1]>mouse_pos[1]){
+        selection_.SetStart(drag_start_-Point(0,minsize)+Point(0,1));        
+        selection_.SetEnd(drag_start_+Point(minsize,0)-Point(1,0));
       }else{
         selection_.SetEnd(selection_.GetStart()+Point(minsize,minsize)-Point(1,1));
       }
diff --git a/modules/gui/src/data_viewer/data_viewer_panel_base.hh b/modules/gui/src/data_viewer/data_viewer_panel_base.hh
index ec2345a5cd471ba29ab78eded8a53934d0ba5624..1727ea9a3e0d5c0fa6c2c9363e9acc77eaf72996 100644
--- a/modules/gui/src/data_viewer/data_viewer_panel_base.hh
+++ b/modules/gui/src/data_viewer/data_viewer_panel_base.hh
@@ -245,7 +245,8 @@ private:
   bool fast_high_mag_;
 
   bool antialiasing_;
-  
+  Point drag_start_;
+
   void move(int dx, int dy);
   void slab(int dz);
   void zoom(int d);
diff --git a/modules/img/alg/src/fft.cc b/modules/img/alg/src/fft.cc
index a924a0fe6ace8e5199ea31a04c664ddbe43194d7..ddc137d1a5272ee98d091b211458ce3791f0c7c7 100644
--- a/modules/img/alg/src/fft.cc
+++ b/modules/img/alg/src/fft.cc
@@ -258,7 +258,7 @@ ImageStateBasePtr FFTFnc::VisitState<Complex,SpatialDomain>(const ComplexSpatial
 
   out_state->Data()=in_state.Data(); // use assignement op to copy data area to new state
   int rank = size.GetDim();
-  int n[3] = {size[0],size[1],size[2]};
+  int n[3] = {static_cast<int>(size[0]),static_cast<int>(size[1]),static_cast<int>(size[2])};
   int dir = FFTW_FORWARD;
 
   assert(sizeof(OST_FFTW_fftw_complex)==sizeof(Complex));
@@ -297,7 +297,7 @@ ImageStateBasePtr FFTFnc::VisitState<Complex,FrequencyDomain>(const ComplexFrequ
   out_state->SetAbsoluteOrigin(in_state.GetAbsoluteOrigin());
 
   int rank = size.GetDim();
-  int n[3] = {size[0],size[1],size[2]};
+  int n[3] = {static_cast<int>(size[0]),static_cast<int>(size[1]),static_cast<int>(size[2])};
   int dir = FFTW_BACKWARD;
 
   assert(sizeof(OST_FFTW_fftw_complex)==sizeof(Complex));
diff --git a/modules/img/alg/src/fourier_filters.cc b/modules/img/alg/src/fourier_filters.cc
index a1b355b2d9d7f6c72e5c286b6fb17ea080bb5469..57462ecfeae38dc26f31a210e5fd8b63b334506e 100644
--- a/modules/img/alg/src/fourier_filters.cc
+++ b/modules/img/alg/src/fourier_filters.cc
@@ -58,7 +58,7 @@ public:
       Vec3 d=is.GetSampling().GetPixelSampling();
       Real F=calcF(Point(it),d);
       Real value = (F <= limit_ ? 1.0 : 0.0);
-      is.Value(it)*=value;
+      is.Value(it)*=Val2Val<Real,T>(value);
     }
   }
 
@@ -91,7 +91,7 @@ public:
       Vec3 d=is.GetSampling().GetPixelSampling();
       Real F=calcF(Point(it),d);
       Real value= (F >= limit_ ? 1.0 : 0.0);
-      is.Value(it)*=value;
+      is.Value(it)*=Val2Val<Real,T>(value);
     }
   }
 
@@ -123,7 +123,7 @@ public:
       Vec3 d=is.GetSampling().GetPixelSampling();
       Real F=calcF(Point(it),d);
       Real value=exp(-F*F/(2.0*limit_*limit_));
-      is.Value(it)*=value;
+      is.Value(it)*=Val2Val<Real,T>(value);
     }
   }
 
@@ -155,7 +155,7 @@ public:
       Vec3 d=is.GetSampling().GetPixelSampling();
       Real F=calcF(Point(it),d);
       Real value=1.0-exp(-F*F/(2.0*limit_*limit_));
-      is.Value(it)*=value;
+      is.Value(it)*=Val2Val<Real,T>(value);
     }
   }
 
@@ -195,7 +195,7 @@ public:
         Real F=calcF(Point(it),d);
         Real teff=t_*t_/l2*F*(t_>=0?1.0:-1.0);
         Real value=1.0/(1.0+exp((F-limit_)/(teff)));
-        is.Value(it)*=value;
+        is.Value(it)*=Val2Val<Real,T>(value);
       }
     }
   }
@@ -235,7 +235,7 @@ public:
       Vec3 d=is.GetSampling().GetPixelSampling();
       Real F=calcF(Point(it),d);
       Real value=(1.0/(sqrt(1+pow(F/rad,Real(2.0)*order))));
-      is.Value(it)*=value;
+      is.Value(it)*=Val2Val<Real,T>(value);
     }
   }
 
diff --git a/modules/img/alg/src/module_config.hh b/modules/img/alg/src/module_config.hh
index 2ebf29cbfe32d058b742f6d9964d2c494d23ceaa..9749440520b0870acd089847662f5f5fd77a43a8 100644
--- a/modules/img/alg/src/module_config.hh
+++ b/modules/img/alg/src/module_config.hh
@@ -26,7 +26,7 @@
 #  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 ost::img::image_state::t;
+#    define OST_IMG_ALG_EXPLICIT_INST_DECL(c, t) extern template c TEMPLATE_EXPORT ost::img::image_state::t;
 #  endif
 #else
 #  define DLLEXPORT_IMG_ALG DLLIMPORT
diff --git a/modules/img/alg/src/stat_accumulator.hh b/modules/img/alg/src/stat_accumulator.hh
index 3483890b0ced8c3f5e71382f3273fcdcafc68ef0..a07d6219e5dae160cb8198f611d5b38e0ccd4838 100644
--- a/modules/img/alg/src/stat_accumulator.hh
+++ b/modules/img/alg/src/stat_accumulator.hh
@@ -21,6 +21,7 @@
 #define OST_STAT_ACCUMULATOR_HH
 
 #include <ost/base.hh>
+#include <ost/message.hh>
 #include <ost/img/alg/module_config.hh>
 
 namespace ost { namespace img { namespace alg {
diff --git a/modules/img/base/src/extent_mask.cc b/modules/img/base/src/extent_mask.cc
index 9551959620941b5da82ffa2a0d64dc653ed80ede..bf8fbb45383bf37219eed374807be2f043de0c7b 100644
--- a/modules/img/base/src/extent_mask.cc
+++ b/modules/img/base/src/extent_mask.cc
@@ -41,7 +41,7 @@ MaskPtr ExtentMask::Clone()
 }
 bool ExtentMask::IsInside(const Vec2& v)
 {
-  return Contains(Point(floor(v[0]),floor(v[1])));
+  return Contains(Point(static_cast<int>(floor(v[0])),static_cast<int>(floor(v[1]))));
 }
 
 void ExtentMask::Shift(const Vec2& v)
diff --git a/modules/io/doc/mmcif.rst b/modules/io/doc/mmcif.rst
index da1bed9d710d3ec33a4c7dfc16cbc02f6812348e..38934cc7943df2c6d1cec5f40dd43c34485368e6 100644
--- a/modules/io/doc/mmcif.rst
+++ b/modules/io/doc/mmcif.rst
@@ -782,6 +782,7 @@ of the annotation available.
   .. attribute:: align_id
     
     Uniquely identifies every struct_ref_seq item in the mmCIF file.
+
     :type: :class:`str`
 
   .. attribute:: seq_begin
diff --git a/modules/io/pymod/wrap_io.cc b/modules/io/pymod/wrap_io.cc
index 87e4c66185d6096ffa35ae0bff4bdfbeb0a33159..789efe111ba32661c5e0a3da15fb6901e55bbb9c 100644
--- a/modules/io/pymod/wrap_io.cc
+++ b/modules/io/pymod/wrap_io.cc
@@ -66,9 +66,6 @@ BOOST_PYTHON_FUNCTION_OVERLOADS(save_entity_handle_ov,
 BOOST_PYTHON_FUNCTION_OVERLOADS(save_entity_view_ov,
                                 save_ent_view, 2, 3)
 
-BOOST_PYTHON_FUNCTION_OVERLOADS(save_charmm_trj_ov,
-                                SaveCHARMMTraj, 3, 4)
-
 }
 
 void export_pdb_io();
diff --git a/modules/io/src/img/map_io_mrc_handler.cc b/modules/io/src/img/map_io_mrc_handler.cc
index 55d4f69138c1e48b90d797f2c3aefe31b2b8efe2..b49e976eca8e9d1b45aa24b8cffa347934fb8dfe 100644
--- a/modules/io/src/img/map_io_mrc_handler.cc
+++ b/modules/io/src/img/map_io_mrc_handler.cc
@@ -698,7 +698,6 @@ void real_dumper(BinaryOStream<CONVERSIONTYPE>& f, header_base& header, const Co
   img::Point pnt;
   char this_dummy; //create dummy variable to give to Progress as this
   Progress::Instance().Register(&this_dummy,header.ns*header.nr,100);
-  Point start=image.GetExtent().GetStart();
   for(int ss=0;ss<header.ns;++ss) {
     pnt[maps]=header.nsstart+ss;
     for(int sr=0;sr<header.nr;++sr) {
diff --git a/modules/io/src/img/map_io_tiff_handler.cc b/modules/io/src/img/map_io_tiff_handler.cc
index e6144315b78e3c2c13ddd7669f68ca841b983d0d..4be8a815e335f4c17ff75ad2f57241cffad24430 100644
--- a/modules/io/src/img/map_io_tiff_handler.cc
+++ b/modules/io/src/img/map_io_tiff_handler.cc
@@ -301,12 +301,12 @@ void MapIOTiffHandler::do_export(const img::MapHandle& image,TIFF* tfile,TIF& fo
   img::image_state::ComplexSpatialImageState *isc = NULL;
   img::image_state::WordSpatialImageState *isw = NULL;
 
-  boost::function<void (TIFF *,img::image_state::RealSpatialImageState*,UINTNN_T,UINTNN_T,UINTNN_T,UINTNN_T,const  img::NormalizerPtr& )> fsr;
-  boost::function<void (TIFF *,img::image_state::ComplexSpatialImageState*,UINTNN_T,UINTNN_T,UINTNN_T,UINTNN_T,const  img::NormalizerPtr&)> fsc;
-  boost::function<void (TIFF *,img::image_state::WordSpatialImageState*,UINTNN_T,UINTNN_T,UINTNN_T,UINTNN_T,const  img::NormalizerPtr&)> fsw;
+  boost::function<void (TIFF *,img::image_state::RealSpatialImageState*,unsigned int,unsigned int,unsigned int,unsigned int,const  img::NormalizerPtr& )> fsr;
+  boost::function<void (TIFF *,img::image_state::ComplexSpatialImageState*,unsigned int,unsigned int,unsigned int,unsigned int,const  img::NormalizerPtr&)> fsc;
+  boost::function<void (TIFF *,img::image_state::WordSpatialImageState*,unsigned int,unsigned int,unsigned int,unsigned int,const  img::NormalizerPtr&)> fsw;
 
-  UINTNN_T width=image.GetSize().GetWidth();
-  UINTNN_T height=image.GetSize().GetHeight();
+  unsigned int width=image.GetSize().GetWidth();
+  unsigned int height=image.GetSize().GetHeight();
   uint16 spp=1;
   uint16 fmt =0;
   uint16 bpp =0 ;
@@ -344,7 +344,7 @@ void MapIOTiffHandler::do_export(const img::MapHandle& image,TIFF* tfile,TIF& fo
       case OST_BIT32_FORMAT:
         fmt=SAMPLEFORMAT_INT;
         bpp=32;
-        fsr=detail::do_tiff_write<Real,INTNN_T,img::image_state::RealSpatialImageState>;
+        fsr=detail::do_tiff_write<Real,int32,img::image_state::RealSpatialImageState>;
         break;
       case OST_FLOAT_FORMAT:
         fmt=SAMPLEFORMAT_IEEEFP;
@@ -377,7 +377,7 @@ void MapIOTiffHandler::do_export(const img::MapHandle& image,TIFF* tfile,TIF& fo
       case OST_BIT32_FORMAT:
         fmt=SAMPLEFORMAT_UINT;
         bpp=32;
-        fsr=detail::do_tiff_write<Real,UINTNN_T,img::image_state::RealSpatialImageState>;
+        fsr=detail::do_tiff_write<Real,uint32,img::image_state::RealSpatialImageState>;
         break;
       case OST_FLOAT_FORMAT:
         fmt=SAMPLEFORMAT_IEEEFP;
@@ -412,7 +412,7 @@ void MapIOTiffHandler::do_export(const img::MapHandle& image,TIFF* tfile,TIF& fo
     case OST_BIT32_FORMAT:
       fmt=SAMPLEFORMAT_COMPLEXINT;
       bpp=64;
-      fsc=detail::do_tiff_write<Complex,std::complex<INTNN_T>,img::image_state::ComplexSpatialImageState>;
+      fsc=detail::do_tiff_write<Complex,std::complex<int32>,img::image_state::ComplexSpatialImageState>;
       break;
     case OST_FLOAT_FORMAT:
       fmt=SAMPLEFORMAT_COMPLEXIEEEFP;
@@ -438,7 +438,7 @@ void MapIOTiffHandler::do_export(const img::MapHandle& image,TIFF* tfile,TIF& fo
   }
 
   TIFFSetField(tfile,TIFFTAG_BITSPERSAMPLE,bpp);
-  UINTNN_T rowsperstrip=std::max<int>(1,8192/(width*bpp/8)); //ca. 8 kb per strip (adobe tiff specs recomendation)
+  unsigned int rowsperstrip=std::max<int>(1,8192/(width*bpp/8)); //ca. 8 kb per strip (adobe tiff specs recomendation)
   TIFFSetField(tfile,TIFFTAG_ROWSPERSTRIP,rowsperstrip);
   TIFFSetField(tfile,TIFFTAG_SAMPLEFORMAT,fmt);
   unsigned int stripcount=static_cast<int>(ceil( height/static_cast<Real>(rowsperstrip)));
@@ -551,9 +551,8 @@ TIFF* MapIOTiffHandler::open_subimage_stream(std::istream& location,const TIF& f
 
 void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  const TIF& formattif)
 {
-  UINTNN_T width,height,rps;
+  unsigned int width,height,rps;
   uint16 bpp,spp,plc,ori,reso=RESUNIT_NONE,fmt=SAMPLEFORMAT_UINT;
-  UINTNN_T* sbc;
   float xpos=0.0,ypos=0.0;
   float xreso=1.0,yreso=1.0;
 
@@ -563,7 +562,6 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
   if(!TIFFGetField(tfile,TIFFTAG_SAMPLESPERPIXEL,&spp)) {
     spp=0;
   }
-  TIFFGetField(tfile,TIFFTAG_STRIPBYTECOUNTS, &sbc);
   TIFFGetField(tfile,TIFFTAG_PLANARCONFIG,&plc);
   if(!TIFFGetField(tfile,TIFFTAG_ORIENTATION,&ori)) {
     ori=0;
@@ -639,7 +637,7 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
       throw IOException("unexpected failure of dynamic_cast in tiff io");
     }
 
-    int current_row = 0;
+    unsigned int current_row = 0;
 
     LOG_VERBOSE("I/O Tiff: " << "importing data");
     img::Progress::Instance().Register(this,stripcount,100);
@@ -647,14 +645,14 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
       int cread=TIFFReadEncodedStrip(tfile, strip, buf, (tsize_t) -1);
 
       if(bpp==8) {
-  int rowcount = cread/(width*spp);
-  detail::do_tiff_read<uchar,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
+        int rowcount = cread/(width*spp);
+        detail::do_tiff_read<uchar,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
       } else if(bpp==16) {
-  uint rowcount = cread/(width*2*spp);
-  detail::do_tiff_read<uint16,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
+        uint rowcount = cread/(width*2*spp);
+        detail::do_tiff_read<uint16,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
       } else if(bpp==32) {
-  uint rowcount = cread/(width*4*spp);
-  detail::do_tiff_read<UINTNN_T,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
+        uint rowcount = cread/(width*4*spp);
+        detail::do_tiff_read<uint32,short,img::image_state::WordSpatialImageState>(buf,rowcount,width,is,current_row,spp);
       }
       img::Progress::Instance().AdvanceProgress(this);
     }
@@ -694,7 +692,7 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
     }
 
 
-    int current_row = 0;
+    unsigned int current_row = 0;
 
     LOG_VERBOSE("I/O Tiff: " << "importing data");
     img::Progress::Instance().Register(this,stripcount,100);
@@ -728,9 +726,9 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
       } else if(bpp==32) {
         uint rowcount = cread/(width*4*spp);
         if(fmt==SAMPLEFORMAT_INT){
-          detail::do_tiff_read<INTNN_T,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
+          detail::do_tiff_read<int32,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
         }else if(fmt==SAMPLEFORMAT_UINT){
-          detail::do_tiff_read<UINTNN_T,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
+          detail::do_tiff_read<uint32,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
         }else if(fmt==SAMPLEFORMAT_IEEEFP){
           detail::do_tiff_read<float,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
         }else if(fmt==SAMPLEFORMAT_COMPLEXINT){
@@ -745,7 +743,7 @@ void MapIOTiffHandler::load_image_data(TIFF* tfile, img::ImageHandle& image,  co
         if(fmt==SAMPLEFORMAT_IEEEFP){
           detail::do_tiff_read<Real,Real,img::image_state::RealSpatialImageState>(buf,rowcount,width,isr,current_row,spp);
         }else if(fmt==SAMPLEFORMAT_COMPLEXINT){
-          detail::do_tiff_read<detail::COMPLEXINTNN_T,Complex,img::image_state::ComplexSpatialImageState>(buf,rowcount,width,isc,current_row,spp);
+          detail::do_tiff_read<detail::complexint32,Complex,img::image_state::ComplexSpatialImageState>(buf,rowcount,width,isc,current_row,spp);
         }else if(fmt==SAMPLEFORMAT_COMPLEXIEEEFP){
           detail::do_tiff_read<std::complex<float>,Complex,img::image_state::ComplexSpatialImageState>(buf,rowcount,width,isc,current_row,spp);
         }else{
diff --git a/modules/io/src/img/tiff_util.cc b/modules/io/src/img/tiff_util.cc
index 105ebf73becf4ea763190c52d1fdec59402eca7f..053f179766865a3cdb3d4a64553c55f59b7268e0 100644
--- a/modules/io/src/img/tiff_util.cc
+++ b/modules/io/src/img/tiff_util.cc
@@ -41,7 +41,7 @@ void tiff_warning_handler(const char *mod, const char* fmt, va_list ap)
   LOG_INFO(mod << ": " << message);
 }
 
-INTNN_T CustomTIFFReadProcIStream(void* thandle, void* tdata, INTNN_T tsize)
+tsize_t CustomTIFFReadProcIStream(thandle_t thandle, tdata_t tdata, tsize_t tsize)
 {
    std::istream* file= reinterpret_cast<std::istream*>(thandle);
    char* data= reinterpret_cast<char*>(tdata);
@@ -49,29 +49,29 @@ INTNN_T CustomTIFFReadProcIStream(void* thandle, void* tdata, INTNN_T tsize)
    return file->gcount();
 }
 
-INTNN_T CustomTIFFReadProcOStream(void* thandle, void* tdata, INTNN_T tsize)
+tsize_t CustomTIFFReadProcOStream(thandle_t thandle, tdata_t tdata, tsize_t tsize)
 {
   assert(false);
   return -1;
 }
 
-INTNN_T CustomTIFFWriteProcIStream(void* thandle, void* tdata, INTNN_T tsize)
+tsize_t CustomTIFFWriteProcIStream(thandle_t thandle, tdata_t tdata, tsize_t tsize)
 {
   assert(false);
   return -1;
 }
 
-INTNN_T CustomTIFFWriteProcOStream(void* thandle, void* tdata, INTNN_T tsize)
+tsize_t CustomTIFFWriteProcOStream(thandle_t thandle, tdata_t tdata, tsize_t tsize)
 {
    std::ostream* file= reinterpret_cast<std::ostream*>(thandle);
    char* data= reinterpret_cast<char*>(tdata);
-   INTNN_T before = file->tellp();
+   tsize_t before = file->tellp();
    file->write(data,tsize);
-   INTNN_T after = file->tellp();
+   tsize_t after = file->tellp();
    return after-before;
 }
 
-UINTNN_T CustomTIFFSeekProcIStream(void* thandle, UINTNN_T toff, int dir)
+toff_t CustomTIFFSeekProcIStream(thandle_t thandle, toff_t toff, int dir)
 {
   std::istream* stream= reinterpret_cast<std::istream*>(thandle);
 
@@ -89,7 +89,7 @@ UINTNN_T CustomTIFFSeekProcIStream(void* thandle, UINTNN_T toff, int dir)
   return stream->rdstate();
 }
 
-UINTNN_T CustomTIFFSeekProcOStream(void* thandle, UINTNN_T toff, int dir)
+toff_t CustomTIFFSeekProcOStream(thandle_t thandle, toff_t toff, int dir)
 {
   std::ostream* stream= reinterpret_cast<std::ostream*>(thandle);
 
@@ -106,38 +106,38 @@ UINTNN_T CustomTIFFSeekProcOStream(void* thandle, UINTNN_T toff, int dir)
   return stream->rdstate();
 }
 
-int CustomTIFFCloseProc(void* thandle)
+int CustomTIFFCloseProc(thandle_t thandle)
 {
   return 0;
 }
 
-UINTNN_T CustomTIFFSizeProcIStream(void* thandle)
+toff_t CustomTIFFSizeProcIStream(thandle_t thandle)
 {
    std::istream* stream= reinterpret_cast<std::istream*>(thandle);
-   UINTNN_T curr_pos = stream->tellg();
+   toff_t curr_pos = stream->tellg();
    stream->seekg(0,std::ios::end);
-   UINTNN_T size = stream->tellg();
+   toff_t size = stream->tellg();
    stream->seekg(curr_pos,std::ios::beg);
    return size;
 }
 
-UINTNN_T CustomTIFFSizeProcOStream(void* thandle)
+toff_t CustomTIFFSizeProcOStream(thandle_t thandle)
 {
    std::ostream* stream= reinterpret_cast<std::ostream*>(thandle);
-   UINTNN_T curr_pos = stream->tellp();
+   toff_t curr_pos = stream->tellp();
    stream->seekp(0,std::ios::end);
-   UINTNN_T size = stream->tellp();
+   toff_t size = stream->tellp();
    stream->seekp(curr_pos,std::ios::beg);
    return size;
 }
 
-int CustomTIFFMapFileProc(void* thandle, void** tdata, UINTNN* toff)
+int CustomTIFFMapFileProc(thandle_t thandle, tdata_t* tdata, toff_t* toff)
 {
   assert(false);
   return(0);
 }
 
-void CustomTIFFUnmapFileProc(void* thandle, void* tdata, UINTNN toff)
+void CustomTIFFUnmapFileProc(thandle_t thandle, tdata_t tdata, toff_t toff)
 {
   assert(false);
 }
diff --git a/modules/io/src/img/tiff_util.hh b/modules/io/src/img/tiff_util.hh
index b2aca3386a39f3587ba4fb31eb892147932940b7..76de383f7c2e227fea4bd4acd6d5f6e800417fc7 100644
--- a/modules/io/src/img/tiff_util.hh
+++ b/modules/io/src/img/tiff_util.hh
@@ -27,18 +27,6 @@
 #include <ost/img/alg/normalizer_factory.hh>
 #include <ost/io/img/image_format.hh>
 
-#if defined(TIFFLIB_VERSION) && TIFFLIB_VERSION >= 20111221 
-#  define INTNN_T int64_t
-#  define UINTNN uint64
-#  define UINTNN_T uint64_t
-#  define COMPLEXINTNN_T complexint64_t
-#else
-#  define INTNN_T int32_t
-#  define UINTNN uint32
-#  define UINTNN_T uint32_t
-#  define COMPLEXINTNN_T complexint32_t
-#endif
-
 namespace ost { namespace io { namespace detail {
 /// \internal
 typedef void (*TIFFWarningHandler)(const char*, const char*, va_list);
@@ -60,7 +48,7 @@ struct tiff_warning_handler_wrapper {
 };
 
 /// \internal
-class COMPLEXINTNN_T:public std::complex<INTNN_T>{
+class complexint32:public std::complex<int32>{
 public:
 
   operator std::complex<Real>()
@@ -90,33 +78,31 @@ public:
 };
 
 /// \internal
-INTNN_T CustomTIFFReadProcIStream(void* thandle, void* tdata, INTNN_T tsize);
-/// \internal
-INTNN_T CustomTIFFReadProcIStream(void* thandle, void* tdata, INTNN_T tsize);
+tsize_t CustomTIFFReadProcIStream(thandle_t thandle, tdata_t  tdata, tsize_t tsize);
 /// \internal
-INTNN_T CustomTIFFReadProcOStream(void* thandle, void* tdata, INTNN_T tsize);
+tsize_t CustomTIFFReadProcOStream(thandle_t thandle, tdata_t  tdata, tsize_t tsize);
 /// \internal
-INTNN_T CustomTIFFWriteProcIStream(void* thandle, void* tdata, INTNN_T tsize);
+tsize_t CustomTIFFWriteProcIStream(thandle_t thandle, tdata_t  tdata, tsize_t tsize);
 /// \internal
-INTNN_T CustomTIFFWriteProcOStream(void* thandle, void* tdata, INTNN_T tsize);
+tsize_t CustomTIFFWriteProcOStream(thandle_t thandle, tdata_t  tdata, tsize_t tsize);
 /// \internal
-UINTNN_T CustomTIFFSeekProcIStream(void* thandle, UINTNN_T toff, int dir);
+toff_t CustomTIFFSeekProcIStream(thandle_t thandle, toff_t toff, int dir);
 /// \internal
-UINTNN_T CustomTIFFSeekProcOStream(void* thandle, UINTNN_T toff, int dir);
+toff_t CustomTIFFSeekProcOStream(thandle_t thandle, toff_t toff, int dir);
 /// \internal
-int CustomTIFFCloseProc(void* thandle);
+int CustomTIFFCloseProc(thandle_t thandle);
 /// \internal
-UINTNN_T CustomTIFFSizeProcIStream(void* thandle);
+toff_t CustomTIFFSizeProcIStream(thandle_t thandle);
 /// \internal
-UINTNN_T CustomTIFFSizeProcOStream(void* thandle);
+toff_t CustomTIFFSizeProcOStream(thandle_t thandle);
 /// \internal
-int CustomTIFFMapFileProc(void* thandle, void** tdata, UINTNN* toff);
+int CustomTIFFMapFileProc(thandle_t thandle, tdata_t* tdata, toff_t* toff);
 /// \internal
-void CustomTIFFUnmapFileProc(void* thandle, void* tdata, UINTNN toff);
+void CustomTIFFUnmapFileProc(thandle_t thandle, tdata_t tdata, toff_t toff);
 
 /// \internal
 template<typename IN_TYPE,typename OUT_TYPE, class IST>
-void do_tiff_read(tdata_t buf,uint16 rps, UINTNN_T width, IST* is,int& current_row, int spp)
+void do_tiff_read(tdata_t buf,unsigned int rps, unsigned int width, IST* is,unsigned int& current_row, uint16 spp)
 {
   IN_TYPE* dp = static_cast<IN_TYPE*>(buf);
   for(uint r=0;r<rps;r++) {
@@ -129,7 +115,7 @@ void do_tiff_read(tdata_t buf,uint16 rps, UINTNN_T width, IST* is,int& current_r
 
 /// \internal
 template<typename IN_TYPE,typename OUT_TYPE, class IST>
-void do_tiff_write(TIFF *tif, IST* is,UINTNN_T rowsperstrip,UINTNN_T width,UINTNN_T height, UINTNN_T strip,const  img::NormalizerPtr& nptr)
+void do_tiff_write(TIFF *tif, IST* is,unsigned int rowsperstrip,unsigned int width, unsigned int height, unsigned int strip,const  img::NormalizerPtr& nptr)
 {
   uint datalength=rowsperstrip*width;
   if((strip+1)*rowsperstrip>height){
diff --git a/modules/mol/alg/doc/molalg.rst b/modules/mol/alg/doc/molalg.rst
index 9455d58dee59c029ea8d37e3d82804f63b625021..66b14294022870a6dfe967ce407994388ef6679d 100644
--- a/modules/mol/alg/doc/molalg.rst
+++ b/modules/mol/alg/doc/molalg.rst
@@ -374,6 +374,22 @@ The following function detects steric clashes in atomic structures. Two atoms ar
   :returns: :class:`~ost.mol.alg.ClashingDistances` and :class:`~ost.mol.alg.StereoChemicalParams` respectively
 
 
+.. function:: ResidueNamesMatch(probe,reference)
+
+  The function requires a reference structure and a probe structure. The function checks that all the 
+  residues in the reference structure that appear in the probe structure (i.e., that have the 
+  same ResNum) are of the same residue type. Chains are comapred by order, not by chain name 
+  (i.e.: the first chain of the reference will be compared with the first chain of the probe 
+  structure, etc.)
+
+  :param probe: the structure to test
+  :type probe: :class:`~ost.mol.EntityView`
+  :param reference: the reference structure
+  :type reference: :class:`~ost.mol.EntityView`
+
+  :returns: true if the residue names are the same, false otherwise
+
+
 .. _traj-analysis:
 
 Trajectory Analysis
diff --git a/modules/mol/alg/pymod/wrap_mol_alg.cc b/modules/mol/alg/pymod/wrap_mol_alg.cc
index 72a67e4d09299d1e0ce88c0d839e2fe1b599492a..08ad6631efe89ce483e9cc653c2baec321db6927 100644
--- a/modules/mol/alg/pymod/wrap_mol_alg.cc
+++ b/modules/mol/alg/pymod/wrap_mol_alg.cc
@@ -23,6 +23,8 @@
 #include <ost/mol/alg/local_dist_diff_test.hh>
 #include <ost/mol/alg/superpose_frames.hh>
 #include <ost/mol/alg/filter_clashes.hh>
+#include <ost/mol/alg/consistency_checks.hh>
+
 using namespace boost::python;
 using namespace ost;
 
@@ -159,5 +161,8 @@ BOOST_PYTHON_MODULE(_ost_mol_alg)
   def("IsStandardResidue",&mol::alg::IsStandardResidue);
   def("PrintGlobalRDMap",&mol::alg::PrintGlobalRDMap);
   def("PrintResidueRDMap",&mol::alg::PrintResidueRDMap);
-  
+ 
+  def("ResidueNamesMatch",&mol::alg::ResidueNamesMatch);
+
+ 
 }
diff --git a/modules/mol/alg/src/CMakeLists.txt b/modules/mol/alg/src/CMakeLists.txt
index b91dd1e42a5f975e29a192666d847e1c56b33115..eca9aa6e892d9a8bd463be00b1e2f01fc3e59125 100644
--- a/modules/mol/alg/src/CMakeLists.txt
+++ b/modules/mol/alg/src/CMakeLists.txt
@@ -9,6 +9,7 @@ set(OST_MOL_ALG_HEADERS
   clash_score.hh
   trajectory_analysis.hh
   structure_analysis.hh
+  consistency_checks.hh
 )
 
 set(OST_MOL_ALG_SOURCES
@@ -21,6 +22,7 @@ set(OST_MOL_ALG_SOURCES
   construct_cbeta.cc
   trajectory_analysis.cc
   structure_analysis.cc
+  consistency_checks.cc
 )
 
 set(MOL_ALG_DEPS ost_mol ost_seq)
diff --git a/modules/mol/alg/src/consistency_checks.cc b/modules/mol/alg/src/consistency_checks.cc
new file mode 100644
index 0000000000000000000000000000000000000000..371f3c37b6b8fbc921ecd3a82fa647251992b216
--- /dev/null
+++ b/modules/mol/alg/src/consistency_checks.cc
@@ -0,0 +1,67 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2011 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/chain_view.hh>
+#include <ost/mol/residue_view.hh>
+#include <ost/mol/alg/consistency_checks.hh>
+
+namespace ost { namespace mol { namespace alg {
+  
+/// \brief Checks that residue types with the same ResNum in the two structures match
+///
+/// Requires a reference structure and a probe structure. The function checks that all the 
+/// residues in the reference structure that appear in the probe structure (i.e., that have the 
+/// same ResNum) are of the same residue type. Chains are paired by index, not by chain name
+/// (i.e., the first chain of the reference will be compared with the first chain of the probe,
+/// the second with the second, etc.)
+
+
+
+
+
+bool ResidueNamesMatch (const mol::EntityView& probe, const mol::EntityView& reference)
+{
+  bool return_value = true;
+  ChainViewList ref_chains = reference.GetChainList();
+  ChainViewList probe_chains = probe.GetChainList();
+  for (unsigned int rci = 0; rci < ref_chains.size(); ++rci) {
+     ChainView ref_chain= ref_chains[rci];
+     if (rci<probe_chains.size()) {
+      ChainView probe_chain = probe_chains[rci];     
+      ResidueViewList ref_residues = ref_chain.GetResidueList();       
+      for (ResidueViewList::iterator rri=ref_residues.begin(), rre=ref_residues.end(); rri!=rre; ++rri) {
+        ResidueView probe_residue = probe_chain.FindResidue(rri->GetNumber());
+        if (probe_residue.IsValid()) {
+          if (probe_residue.GetName()!=rri->GetName()) {
+            return_value = false;
+            LOG_VERBOSE("Name mismatch for residue " << probe_residue.GetNumber() << " in chain " << rci);
+            LOG_VERBOSE("In reference: " << rri->GetName() << ", in compared structure: " << probe_residue.GetName());
+          } 
+        }            
+      }
+    }
+  }          
+  return return_value;
+}
+ 
+}}}
+
+
+
diff --git a/modules/mol/alg/src/consistency_checks.hh b/modules/mol/alg/src/consistency_checks.hh
new file mode 100644
index 0000000000000000000000000000000000000000..77cffda1ce3639c37111cc0b7d8fa120015e9958
--- /dev/null
+++ b/modules/mol/alg/src/consistency_checks.hh
@@ -0,0 +1,41 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2011 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_CONSISTENCY_CHECKS_HH
+#define OST_MOL_CONSISTENCY_CHECKS_HH
+
+#include <ost/mol/entity_view.hh>
+#include <ost/mol/alg/module_config.hh>
+
+namespace ost { namespace mol { namespace alg {
+  
+/// \brief Checks that residue types with the same ResNum in the two structures match
+///
+/// Requires a reference structure and a probe structure. The function checks that all the 
+/// residues in the reference structure that appear in the probe structure (i.e., that have the 
+/// same ResNum) are of the same residue type. Chains are comapred by order, not by chain name 
+/// (i.e.: the first chain of the reference will be compared with the first chain of the probe 
+/// structure, etc.)
+
+bool DLLEXPORT_OST_MOL_ALG ResidueNamesMatch (const mol::EntityView& probe, const mol::EntityView& reference);
+  
+}}}
+
+#endif
+
+
diff --git a/modules/mol/alg/src/lddt.cc b/modules/mol/alg/src/lddt.cc
index a2c5aedb9f161b234d3381ca128d755d09eb7201..15add8e111bf49eb1aa2cee6a00d3e7c7723d7eb 100644
--- a/modules/mol/alg/src/lddt.cc
+++ b/modules/mol/alg/src/lddt.cc
@@ -37,6 +37,7 @@
 #include <ost/mol/iterator.hh>
 #include <ost/platform.hh>
 #include <ost/log.hh>
+#include <ost/mol/alg/consistency_checks.hh>
 
 #if defined(__APPLE__)
 #include <mach-o/dyld.h>
@@ -94,6 +95,8 @@ void usage()
   std::cerr << "   -r <value> distance inclusion radius" << std::endl;
   std::cerr << "   -i <value> sequence separation" << std::endl;
   std::cerr << "   -e         print version" << std::endl;
+  std::cerr << "   -x         ignore residue name consistency checks" << std::endl;
+
 }
 
 // computes coverage
@@ -165,8 +168,8 @@ int main (int argc, char **argv)
 {
   // sets some default values for parameters
   String version = "1.2";
-  Real bond_tolerance = 15.0;
-  Real angle_tolerance = 15.0;
+  Real bond_tolerance = 12.0;
+  Real angle_tolerance = 12.0;
   Real radius=15.0; 
   int sequence_separation = 0;
 
@@ -179,12 +182,14 @@ int main (int argc, char **argv)
   String sel;
   String custom_path;
   bool structural_checks=false;
+  bool consistency_checks=true;
   po::options_description desc("Options");
   desc.add_options()
     ("calpha,c", "consider only calpha atoms")
     ("sel,s", po::value<String>(&sel)->default_value(""), "selection performed on reference structure")
     ("tolerant,t", "fault tolerant mode")
     ("structural-checks,f", "perform stereo-chemical and clash checks")
+    ("ignore-consistency-checks,x", "ignore residue name consistency checks")
     ("version,e", "version")
     ("parameter-file,p", po::value<String>(), "stereo-chemical parameter file")
     ("verbosity,v", po::value<int>(), "verbosity level")
@@ -231,6 +236,9 @@ int main (int argc, char **argv)
   if (vm.count("structural-checks")) {
     structural_checks=true;
   }
+  if (vm.count("ignore-consistency-checks")) {
+    consistency_checks=false;
+  }
   if (vm.count("tolerant")) {
     profile.fault_tolerant=true;
   }
@@ -277,6 +285,8 @@ int main (int argc, char **argv)
   cutoffs.push_back(1.0);
   cutoffs.push_back(2.0);
   cutoffs.push_back(4.0);
+
+  std::vector<EntityView> ref_list;  
     
   // loads the reference file and creates the list of distances to check in lddt    
   // if the reference file is a comma-separated list of files, switches to multi-
@@ -292,10 +302,10 @@ int main (int argc, char **argv)
     if (!ref) {
       exit(-1);
     }  
+    ref_list.push_back(ref.CreateFullView());
     glob_dist_list = CreateDistanceList(ref.CreateFullView(),radius);  
   } else {
     std::cout << "Multi-reference mode: On" << std::endl;  
-    std::vector<EntityView> ref_list;  
     for (std::vector<StringRef>::const_iterator ref_file_split_sr_it = ref_file_split_sr.begin();
          ref_file_split_sr_it != ref_file_split_sr.end();++ref_file_split_sr_it) {
       String ref_filename = ref_file_split_sr_it->str();  
@@ -346,6 +356,19 @@ int main (int argc, char **argv)
     }
     EntityView v=model.CreateFullView();
 
+    for (std::vector<EntityView>::const_iterator ref_list_it = ref_list.begin();
+         ref_list_it != ref_list.end(); ++ref_list_it) {
+      bool cons_check = ResidueNamesMatch(v,*ref_list_it);
+      if (cons_check==false) {
+        if (consistency_checks==true) {
+          LOG_ERROR("Residue names in model: " << files[i] << " are inconsistent with one or more references");
+          exit(-1);            
+        } else {
+          LOG_WARNING("Residue names in model: " << files[i] << " are inconsistent with one or more references");
+        }   
+      } 
+    }
+
     boost::filesystem::path pathstring(files[i]);
 
     String filestring=BFPathToString(pathstring);
diff --git a/modules/mol/alg/tests/CMakeLists.txt b/modules/mol/alg/tests/CMakeLists.txt
index 1008a3578e384b05160bf5ea4a127d1be693b349..758bbbe10df71687391cac11a0425a253b94dc27 100644
--- a/modules/mol/alg/tests/CMakeLists.txt
+++ b/modules/mol/alg/tests/CMakeLists.txt
@@ -1,6 +1,7 @@
 set(OST_MOL_ALG_UNIT_TESTS
   test_superposition.cc
   tests.cc
+  test_consistency_checks.cc
   test_convenient_superpose.py
 )
 
diff --git a/modules/mol/alg/tests/test_consistency_checks.cc b/modules/mol/alg/tests/test_consistency_checks.cc
new file mode 100644
index 0000000000000000000000000000000000000000..aad198febf3decc69d591cb16058cfe9d6e07a24
--- /dev/null
+++ b/modules/mol/alg/tests/test_consistency_checks.cc
@@ -0,0 +1,72 @@
+//------------------------------------------------------------------------------
+// This file is part of the OpenStructure project <www.openstructure.org>
+//
+// Copyright (C) 2008-2011 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 Valerio Mariani
+ */
+#define BOOST_TEST_MODULE ost_mol_alg
+#include <boost/test/unit_test.hpp>
+#include <boost/test/auto_unit_test.hpp>
+
+#include <ost/mol/mol.hh>
+#include <ost/mol/alg/consistency_checks.hh>
+
+using namespace ost::mol;
+using namespace ost::mol::alg;
+
+
+BOOST_AUTO_TEST_SUITE( mol_alg );
+
+BOOST_AUTO_TEST_CASE(consistency_check) 
+{
+
+  EntityHandle a=CreateEntity();
+  XCSEditor eda=a.EditXCS();
+  ChainHandle ca=eda.InsertChain("A");
+  ResidueHandle r1a = eda.AppendResidue(ca, "ALA",1);
+  ResidueHandle r2a = eda.AppendResidue(ca, "TYR",2);
+  ResidueHandle r3a = eda.AppendResidue(ca, "LEU",3);
+  ResidueHandle r4a = eda.AppendResidue(ca, "GLY",4);
+  ChainHandle ca2=eda.InsertChain("C");
+  ResidueHandle r1a2 = eda.AppendResidue(ca2, "PRO",1);
+
+
+  EntityHandle b=CreateEntity();
+  XCSEditor edb=b.EditXCS();
+  ChainHandle cb=edb.InsertChain("A");
+  ResidueHandle r1b = edb.AppendResidue(cb, "ALA",1);
+  ResidueHandle r2b = edb.AppendResidue(cb, "TYR",2);
+  ResidueHandle r3b = edb.AppendResidue(cb, "LEU",3);
+  ResidueHandle r4b = edb.AppendResidue(cb, "GLY",4);
+  ResidueHandle r5b = edb.AppendResidue(cb, "PRO",5);
+
+
+  EntityHandle c=CreateEntity();
+  XCSEditor edc=c.EditXCS();
+  ChainHandle cc=edc.InsertChain("A");
+  ResidueHandle r1c = edc.AppendResidue(cc, "ALA",1);
+  ResidueHandle r2c = edc.AppendResidue(cc, "PRO",2);
+  ResidueHandle r3c = edc.AppendResidue(cc, "LEU",3);
+  ResidueHandle r4c = edc.AppendResidue(cc, "GLY",4);
+   
+  BOOST_CHECK(ost::mol::alg::ResidueNamesMatch(a.CreateFullView(),b.CreateFullView())==true);   
+  BOOST_CHECK(ost::mol::alg::ResidueNamesMatch(c.CreateFullView(),b.CreateFullView())==false);    
+}
+
+BOOST_AUTO_TEST_SUITE_END();
diff --git a/modules/mol/base/src/chem_type.hh b/modules/mol/base/src/chem_type.hh
index eac806433400daeb1ead20ecf88ddff558b64fc7..ff3a6b059241ebd76a9e9b77512fd87bc38147fc 100644
--- a/modules/mol/base/src/chem_type.hh
+++ b/modules/mol/base/src/chem_type.hh
@@ -52,7 +52,7 @@ struct ChemType {
   }
 
   bool operator!=(const ChemType& cc) const {
-    return this->operator!=(cc);
+    return cc.chem_type_!=chem_type_;
   }
 
   bool IsIon() const {
diff --git a/scripts/dng.in b/scripts/dng.in
index 41e31bd636c0193f83bb87671df25e0feed39733..d1d7096fca8c777e211d61e462b9d5709844f5f4 100755
--- a/scripts/dng.in
+++ b/scripts/dng.in
@@ -26,6 +26,6 @@ else
   SCRIPT_NAME="$0"
 fi
 BIN_DIR=`dirname "$SCRIPT_NAME"`
-source $BIN_DIR/../@LIBEXEC_PATH@/ost_config
+source "$BIN_DIR/../@LIBEXEC_PATH@/ost_config"
 
 $BIN_DIR/../@LIBEXEC_PATH@/gosty $DNG_INITDIR/init.py dng $opts
diff --git a/scripts/ost.in b/scripts/ost.in
index 407daed10f8d2b6fed92f1724c9c4b369bef0244..bea69d9ec23a36cc1912b9457938c31e8d898ea6 100755
--- a/scripts/ost.in
+++ b/scripts/ost.in
@@ -29,7 +29,7 @@ else
 fi
 BIN_DIR=`dirname "$SCRIPT_NAME"`
 
-source $BIN_DIR/../@LIBEXEC_PATH@/ost_config
+source "$BIN_DIR/../@LIBEXEC_PATH@/ost_config"
 
 $pyexec $interactive "$DNG_ROOT/@LIBDIR@/python@PYTHON_VERSION@/site-packages/init_cl.py" $opts
 RC=$?